https://github.com/jcchavezs/mdctx
Mapped Diagnostic Context for logging in golang
https://github.com/jcchavezs/mdctx
go golang logging mdc observability
Last synced: 8 months ago
JSON representation
Mapped Diagnostic Context for logging in golang
- Host: GitHub
- URL: https://github.com/jcchavezs/mdctx
- Owner: jcchavezs
- License: mit
- Created: 2018-10-23T18:41:17.000Z (over 7 years ago)
- Default Branch: master
- Last Pushed: 2019-07-10T16:32:34.000Z (almost 7 years ago)
- Last Synced: 2025-10-09T19:31:53.475Z (8 months ago)
- Topics: go, golang, logging, mdc, observability
- Language: Go
- Homepage:
- Size: 12.7 KB
- Stars: 6
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# mdctx
[](https://travis-ci.com/jcchavezs/mdctx)
[](https://goreportcard.com/report/github.com/jcchavezs/mdctx)
[](https://godoc.org/github.com/jcchavezs/mdctx)
Mapped Diagnostic Context (MDC) for Go logging
The idea of Mapped Diagnostic Context is to provide a way to enrich log messages with pieces of information that could be not available in the scope where the logging actually occurs, but that can be indeed useful to better track the execution of the program.
## Usage
```go
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Header.Get(RequestIDHeader)
if val != "" {
ctx := mdctx.Add(r.Context(), "request_id", val)
r = r.WithContext(ctx)
}
next.ServeHTTP(w, r)
})
}
```
```go
func (r *repository) DoSomething(ctx context.Context, ...) {
logger := mdctx.With(ctx, r.logger)
...
logger.Log("key", "value")
}
```
## Providers
Providers allows you to include additional context to the logs coming from other
sources. E.g. if a middleware include the `request_id` in the context under a private
key, you can use the API of that middleware to inject that `request_id` in the mdc.
```go
package requestIDMiddleware
type reqIDKey string
func Middleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
val := r.Header.Get(RequestIDHeader)
if val != "" {
r.WithContext(context.WithValue(r.Context(), reqIDKey, val))
}
next.ServeHTTP(w, r)
})
}
```
```go
package requestID
func Provider(ctx context.Context) context.Context {
return context.WithValue(ctx, "request_id", ctx.Value(reqIDKey))
}
```
```go
package main
func main() {
mdctx.RegisterProvider(requestID.Provider)
}
```