https://github.com/trackit/jsonlog
A structured logger for Go
https://github.com/trackit/jsonlog
Last synced: about 1 year ago
JSON representation
A structured logger for Go
- Host: GitHub
- URL: https://github.com/trackit/jsonlog
- Owner: trackit
- License: mit
- Created: 2017-10-05T19:29:50.000Z (over 8 years ago)
- Default Branch: master
- Last Pushed: 2021-07-30T14:30:51.000Z (almost 5 years ago)
- Last Synced: 2023-08-12T04:13:32.872Z (almost 3 years ago)
- Language: Go
- Size: 10.7 KB
- Stars: 2
- Watchers: 6
- Forks: 1
- Open Issues: 3
-
Metadata Files:
- Readme: README.adoc
- License: LICENSE
Awesome Lists containing this project
README
jsonlog
=======
Victor Schubert
v1.0, 2017-10-05
_jsonlog_ is a simple Go logger. It produces structured logs using JSON and can
also output arbitrary data taken as an argument and from a `context.Context`.
== Usage
=== Logging
The module provides a default logger which logs on the standard output.
[source,go]
----
package main
import "github.com/trackit/jsonlog"
func main() {
jsonlog.DefaultLogger.Info("Info log message", nil)
jsonlog.DefaultLogger.Warning("Warning with data", map[string]int{ "foobar": 42 })
}
----
This code produces the following output (the JSON objects were prettified, the
library outputs each object on a single line and without unnecessary spaces):
[source,json]
----
{
"message": "Info log message",
"level": "info",
"time": "2017-10-05T21:07:58.115210089+02:00"
}
{
"message": "Warning with data",
"level": "warning",
"time": "2017-10-05T21:07:58.115320884+02:00",
"data": {
"foobar": 42
}
}
----
=== Choosing the log level
The logger has four log levels: debug, info, warning and error. Each message
has a `"level"` field to indicate the message's level.
[source,go]
----
package main
import "github.com/trackit/jsonlog"
func main() {
logger := jsonlog.DefaultLogger.WithLogLevel(jsonlog.LogLevelDebug)
logger.Debug("Debug message. Only prints with adequate log level.", nil)
}
----
=== Using values from a context
The Go standard library provides the `context` module to propagate
cancellation, enforce timeouts and hold data about the current context.
_jsonlog_ can make use of those values.
[source,go]
----
package main
import (
"context"
"math/rand"
"github.com/trackit/jsonlog"
)
const (
runId = iota
)
func main() {
ctx := context.WithValue(context.Background(), runId, rand.Int63())
logger := jsonlog.DefaultLogger.WithContext(ctx).WithContextKey(runId, "runId")
logger.Info("Log with context", nil)
}
----
A `Logger` with a `Context` and registered context keys will include the
context values in each message; the previous code would produce the following
log: (the JSON object was prettified)
[source,go]
----
{
"message": "Log with context",
"level": "info",
"time": "2017-10-05T21:18:49.973938562+02:00",
"context": {
"runId": 5577006791947779410
}
}
----