https://github.com/mashiike/go-logx
logx is a go package to extend the standard logging package "log" to context
https://github.com/mashiike/go-logx
Last synced: 3 months ago
JSON representation
logx is a go package to extend the standard logging package "log" to context
- Host: GitHub
- URL: https://github.com/mashiike/go-logx
- Owner: mashiike
- License: mit
- Created: 2022-06-11T05:24:41.000Z (almost 3 years ago)
- Default Branch: main
- Last Pushed: 2022-06-11T08:09:56.000Z (almost 3 years ago)
- Last Synced: 2024-05-01T16:15:22.030Z (about 1 year ago)
- Language: Go
- Size: 5.86 KB
- Stars: 0
- Watchers: 1
- Forks: 0
- Open Issues: 0
-
Metadata Files:
- Readme: README.md
- License: LICENSE
Awesome Lists containing this project
README
# go-logx
[](https://godoc.org/github.com/mashiike/go-logx)



[](https://github.com/mashiike/go-logx/blob/master/LICENSE)This package extends Go's standard package `log` to context.Context.
## Usage
```go
logger := log.New(&buf, "context_logger: ", log.Lshortfile)
ctx := logx.WithLogger(context.Background(), logger)
logx.Print(ctx, "Hello World!?")
```for example: http logging middleware
```go
func main() {
middleware := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
reqID := r.Header.Get("X-Request-ID")
if reqID == "" {
reqID = "-"
}
logger := log.New(os.Stderr, " request_id:"+reqID, log.LUTC)
h.ServeHTTP(w, r.WithContext(
logx.WithLogger(r.Context(), logger),
))
})
}
http.ListenAndServe(":8080", middleware(http.HandlerFunc(handler)))
}func handler(w http.ResponseWriter, r *http.Request){
logx.Print(r.Context(), "call handler")
w.WriteHeader(http.StatusOK)
}
```## Benchmark
```shell
$ go test -bench . -benchmem -benchtime 10s
goos: darwin
goarch: amd64
pkg: github.com/mashiike/go-logx
cpu: Intel(R) Core(TM) i7-1068NG7 CPU @ 2.30GHz
BenchmarkLogDefaultLogger-8 49358439 231.9 ns/op 16 B/op 1 allocs/op
BenchmarkLogxDefaultLogger-8 48866178 276.3 ns/op 32 B/op 2 allocs/op
BenchmarkLogxContextLogger-8 47944270 277.2 ns/op 32 B/op 2 allocs/op
```