Documentation ¶
Overview ¶
Package log implements a simple logging handler.
Index ¶
- Constants
- func GetId(ctx context.Context) (string, bool)
- func New(w io.Writer, maxMsgs int) func(ctx context.Context) *slog.Logger
- type Handler
- func (h Handler) Enabled(_ context.Context, _ slog.Level) bool
- func (h Handler) Handle(r slog.Record) error
- func (h Handler) StdLogger() *stdLog.Logger
- func (h Handler) WithAttrs(attrs []slog.Attr) slog.Handler
- func (h Handler) WithGroup(name string) slog.Handler
- func (h Handler) Write(p []byte) (n int, err error)
Examples ¶
Constants ¶
const CtxKey = logContextKeyType("Ong-logID")
CtxKey is the name of the context key used to store the logID.
Variables ¶
This section is empty.
Functions ¶
func GetId ¶
GetId gets a logId either from the provided context or auto-generated. It returns the logID and true if the id came from ctx else false
func New ¶
New returns a function that returns an slog.Logger The logger is backed by a handler that stores log messages into a circular buffer. Those log messages are only flushed to the underlying io.Writer when a message with level >= slog.LevelError is logged. A unique logID is also added to the logs that acts as a correlation id of log events from diffrent components that neverthless are related.
Example ¶
package main import ( "context" "errors" "os" "github.com/komuw/ong/log" ) func main() { l := log.New(os.Stdout, 1000) hey := func(ctx context.Context) { logger := l(ctx) logger.Info("sending email", "email", "jane@example.com") logger.Error("fail", errors.New("sending email failed."), "email", "jane@example.com") } hey(context.Background()) // example output: // {"time":"2023-02-03T11:26:47.460792396Z","level":"INFO","source":"main.go:17","msg":"sending email","email":"jane@example.com","logID":"DQTXGs3HM8Xgx3yt"} // {"time":"2023-02-03T11:26:47.46080217Z","level":"ERROR","source":"main.go:18","msg":"fail","err":"sending email failed.","email":"jane@example.com","logID":"DQTXGs3HM8Xgx3yt"} }
Output:
Types ¶
type Handler ¶ added in v0.0.30
type Handler struct {
// contains filtered or unexported fields
}
Handler is an slog.Handler It stores log messages into a circular buffer. Those log messages are only flushed to the underlying io.Writer when a message with level >= slog.LevelError is logged.
func (Handler) StdLogger ¶ added in v0.0.30
StdLogger returns an unstructured logger from the Go standard library log package. That logger will use l as its output.