diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..7970236 --- /dev/null +++ b/.gitignore @@ -0,0 +1,3 @@ +coverage.out +coverage.html +*.test diff --git a/README.md b/README.md index cb99148..6432ad5 100644 --- a/README.md +++ b/README.md @@ -1,5 +1,40 @@ # applog -applog is a opinionated logger configuration. +Opinionated slog wiring for go-toolkit [app](https://gitea.auvem.com/go-toolkit/app) lifecycles. -WARNING: do not use this library, the API is not stable and I make breaking changes at random. There's a reason it's not on GitHub yet, or possibly ever tbh. +## Install + +```bash +go get gitea.auvem.com/go-toolkit/applog +``` + +## Usage + +```go +lifecycle := app.NewLifecycle(applog.AppLogOpts{ + ConsoleOutput: os.Stderr, + ConsoleLevel: slog.LevelInfo, + FileOutput: "/var/log/myapp.log", + FileLevel: slog.LevelInfo, +}.Module()) +``` + +## Outputs + +| Sink | Format | Default level | +|------|--------|---------------| +| Console (`ConsoleOutput`) | tint (human-readable) | Info | +| File (`FileOutput`) | JSON lines | Info | + +## Teardown + +On teardown the log file is closed and the lifecycle logger falls back to console-only (or discard). Logging via `lifecycle.Logger()` after teardown does not write to a closed file. + +## Migration from pre-V1 API + +| Before | After | +|--------|-------| +| `applog.Module(opts)` | `opts.Module()` | +| `LogOutput` | `ConsoleOutput` | +| `LogFile` | `FileOutput` | +| `Verbose bool` | `ConsoleLevel: slog.LevelDebug` | diff --git a/applog.go b/applog.go deleted file mode 100644 index b27d723..0000000 --- a/applog.go +++ /dev/null @@ -1,146 +0,0 @@ -package applog - -import ( - "fmt" - "io" - "log/slog" - "os" - "time" - - "gitea.auvem.com/go-toolkit/app" - "github.com/lmittmann/tint" - slogmulti "github.com/samber/slog-multi" -) - -// ModuleName is the name of the module provided by applog. -const ModuleName = "app logger" - -var ( - // logfile is the file handle for the log file, if any. - logfile *os.File -) - -// AppLogOpts contains options for configuring the application logger. -type AppLogOpts struct { - // ConsoleOutput is the writer for pretty-printed console logs. If nil, - // console output is disabled. Generally recommended to set this to - // os.Stderr, leaving os.Stdout for application output (usually via - // fmt.Print*). - ConsoleOutput io.Writer - - // ConsoleLevel is the minimum log level for console output. Defaults to - // slog.LevelInfo. - ConsoleLevel slog.Level - - // FileOutput is the path to a file where JSON formatted logs will be - // written. If empty, file output will be disabled. - FileOutput string - - // FileLevel is the minimum log level for file output. Defaults to - // slog.LevelInfo. - FileLevel slog.Level - - // SetDefault indicates whether to set the logger as the default logger - // for slog. Generally recommended to manage logger via app lifecycle - // instead of relying on globals. - SetDefault bool - - // Disables announcement of log module w/ log level on app start. - DisableAnnouncement bool -} - -// Module creates a new Module instance. -func (opts AppLogOpts) Module() *app.Module { - return app.NewModule(ModuleName, app.ModuleOpts{ - Setup: func(m *app.Module) error { - if opts.FileOutput == "" && opts.ConsoleOutput == nil { - return fmt.Errorf("no logging output configured") - } - - if err := setupLogger(m.Lifecycle(), opts); err != nil { - return fmt.Errorf("failed to set up logger: %w", err) - } - - return nil - }, - Teardown: func(m *app.Module) error { - teardownLogger() - return nil - }, - }) -} - -// Module creates a new Module instance for the application logger with the -// provided options. -func Module(opts AppLogOpts) *app.Module { - return opts.Module() -} - -// setupLogger initializes the multi logger with a JSON handler for file output -// and a tint handler for pretty-printed console output. May return an error -// if the log file cannot be opened. Log file should be created if it does not -// exist and appended to if it does. -func setupLogger(lifecycle *app.Lifecycle, opts AppLogOpts) error { - handlers := make([]slog.Handler, 0) - - // If log file is specified, set up JSON file logging - if opts.FileOutput != "" { - var err error - logfile, err = os.OpenFile(opts.FileOutput, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0644) - if err != nil { - return err - } - - fileHandler := slog.NewJSONHandler(logfile, &slog.HandlerOptions{ - Level: opts.FileLevel, - }) - - if !opts.DisableAnnouncement { - slog.New(fileHandler).Info("Logger initialized", "level", opts.FileLevel.String(), "output", opts.FileOutput) - } - - handlers = append(handlers, fileHandler) - } - - // If log output is specified, set up pretty-printed console logging - if opts.ConsoleOutput != nil { - consoleHandler := tint.NewHandler(opts.ConsoleOutput, &tint.Options{ - Level: opts.ConsoleLevel, - TimeFormat: time.Kitchen, - }) - - if !opts.DisableAnnouncement { - slog.New(consoleHandler).Info("Logger initialized", "level", opts.ConsoleLevel.String()) - } - - handlers = append(handlers, consoleHandler) - } - - logger := slog.New(slogmulti.Fanout(handlers...)) - lifecycle.WithLogger(logger) // set logger on lifecycle - - // optionally set logger as slog default (not recommended) - if opts.SetDefault { - slog.SetDefault(logger) - } - - return nil -} - -// teardownLogger flushes and closes the log file handle. -func teardownLogger() { - // If logfile is nil, nothing to do - if logfile == nil { - return - } - - // Flush the logger to ensure all logs are written - if err := logfile.Sync(); err != nil { - slog.Error("Error flushing log file", "err", err) - } - - // Close log file handle - if err := logfile.Close(); err != nil { - slog.Error("Error closing log file", "err", err) - } -} diff --git a/applog_test.go b/applog_test.go new file mode 100644 index 0000000..5c277ab --- /dev/null +++ b/applog_test.go @@ -0,0 +1,57 @@ +package applog_test + +import ( + "bytes" + "io" + "log/slog" + "os" + "path/filepath" + "testing" + + "gitea.auvem.com/go-toolkit/applog" + "gitea.auvem.com/go-toolkit/app" + "github.com/stretchr/testify/assert" + "github.com/stretchr/testify/require" +) + +func TestModuleConsoleOnly(t *testing.T) { + var buf bytes.Buffer + lc := app.NewLifecycle(applog.AppLogOpts{ + ConsoleOutput: &buf, + ConsoleLevel: slog.LevelDebug, + DisableAnnouncement: true, + }.Module()) + + require.NoError(t, lc.Setup()) + lc.Logger().Info("hello") + require.NoError(t, lc.Teardown()) + assert.Contains(t, buf.String(), "hello") +} + +func TestModuleRequiresOutput(t *testing.T) { + lc := app.NewLifecycle(applog.AppLogOpts{}.Module()) + err := lc.Setup() + assert.Error(t, err) +} + +func TestModuleFileAndTeardown(t *testing.T) { + dir := t.TempDir() + logPath := filepath.Join(dir, "app.log") + + lc := app.NewLifecycle(applog.AppLogOpts{ + ConsoleOutput: io.Discard, + FileOutput: logPath, + DisableAnnouncement: true, + }.Module()) + + require.NoError(t, lc.Setup()) + lc.Logger().Info("file line") + require.NoError(t, lc.Teardown()) + + // Logger should not write to closed file after teardown + lc.Logger().Info("after teardown") + + data, err := os.ReadFile(logPath) + require.NoError(t, err) + assert.Contains(t, string(data), "file line") +} diff --git a/doc.go b/doc.go new file mode 100644 index 0000000..b516a8a --- /dev/null +++ b/doc.go @@ -0,0 +1,6 @@ +// Package applog configures slog for [gitea.auvem.com/go-toolkit/app.Lifecycle] +// with optional JSON file output and tint console formatting. +// +// Teardown closes the log file and re-points the lifecycle logger to console-only +// (or discard if console is disabled) so post-teardown lifecycle logs remain safe. +package applog diff --git a/go.mod b/go.mod index ce4aa4f..a182ab7 100644 --- a/go.mod +++ b/go.mod @@ -3,12 +3,16 @@ module gitea.auvem.com/go-toolkit/applog go 1.24.0 require ( - gitea.auvem.com/go-toolkit/app v0.0.0-20250603235859-6f9e3731acf9 + gitea.auvem.com/go-toolkit/app v0.0.0-1782781086-58e5e33e18da github.com/lmittmann/tint v1.1.1 github.com/samber/slog-multi v1.4.0 + github.com/stretchr/testify v1.10.0 ) require ( + github.com/davecgh/go-spew v1.1.1 // indirect + github.com/pmezard/go-difflib v1.0.0 // indirect github.com/samber/lo v1.49.1 // indirect golang.org/x/text v0.25.0 // indirect + gopkg.in/yaml.v3 v3.0.1 // indirect ) diff --git a/go.sum b/go.sum index a983189..89ce262 100644 --- a/go.sum +++ b/go.sum @@ -2,8 +2,12 @@ gitea.auvem.com/go-toolkit/app v0.0.0-20250603235859-6f9e3731acf9 h1:MYOI+bB4IBA gitea.auvem.com/go-toolkit/app v0.0.0-20250603235859-6f9e3731acf9/go.mod h1:a7ENpOxndUdONE6oZ9MZAvG1ba2uq01x/LtcnDkpOj8= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= +github.com/kr/text v0.2.0/go.mod h1:eLer722TekiGuMkidMxC/pM04lWEeraHUUmBw8l2grE= github.com/lmittmann/tint v1.1.1 h1:xmmGuinUsCSxWdwH1OqMUQ4tzQsq3BdjJLAAmVKJ9Dw= github.com/lmittmann/tint v1.1.1/go.mod h1:HIS3gSy7qNwGCj+5oRjAutErFBl4BzdQP6cJZ0NfMwE= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e h1:fD57ERR4JtEqsWbfPhv4DMiApHyliiK5xCTNVSPiaAs= +github.com/niemeyer/pretty v0.0.0-20200227124842-a10e7caefd8e/go.mod h1:zD1mROLANZcx1PVRCS0qkT7pwLkGfwJo4zjcN/Tysno= github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= github.com/samber/lo v1.49.1 h1:4BIFyVfuQSEpluc7Fua+j1NolZHiEHEpaSEKdsH0tew= @@ -13,5 +17,9 @@ github.com/samber/slog-multi v1.4.0/go.mod h1:FsQ4Uv2L+E/8TZt+/BVgYZ1LoDWCbfCU21 github.com/stretchr/testify v1.10.0 h1:Xv5erBjTwe/5IxqUQTdXv5kgmIvbHo3QQyRwhJsOfJA= github.com/stretchr/testify v1.10.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY= golang.org/x/text v0.25.0 h1:qVyWApTSYLk/drJRO5mDlNYskwQznZmkpV2c8q9zls4= +golang.org/x/text v0.25.0/go.mod h1:WEdwpYrmk1qmdHvhkSTNPm3app7v4rsT8F2UD6+VHIA= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f h1:BLraFXnmrev5lT+xlilqcH8XK9/i0At2xKjWk4p6zsU= +gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/module.go b/module.go new file mode 100644 index 0000000..914d2ce --- /dev/null +++ b/module.go @@ -0,0 +1,51 @@ +package applog + +import ( + "io" + "log/slog" + + "gitea.auvem.com/go-toolkit/app" +) + +// ModuleName is the name of the module provided by applog. +const ModuleName = "app logger" + +// AppLogOpts contains options for configuring the application logger. +type AppLogOpts struct { + // ConsoleOutput is the writer for pretty-printed console logs. If nil, + // console output is disabled. Generally recommended to set this to + // os.Stderr, leaving os.Stdout for application output (usually via + // fmt.Print*). + ConsoleOutput io.Writer + + // ConsoleLevel is the minimum log level for console output. Defaults to + // slog.LevelInfo when console output is enabled. + ConsoleLevel slog.Level + + // FileOutput is the path to a file where JSON formatted logs will be + // written. If empty, file output is disabled. + FileOutput string + + // FileLevel is the minimum log level for file output. Defaults to + // slog.LevelInfo when file output is enabled. + FileLevel slog.Level + + // SetDefault sets slog.SetDefault to the configured logger. + SetDefault bool + + // DisableAnnouncement skips the startup log line after initialization. + DisableAnnouncement bool +} + +// Module returns an app module that configures slog for the lifecycle. +func (opts AppLogOpts) Module() *app.Module { + state := &moduleState{opts: opts} + return app.NewModule(ModuleName, app.ModuleOpts{ + Setup: func(m *app.Module) error { + return state.setup(m) + }, + Teardown: func(m *app.Module) error { + return state.teardown(m.Lifecycle()) + }, + }) +} diff --git a/setup.go b/setup.go new file mode 100644 index 0000000..1baeba2 --- /dev/null +++ b/setup.go @@ -0,0 +1,91 @@ +package applog + +import ( + "errors" + "fmt" + "log/slog" + "os" + "time" + + "gitea.auvem.com/go-toolkit/app" + "github.com/lmittmann/tint" + slogmulti "github.com/samber/slog-multi" +) + +type moduleState struct { + opts AppLogOpts + logfile *os.File + consoleHandler slog.Handler +} + +func (s *moduleState) setup(m *app.Module) error { + if s.opts.FileOutput == "" && s.opts.ConsoleOutput == nil { + return fmt.Errorf("no logging output configured") + } + + handlers := make([]slog.Handler, 0, 2) + + if s.opts.FileOutput != "" { + f, err := os.OpenFile(s.opts.FileOutput, os.O_APPEND|os.O_CREATE|os.O_WRONLY, 0o644) + if err != nil { + return err + } + s.logfile = f + + fileLevel := s.opts.FileLevel + if fileLevel == 0 && s.opts.ConsoleOutput == nil { + fileLevel = slog.LevelInfo + } + handlers = append(handlers, slog.NewJSONHandler(f, &slog.HandlerOptions{Level: fileLevel})) + } + + if s.opts.ConsoleOutput != nil { + consoleLevel := s.opts.ConsoleLevel + if consoleLevel == 0 { + consoleLevel = slog.LevelInfo + } + s.consoleHandler = tint.NewHandler(s.opts.ConsoleOutput, &tint.Options{ + Level: consoleLevel, + TimeFormat: time.Kitchen, + }) + handlers = append(handlers, s.consoleHandler) + } + + logger := slog.New(slogmulti.Fanout(handlers...)) + m.Lifecycle().WithLogger(logger) + + if s.opts.SetDefault { + slog.SetDefault(logger) + } + + if !s.opts.DisableAnnouncement { + logger.Info("Logger initialized", "module", ModuleName) + } + + return nil +} + +func (s *moduleState) teardown(lifecycle *app.Lifecycle) error { + if lifecycle != nil { + switch { + case s.consoleHandler != nil: + lifecycle.WithLogger(slog.New(s.consoleHandler)) + default: + lifecycle.WithLogger(slog.New(slog.DiscardHandler)) + } + } + + if s.logfile == nil { + return nil + } + + var err error + if syncErr := s.logfile.Sync(); syncErr != nil { + err = fmt.Errorf("flush log file: %w", syncErr) + } + if closeErr := s.logfile.Close(); closeErr != nil { + err = errors.Join(err, fmt.Errorf("close log file: %w", closeErr)) + } + s.logfile = nil + return err +}