Documentation
¶
Overview ¶
Package ctxlog provides a context key and functions for logging to a context.
Index ¶
- func Context(ctx context.Context, logger *slog.Logger) context.Context
- func ContextWith(ctx context.Context, attributes ...any) context.Context
- 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 Logger(ctx context.Context) *slog.Logger
- func NewJSONLogger(ctx context.Context, w io.Writer, opts *slog.HandlerOptions) context.Context
- func Warn(ctx context.Context, msg string, args ...any)
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func ContextWith ¶
ContextWithLoggerAttributes returns a new context with the embedded logger updated with the given logger attributes.
func Logger ¶
LoggerFromContext 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.ContextWith(ctx, "requestID", "123") logger = ctxlog.Logger(ctx) logger.Info("processing request") // Output will be JSON logs with context attributes }
Output:
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 }
Output:
Types ¶
This section is empty.
Click to show internal directories.
Click to hide internal directories.