Documentation ¶
Overview ¶
Package log is a module injecting a `*slog.Logger` instance. It provides a group of functions to log with the injected instance. See [examples_test.go](./examples_test.go) for the usage.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var ( // Module for injecting `*slog.Logger` Module = module.New[*slog.Logger]() // TextLogger provides a instance with `slog.TextHandler` logging to `os.Stderr` TextLogger = Module.ProvideWithFunc(func(ctx context.Context) (*slog.Logger, error) { handler := slog.NewTextHandler(os.Stderr, nil) return slog.New(handler), nil }) // JSONLogger provides a instance with `slog.JSONHandler` logging to `os.Stderr` JSONLogger = Module.ProvideWithFunc(func(ctx context.Context) (*slog.Logger, error) { handler := slog.NewJSONHandler(os.Stderr, nil) return slog.New(handler), nil }) )
Functions ¶
func DEBUG ¶
DEBUG logs with the injected instance at DEBUG level. If no injected `*slog.Logger`, the function does nothing.
func ERROR ¶
ERROR logs with the injected instance at ERROR level. If no injected `*slog.Logger`, the function does nothing.
func INFO ¶
INFO logs with the injected instance at INFO level. If no injected `*slog.Logger`, the function does nothing.
func WARN ¶
WARN logs with the injected instance at WARN level. If no injected `*slog.Logger`, the function does nothing.
func With ¶
With creates a new `context.Context` with new attrs. It's similar to [`slog.Logger.With()`](https://pkg.go.dev/log/slog#Logger.With).
Example ¶
package main import ( "context" "log/slog" "os" "github.com/googollee/module" "github.com/googollee/module/log" ) func removeTimeAttr(groups []string, a slog.Attr) slog.Attr { if a.Key == slog.TimeKey { return slog.Attr{} } return a } func main() { loggerOption := slog.HandlerOptions{ AddSource: false, // Remove code position from the output for predictable test output. ReplaceAttr: removeTimeAttr, } repo := module.NewRepo() // repo.Add(log.TextLogger)) in common usage // Provide a customed slog.Logger for predictable test output. repo.Add(log.Module.ProvideValue(slog.New(slog.NewTextHandler(os.Stdout, &loggerOption)))) ctx, err := repo.InjectTo(context.Background()) if err != nil { return } log.INFO(ctx, "before") { ctx := log.With(ctx, "span", "abc") log.INFO(ctx, "in") } log.INFO(ctx, "after") }
Output: level=INFO msg=before level=INFO msg=in span=abc level=INFO msg=after
Types ¶
This section is empty.