Skip to content
Snippets Groups Projects
Commit 5d7a7776 authored by John Harris's avatar John Harris
Browse files

feat: initial commit

parents
No related branches found
No related tags found
No related merge requests found
# slog
Go module for structured logging.
Configures a logger with a JSON formatter using a schema suitable for datadog log ingestion.
## Example usage
Initialise and use the logger:
```
go run src/main/main.go
```
go.mod 0 → 100644
module gitlab.nexdev.uk/pub/go-slog
go 1.20
require golang.org/x/exp v0.0.0-20230711023510-fffb14384f22
go.sum 0 → 100644
golang.org/x/exp v0.0.0-20230711023510-fffb14384f22 h1:FqrVOBQxQ8r/UwwXibI0KMolVhvFiGobSfdE33deHJM=
golang.org/x/exp v0.0.0-20230711023510-fffb14384f22/go.mod h1:FXUEEKJgO7OQYeo8N01OfiKP8RXMtf6e8aTskBGqWdc=
package main
import (
"gitlab.nexdev.uk/pub/go-slog/src/slog"
)
func main() {
logger := slog.InitLogger()
logger.Info("Logger test.")
}
package slog
import (
"golang.org/x/exp/slog"
"os"
"strings"
)
func InitLogger() *slog.Logger {
// Could set logger level via ENV vars in future.
programLevel := new(slog.LevelVar)
programLevel.Set(slog.LevelDebug)
// Attributes modified for datadog schema via HandlerOptions.ReplaceAttr
// Per recommendation at https://pkg.go.dev/golang.org/x/exp/slog#JSONHandler
// See datadog: https://docs.datadoghq.com/logs/log_configuration/attributes_naming_convention/#reserved-attributes
loggerReplace := func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "msg" {
a.Key = "message"
}
if a.Key == "time" {
a.Key = "date"
}
if a.Key == "level" {
a.Key = "status"
a.Value = slog.StringValue(strings.ToLower(a.Value.String()))
}
return a
}
logger := slog.New(slog.NewJSONHandler(os.Stdout,
&slog.HandlerOptions{Level: programLevel, AddSource: true, ReplaceAttr: loggerReplace}))
hostname, hostnameErr := os.Hostname()
if hostnameErr == nil {
logger = logger.With("host", hostname)
} else {
logger.Error("Failed to get hostname.", slog.String("error", hostnameErr.Error()))
}
logger.Info("Initialised.")
return logger
}
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment