An open API service indexing awesome lists of open source software.

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

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
}
}
----