go: change how logger is initialised
All checks were successful
continuous-integration/drone/push Build is passing

* init in run.go
* use slogger instead of slog in main
* print different messages based on whether we're initialising or
  re-initialising slogger..
This commit is contained in:
surtur 2023-08-02 15:26:51 +02:00
parent 64f330b034
commit 9ac8810f67
Signed by: wanderer
SSH Key Fingerprint: SHA256:MdCZyJ2sHLltrLBp0xQO0O1qTW9BT/xl5nXkDvhlMCI
4 changed files with 28 additions and 13 deletions

View File

@ -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)
}

View File

@ -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)
}

18
run.go
View File

@ -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":

View File

@ -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
}