diff options
Diffstat (limited to 'logging/log.go')
-rw-r--r-- | logging/log.go | 42 |
1 files changed, 41 insertions, 1 deletions
diff --git a/logging/log.go b/logging/log.go index 8dc8017..5f9af8d 100644 --- a/logging/log.go +++ b/logging/log.go @@ -81,14 +81,35 @@ func RecoverAndLog(ctx context.Context, msg string, err any) { logger.ErrorContext(ctx, msg, "Error", err, "stack", string(buf)) } +// LogSink defines where log output should be written. +// +// It is used to configure the log destination in Setup. type LogSink string const ( + // SinkStdout directs logs to the standard output (os.Stdout). SinkStdout LogSink = "stdout" + + // SinkStderr directs logs to the standard error (os.Stderr). SinkStderr LogSink = "stderr" - SinkFile LogSink = "file" + + // SinkFile directs logs to a file specified by the File field in LogConfig. + // + // If configured, the File field must be a valid path for writing logs. + SinkFile LogSink = "file" ) +// LogConfig holds configuration for the logging setup. +// +// Level specifies the minimum level for logs (e.g., slog.LevelInfo). +// +// Sink specifies the output destination (e.g., SinkStdout, SinkStderr, SinkFile). +// +// Format specifies the log format, either "json" or "text". +// If empty or "json", JSON format is used. +// +// File specifies the output file path when SinkFile is selected. +// It is required if SinkFile is used. type LogConfig struct { Level slog.Level `toml:"level"` Sink LogSink `toml:"sink"` @@ -96,6 +117,25 @@ type LogConfig struct { File string `toml:"file"` } +// Setup initializes the default slog.Logger based on the provided LogConfig. +// +// It configures the log output sink, log format, and log level. +// +// Returns an error if the configuration is invalid or if opening the log file fails. +// +// Example: +// +// cfg := LogConfig{ +// Level: slog.LevelInfo, +// Sink: SinkFile, +// Format: "json", +// File: "/var/log/myapp.log", +// } +// if err := Setup(cfg); err != nil { +// log.Fatalf("failed to configure logging: %v", err) +// } +// +// After a successful call, the global slog logger will log accordingly. func Setup(cfg LogConfig) error { var w io.Writer |