aboutsummaryrefslogtreecommitdiffhomepage
path: root/context.go
diff options
context:
space:
mode:
authorFrancis Lavoie <[email protected]>2024-01-25 14:31:15 -0500
committerGitHub <[email protected]>2024-01-25 12:31:15 -0700
commite1b9a9d7b08f6f0c21feb8edf122585891aa7099 (patch)
treeba0c6540668dbc2b4fd617022a34169493a10e59 /context.go
parent697cc593a17fcb39087161b058fc1dba8b767060 (diff)
downloadcaddy-e1b9a9d7b08f6f0c21feb8edf122585891aa7099.tar.gz
caddy-e1b9a9d7b08f6f0c21feb8edf122585891aa7099.zip
core: Add `ctx.Slogger()` which returns an `slog` logger (#5945)
Diffstat (limited to 'context.go')
-rw-r--r--context.go26
1 files changed, 26 insertions, 0 deletions
diff --git a/context.go b/context.go
index 29111a2f3..e90475b19 100644
--- a/context.go
+++ b/context.go
@@ -19,10 +19,12 @@ import (
"encoding/json"
"fmt"
"log"
+ "log/slog"
"reflect"
"github.com/caddyserver/certmagic"
"go.uber.org/zap"
+ "go.uber.org/zap/exp/zapslog"
"github.com/caddyserver/caddy/v2/internal/filesystems"
)
@@ -503,6 +505,30 @@ func (ctx Context) Logger(module ...Module) *zap.Logger {
return ctx.cfg.Logging.Logger(mod)
}
+// Slogger returns a slog logger that is intended for use by
+// the most recent module associated with the context.
+func (ctx Context) Slogger() *slog.Logger {
+ if ctx.cfg == nil {
+ // often the case in tests; just use a dev logger
+ l, err := zap.NewDevelopment()
+ if err != nil {
+ panic("config missing, unable to create dev logger: " + err.Error())
+ }
+ return slog.New(zapslog.NewHandler(l.Core(), nil))
+ }
+ mod := ctx.Module()
+ if mod == nil {
+ return slog.New(zapslog.NewHandler(Log().Core(), nil))
+ }
+
+ return slog.New(zapslog.NewHandler(
+ ctx.cfg.Logging.Logger(mod).Core(),
+ &zapslog.HandlerOptions{
+ LoggerName: string(mod.CaddyModule().ID),
+ },
+ ))
+}
+
// Modules returns the lineage of modules that this context provisioned,
// with the most recent/current module being last in the list.
func (ctx Context) Modules() []Module {