@@ -31,18 +31,47 @@ import (
3131 "github.com/containerd/log"
3232)
3333
34+ // SetupShimLogOption configures [SetupShimLog].
35+ type SetupShimLogOption func (* shimLogConfig )
36+
37+ type format int
38+
39+ const (
40+ formatText format = iota
41+ formatJSON
42+ )
43+
44+ type shimLogConfig struct {
45+ format format
46+ }
47+
48+ // WithJSONFormat sets the log output format to emit one JSON object per line.
49+ func WithJSONFormat () SetupShimLogOption {
50+ return func (c * shimLogConfig ) {
51+ c .format = formatJSON
52+ }
53+ }
54+
3455// SetupShimLog configures slog-based logging for the shim process.
3556// It opens the platform-specific log output (FIFO on Unix, named pipe
36- // on Windows), then creates a slog TextHandler and sets it as the
37- // default logger with a "component=shim" attribute.
57+ // on Windows), then creates a slog handler and sets it as the default
58+ // logger with a "component=shim" attribute.
59+ //
60+ // The handler's format defaults to text format. Pass [WithJSONFormat]
61+ // to emit JSON, which structured log consumers can unwrap directly.
3862//
3963// The base handler (without component) is stored for use by
4064// [ForwardConsoleLogs] so that forwarded records carry their own
4165// component rather than inheriting "shim".
4266//
4367// For the short-lived start and delete actions, only [log.UseSlog] is
4468// called to route logrus through slog; the log output is not opened.
45- func SetupShimLog () {
69+ func SetupShimLog (opts ... SetupShimLogOption ) {
70+ cfg := shimLogConfig {format : formatText }
71+ for _ , o := range opts {
72+ o (& cfg )
73+ }
74+
4675 log .UseSlog ()
4776
4877 var (
@@ -81,7 +110,15 @@ func SetupShimLog() {
81110 log .SetLevel ("debug" ) //nolint:errcheck
82111 }
83112
84- handler := slog .NewTextHandler (w , & slog.HandlerOptions {Level : & level }).WithAttrs (attrs )
113+ handlerOpts := & slog.HandlerOptions {Level : & level }
114+ var handler slog.Handler
115+ switch cfg .format {
116+ case formatJSON :
117+ handler = slog .NewJSONHandler (w , handlerOpts )
118+ default :
119+ handler = slog .NewTextHandler (w , handlerOpts )
120+ }
121+ handler = handler .WithAttrs (attrs )
85122 SetBaseHandler (handler )
86123 slog .SetDefault (slog .New (handler ).With ("component" , "shim" ))
87124}
0 commit comments