slogctx

package module
v0.0.1 Latest Latest
Warning

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

Go to latest
Published: Aug 10, 2023 License: MIT Imports: 2 Imported by: 0

README

slogctx

codecov Go Reference

Simple slog wrapping handler that lets you pass fields down to a slog call through context.

Example

package main

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

	"github.com/aidenwallis/slogctx"
)

var logger = slog.New(slogctx.NewHandler(slog.NewTextHandler(os.Stdout, nil)))

func main() {
	ctx := context.Background()

	logger.InfoContext(ctx, "this message has no extra fields tied to it!")

	ctx = slogctx.WithArgs(ctx, "passed_arg", "yes!")

	deeplyNestedFunc(ctx)
}

func deeplyNestedFunc(ctx context.Context) {
	logger.InfoContext(ctx, "this will attach the fields from above! particularly useful for passing through things like request URLs etc.")
}

Note that this now allows you to pass through fields using your context, rather than either deeply pushing a logger down the stack, and is compatible with the global slog functions.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func GetArgs

func GetArgs(ctx context.Context) []any

GetArgs returns the args currently found in context, or nil

func WithArgs

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

WithArgs appends slog args to context

Types

type Handler

type Handler struct {
	slog.Handler
}

Handler wraps a given slog handler, and applies extra fields to the call

func NewHandler

func NewHandler(handler slog.Handler) *Handler

NewHandler creates a new instance of Handler

func (*Handler) Handle

func (h *Handler) Handle(ctx context.Context, r slog.Record) error

Handle appends any fields from context to the record and calls the nested handler

Jump to

Keyboard shortcuts

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