dsb53973 2013-10-01 11:42
浏览 54
已采纳

寻找用于记录的呼叫或线程ID

I am reworking the logging of our little web application written in golang. Due to external requirements logging has been isolated in one place so we can potentially switch in a logging server later on. (Not my idea - I promise....) Nevertheless we are now able to log the common things like date/time, line number, user and the message mostly using parts of the standard library and a user/session struct we are passing around.

But - and here comes the question - in lower level methods it is a waste to pass in the session just to get to the user name for the sake of logging. So I would like to find something else to use to find one specific request in the log files. I am sure there are something obvious I haven't thought of.

Ideas so far:

  • Java logging frameworks can print out the thread id and that would be good enough in this case also. Just that it is called something else in golang?
  • make the user/session struct thing accesible globally somehow. (Still need to pass the session id around unless there are a thread to use as lookup key. Back to idea number 1.)
  • give up and pass the user/session struct around anyway.
  • don't log errors on the lowest level but only when the user/session struct is available. The line number won't be that good though.

We are using parts of gorilla for web things and apart from that mostly the standard library.

Suggestions and ideas about this?

  • 写回答

1条回答 默认 最新

  • duancan8382 2013-10-01 13:03
    关注

    Because of the high potential for abuse, there is no way to access an identifier for the current goroutine in Go. This may seem draconian, but this actually preserves an important property of the Go package ecosystem: it does not matter if you start a new goroutine to do something.

    That is, for any method of function F:

    F()
    

    is almost exactly equivalent to:

    done := make(chan struct{})
    go func() {
       defer close(done)
       F()
    }
    <-done
    

    (The "almost" comes from the fact that if F panics, the panic will not be caught by the original goroutine).

    This applies to logging too - if you were using the current goroutine to infer the current user, any code that started a new goroutine as above would break that assumption, and your logging would not contain the expected information.

    You'll need to pass around some kind of context.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 素材场景中光线烘焙后灯光失效
  • ¥15 请教一下各位,为什么我这个没有实现模拟点击
  • ¥15 执行 virtuoso 命令后,界面没有,cadence 启动不起来
  • ¥50 comfyui下连接animatediff节点生成视频质量非常差的原因
  • ¥20 有关区间dp的问题求解
  • ¥15 多电路系统共用电源的串扰问题
  • ¥15 slam rangenet++配置
  • ¥15 有没有研究水声通信方面的帮我改俩matlab代码
  • ¥15 ubuntu子系统密码忘记
  • ¥15 保护模式-系统加载-段寄存器