|
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 | 15 |
|
16 | 16 | > [!CAUTION] |
17 | | -> This is pre-release software. No releases have been tagged yet. |
| 17 | +> This is pre-release software. No releases have been tagged yet. |
| 18 | +
|
| 19 | + |
| 20 | +### Make sure your logs are compatible with the journal |
| 21 | + |
| 22 | +When using third-party slog libraries, you do not have control over the attributes that are passed to the logger. |
| 23 | +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. |
| 24 | +For this you can use the `ReplaceGroup` and `ReplaceAttr` fields in `Options`: |
| 25 | + |
| 26 | + |
| 27 | +```go |
| 28 | +import ( |
| 29 | + "log/slog" |
| 30 | + sloghttp "github.com/samber/slog-http" |
| 31 | + slogjournal "github.com/systemd/slog-journal" |
| 32 | +) |
| 33 | + |
| 34 | +h , err := slogjournal.NewHandler(&slogjournal.Options{ |
| 35 | + ReplaceGroup: func(k string) string { |
| 36 | + return strings.ReplaceAll(strings.ToUpper(k), "-", "_") |
| 37 | + }, |
| 38 | + ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr { |
| 39 | + a.Key = strings.ReplaceAll(strings.ToUpper(a.Key), "-", "_") |
| 40 | + return a |
| 41 | + }, |
| 42 | +}) |
| 43 | + |
| 44 | +log := slog.New(h) |
| 45 | +mux := http.NewServeMux() |
| 46 | +mux.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) { |
| 47 | + log.Info("Hello world") |
| 48 | + w.Write([]byte("Hello, world!")) |
| 49 | +}) |
| 50 | +http.ListenAndServe(":8080", sloghttp.New(log)(mux)) |
| 51 | +``` |
| 52 | + |
| 53 | + |
| 54 | + |
| 55 | + |
| 56 | + |
| 57 | + |
| 58 | + |
| 59 | + |
| 60 | + |
| 61 | +``` |
0 commit comments