|
6 | 6 | > Journald only supports keys of the form `^[A-Z_][A-Z0-9_]*$`. Any other keys will be silently dropped.
|
7 | 7 |
|
8 | 8 | ```go
|
9 |
| -h := slogjournal.NewHandler(nil) |
| 9 | +h , err := slogjournal.NewHandler(nil) |
10 | 10 | log := slog.New(h)
|
11 | 11 | log.Info("Hello, world!", "EXTRA_KEY", "5")
|
12 | 12 | log.Info("Hello, world!", slog.Group("HTTP", "METHOD", "put", "URL", "http://example.com"))
|
13 | 13 | ```
|
14 | 14 |
|
| 15 | +### Make sure your logs are compatible with the journal |
15 | 16 |
|
16 |
| -> [!CAUTION] |
17 |
| -> This is pre-release software. No releases have been tagged yet. |
| 17 | +When using third-party slog libraries, you do not have control over the attributes that are passed to the logger. |
| 18 | +Because the journal only supports keys of the form `^[A-Z_][A-Z0-9_]*$`, you may need to transform keys that don't match this pattern. |
| 19 | +For this you can use the `ReplaceGroup` and `ReplaceAttr` fields in `Options`: |
| 20 | + |
| 21 | + |
| 22 | +```go |
| 23 | +package main |
| 24 | + |
| 25 | +import ( |
| 26 | + "log/slog" |
| 27 | + sloghttp "github.com/samber/slog-http" |
| 28 | + slogjournal "github.com/systemd/slog-journal" |
| 29 | +) |
| 30 | + |
| 31 | +func main() { |
| 32 | + h , err := slogjournal.NewHandler(&slogjournal.Options{ |
| 33 | + ReplaceGroup: func(k string) string { |
| 34 | + return strings.ReplaceAll(strings.ToUpper(k), "-", "_") |
| 35 | + }, |
| 36 | + ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { |
| 37 | + a.Key = strings.ReplaceAll(strings.ToUpper(a.Key), "-", "_") |
| 38 | + return a |
| 39 | + }, |
| 40 | + }) |
| 41 | + |
| 42 | + log := slog.New(h) |
| 43 | + mux := http.NewServeMux() |
| 44 | + mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 45 | + log.Info("Hello world") |
| 46 | + w.Write([]byte("Hello, world!")) |
| 47 | + }) |
| 48 | + http.ListenAndServe(":8080", sloghttp.New(log)(mux)) |
| 49 | +} |
| 50 | +``` |
0 commit comments