Help us shape the future of Go! Take the 2026 Go Developer Survey

ctxlog

package module
v0.0.0-...-b9af9ad Latest Latest
Warning

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

Go to latest
Published: Feb 13, 2025 License: MIT Imports: 2 Imported by: 0

README

Go Reference

Ctxlog

Small package to embed/fetch logger into the context

Usage:

import (
    "context"
	"github.com/weirdgiraffe/ctxlog"
)

func foo(ctx context.Context) {
    log := ctxlog.From(ctx)
    log.Info("hello")
    bar(ctxlog.Embed(ctx, log.WithField("foo", "foo"))
}

func bar(ctx context.Context) {
    log := ctxlog.From(ctx)
    log.Info("world")
}

Right now only slog is supported, which could be inited as:

log := ctxlog.NewSlog(slog.Default())

But feel free to add whichever logger implementation which fullfils the Logger interface.

Documentation

Overview

Example
package main

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

	"github.com/weirdgiraffe/ctxlog"
)

func main() {
	opts := &slog.HandlerOptions{
		Level: slog.LevelInfo,
		ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
			if a.Key == slog.TimeKey {
				return slog.Attr{
					Key:   a.Key,
					Value: slog.TimeValue(time.Date(2025, 2, 11, 0, 0, 0, 0, time.UTC)),
				}
			}
			return a
		},
	}
	logger := slog.New(slog.NewTextHandler(os.Stdout, opts))
	log := ctxlog.NewSlog(logger)
	bgCtx := context.Background()
	log = log.With("example", "main")
	ctx := ctxlog.Embed(bgCtx, log)
	foo(ctx)

}

func foo(ctx context.Context) {
	log := ctxlog.From(ctx)
	ctx = ctxlog.Embed(ctx, log.With("foo", "foo"))
	bar(ctx)
}

func bar(ctx context.Context) {
	log := ctxlog.From(ctx)
	log.Info("Hello, World!")
}
Output:
time=2025-02-11T00:00:00.000Z level=INFO msg="Hello, World!" example=main foo=foo

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Embed

func Embed(ctx context.Context, logger Logger) context.Context

Embed adds the logger to the provided context

Types

type Level

type Level int
const (
	LevelDebug Level = -4
	LevelInfo  Level = 0
	LevelWarn  Level = 4
	LevelError Level = 8
)

type Logger

type Logger interface {
	With(args ...any) Logger
	WithGroup(name string) Logger

	Log(ctx context.Context, level Level, msg string, args ...any)

	Debug(msg string, args ...any)
	Info(msg string, args ...any)
	Warn(msg string, args ...any)
	Error(msg string, args ...any)
}

func From

func From(ctx context.Context) Logger

From returns the logger from the provided context

func NewSlog

func NewSlog(l *slog.Logger) Logger

Jump to

Keyboard shortcuts

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