ctxslog

package module
v0.0.2 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 9, 2023 License: MIT Imports: 5 Imported by: 0

README

test Go Reference

ctxslog

handler := slog.NewTextHandler(os.Stderr, &slog.HandlerOptions{ReplaceAttr: replace})
slog.SetDefault(slog.New(ctxslog.New(handler)))

ctx := context.Background()
// associate the key my_context and the value foo-bar with the context.
ctx = ctxslog.With(ctx, "my_context", "foo-bar")

slog.InfoContext(ctx, "hello", "count", 42)
slog.InfoContext(ctx, "world")
// Output:
// time=2023-08-03T18:10:20.424+09:00 level=INFO msg=hello count=42 my_context=foo-bar
// time=2023-08-03T18:10:20.424+09:00 level=INFO msg=world my_context=foo-bar

Documentation

Overview

Example
package main

import (
	"context"
	"log/slog"
	"os"

	"github.com/shogo82148/ctxslog"
)

func main() {
	// it's for testing.
	replace := func(groups []string, a slog.Attr) slog.Attr {
		// Remove time.
		if a.Key == slog.TimeKey && len(groups) == 0 {
			return slog.Attr{}
		}
		return a
	}

	handler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{ReplaceAttr: replace})
	slog.SetDefault(slog.New(ctxslog.New(handler)))

	ctx := context.Background()
	ctx = ctxslog.With(ctx, "my_context", "foo-bar")

	slog.InfoContext(ctx, "hello", "count", 42)
	slog.InfoContext(ctx, "world")

}
Output:
level=INFO msg=hello count=42 my_context=foo-bar
level=INFO msg=world my_context=foo-bar

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func New

func New(parent slog.Handler) slog.Handler

New returns a new slog.Handler that injects the attributes from the context.

func With

func With(ctx context.Context, args ...any) context.Context

With returns a new context with the given attributes. The attributes are added into the log record.

func WithAttrs

func WithAttrs(ctx context.Context, attrs ...slog.Attr) context.Context

WithAttrs is a more efficient version of With that accepts only log/slog.Attrs.

func WithLevel added in v0.0.2

func WithLevel(ctx context.Context, level slog.Level) context.Context

WithLevel configures the minimum record level that will be logged in the context.

Types

This section is empty.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL