Documentation
¶
Overview ¶
Package ctxlog provides a context key and functions for logging to a context.
Index ¶
- func Debug(ctx context.Context, msg string, args ...any)
- func Error(ctx context.Context, msg string, args ...any)
- func Info(ctx context.Context, msg string, args ...any)
- func Log(ctx context.Context, level slog.Level, msg string, args ...any)
- func LogDepth(ctx context.Context, logger *slog.Logger, level slog.Level, depth int, ...)
- func Logger(ctx context.Context) *slog.Logger
- func NewJSONLogger(ctx context.Context, w io.Writer, opts *slog.HandlerOptions) context.Context
- func NewLogLogger(ctx context.Context, level slog.Level) *log.Logger
- func Warn(ctx context.Context, msg string, args ...any)
- func WithAttributes(ctx context.Context, attributes ...any) context.Context
- func WithLogger(ctx context.Context, logger *slog.Logger) context.Context
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func LogDepth ¶
func LogDepth(ctx context.Context, logger *slog.Logger, level slog.Level, depth int, msg string, args ...any)
LogDepth logs a message at the specified level with the caller information adjusted by the provided depth.
func Logger ¶
Logger returns the logger from the given context. If no logger is set, it returns a discard logger.
Example ¶
package main
import (
"bytes"
"context"
"cloudeng.io/logging/ctxlog"
)
func main() {
// Create a context with a JSON logger
ctx := context.Background()
buf := &bytes.Buffer{}
ctx = ctxlog.NewJSONLogger(ctx, buf, nil)
// Get logger from context and use it
logger := ctxlog.Logger(ctx)
logger.Info("hello world", "user", "alice")
// Add attributes to logger
ctx = ctxlog.WithAttributes(ctx, "requestID", "123")
logger = ctxlog.Logger(ctx)
logger.Info("processing request")
// Output will be JSON logs with context attributes
}
func NewJSONLogger ¶
NewJSONLogger returns a new context with a JSON logger.
Example ¶
package main
import (
"bytes"
"context"
"log/slog"
"cloudeng.io/logging/ctxlog"
)
func main() {
// Create a new context with JSON logger
ctx := context.Background()
buf := &bytes.Buffer{}
opts := &slog.HandlerOptions{
Level: slog.LevelDebug,
}
ctx = ctxlog.NewJSONLogger(ctx, buf, opts)
// Use the logger
logger := ctxlog.Logger(ctx)
logger.Debug("debug message")
logger.Info("info message")
// Output will be JSON formatted logs
}
func NewLogLogger ¶
NewLogLogger returns a new standard library logger that logs to the provided context's logger at the specified level.
func WithAttributes ¶
WithAttributes returns a new context with the embedded logger updated with the given logger attributes.
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.