Hi Guys: 

Assume we are building a HTTP server, I think it's a pretty common 
requirement to give each request a requestId and add that requestId as a 
log field, so log generated by this request all have this unique requestId, 
so we can do a "grep" in central log system(Graylog, Splunk, ELK, etc) to 
get all logs related to this request. 

 My question is what's the best practice to achieve this in current golang? 

A solution workable for me is use context package:

1.  HTTP endpoint get requestId from HTTP header/cookie or generate a 
requestId
2.  Put uniqueId in context object (context Key/Value pair)
3.  Pass context through control flow, so each function in call chain need 
to have context as its parameter
4.  Function get requestId from context object, and store requestId in log 
entry's field

So all log generated by this request all has requestId as field

Drawbacks:

   - Each function need to have a  context parameter, even if function does 
   not need cancellation, "Context spread like virus"
   - If we don't pass context/requestId to functions, the log generated 
   inside the function is "lost" in logging system, without a requestId, we 
   cannot find them.

I can also encapsulate request in a object, which store the 
context/requestId/logger with requestId, which could alleviate we need to 
add context to each functions as parameter: 

type RequestWorker {
    // members
   //  ctx contain requestId
    ctx context
}  

func (rw *RequestWorker)DoSomething() {
   logger := getLoggerFromContext(rw.ctx)
   logger.Info(...)
   *subFunction()*
}

but logs generated in subFunction() is lost. 

Any thoughts? 

Reference: 
Related discussion on Go2 Proposal: 
proposal: Go 2: log: change Logger to be an interface 
<https://github.com/golang/go/issues/13182>
Proposal: Go 2: Create logger interface in the standard log package, with 
additional levels. Optionally add it to context package, too 
<https://github.com/golang/go/issues/28412>
Context should go away for Go 2 
<https://faiface.github.io/post/context-should-go-away-go2/> (context is 
like a virus)

-- 
You received this message because you are subscribed to the Google Groups 
"golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to golang-nuts+unsubscr...@googlegroups.com.
For more options, visit https://groups.google.com/d/optout.

Reply via email to