From 9ac8810f6764a24b165e32a59d72ae9cff5acc2f Mon Sep 17 00:00:00 2001 From: surtur Date: Wed, 2 Aug 2023 15:26:51 +0200 Subject: [PATCH] go: change how logger is initialised * init in run.go * use slogger instead of slog in main * print different messages based on whether we're initialising or re-initialising slogger.. --- config/config.go | 1 + main.go | 7 +++++-- run.go | 18 +++++++++++------- slogging/log.go | 15 +++++++++++---- 4 files changed, 28 insertions(+), 13 deletions(-) diff --git a/config/config.go b/config/config.go index 5ee3615..262b09f 100644 --- a/config/config.go +++ b/config/config.go @@ -110,6 +110,7 @@ func Load(conf string, isPath bool) (*Config, error) { slogger := slogging.Logger() // initialise if not already initialised. if slogger == nil { + /// this should never happen, as the logger is initialised in run.go. slogger = slogging.Init(true) } diff --git a/main.go b/main.go index d96d510..0a87ecd 100644 --- a/main.go +++ b/main.go @@ -7,13 +7,16 @@ import ( "os" "git.dotya.ml/mirre-mt/pcmt/slogging" - "golang.org/x/exp/slog" ) func main() { err := run() if err != nil { - l := slog.New(slog.NewJSONHandler(os.Stderr, slogging.Opts())) + l := slogging.Logger() + if l == nil { + l = slogging.Init(true) + } + l.Error("unrecoverable failure, stopping the app", "error", err) os.Exit(1) } diff --git a/run.go b/run.go index 944123f..59b1a50 100644 --- a/run.go +++ b/run.go @@ -97,6 +97,17 @@ func run() error { //nolint:gocognit printHeader() } + slogger = slogging.Logger() + if slogger == nil { + slogger = slogging.Init(true) + } + + log = *slogger // local copy. + log.Logger = log.Logger.With( + // local attrs. + slog.Group("pcmt extra", slog.String("module", "run")), + ) + // TODO: allow different configuration formats (toml, ini) // TODO: rename main.go to pcmt.go // TODO: add flake.nix @@ -120,13 +131,6 @@ func run() error { //nolint:gocognit conf, host, port, devel, version, ) - slogger = slogging.Logger() // init is performed in the config package. - log = *slogger // local copy. - log.Logger = log.Logger.With( - // local attrs. - slog.Group("pcmt extra", slog.String("module", "run")), - ) - // expected connstring form for "github.com/xiaoqidun/entps": // "file:ent?mode=memory&cache=shared&_fk=1" // and for the postgres driver "github.com/lib/pq": diff --git a/slogging/log.go b/slogging/log.go index 056562f..d275c14 100644 --- a/slogging/log.go +++ b/slogging/log.go @@ -21,9 +21,11 @@ const ( LevelError ) -var logger *Slogger - -var opts *slog.HandlerOptions +var ( + logger *Slogger + opts *slog.HandlerOptions + initialised = false +) func Opts() *slog.HandlerOptions { return opts @@ -46,7 +48,12 @@ func Init(jsonHandler bool) *Slogger { slog.SetDefault(logger.Logger) - logger.Info("slog logger initialised") + if initialised { + logger.Info("slog logger reinitialised") + } else { + initialised = true + logger.Info("slog logger initialised") + } return logger }