slogctx

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2025 License: MIT Imports: 4 Imported by: 1

README

slogctx

slogctx is a simple context logger implementation for the slog logger introduced in go 1.21

To use this module in your project run:

go get github.com/BrandonBentley/slogctx

There are a few ways to use this module.

The recommended way is to set the slog default logger to use the JSONContextHandler. This way all logs will use the context handler, which if no values are in the context, behaves as a slog.JSONHandler. See the code below for example usage:

package main

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

	"github.com/BrandonBentley/slogctx"
)

func main() {
	slog.SetDefault(slog.New(slogctx.NewJSONContextHandler(os.Stdout, nil)))

	ctx := context.Background()

	ctx = slogctx.WithAttrs(
		ctx,
		slog.String("someKey", "someVal"),
	)

	slog.InfoContext(
		ctx,
		"I have some info for you",
	)
}

Output

{
  "time": "2025-04-11T01:22:31.706502-06:00",
  "level": "INFO",
  "msg": "I have some info for you",
  "someKey": "someVal"
}

sloginit

You can also use the sloginit package provided to initialize the default slog logger with the slogctx.JSONContextHandler and not require any code for initializing

package main

import (
	"context"
	"log/slog"

	"github.com/BrandonBentley/slogctx"
	_ "github.com/BrandonBentley/slogctx/sloginit"
)

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

	ctx = slogctx.WithAttrs(
		ctx,
		slog.String("Key1", "Val1"),
	)

	slog.InfoContext(
		ctx,
		"I have some info for you",
	)
}

Output

{
  "time": "2025-04-11T01:43:33.14336-06:00",
  "level": "INFO",
  "msg": "I have some info for you",
  "Key1": "Val1"
}
No More Duplicates!

A significant update: slogctx.ContextHandler will now remove duplicate keys, keeping the last provided value, and maintains the order in which keys where added

package main

import (
	"context"
	"log/slog"

	"github.com/BrandonBentley/slogctx"
	_ "github.com/BrandonBentley/slogctx/sloginit"
)

func main() {
	firstContext := slogctx.WithAttrs(
		context.Background(),
		slog.String("Key1", "Val1"),
	)

	ctx := firstContext
	slog.ErrorContext(
		ctx,
		"Original Value",
	)

	ctx = slogctx.WithAttrs(
		ctx,
		slog.String("key2", "val2"),
		slog.String("Key1", "IChangedIt"),
	)

	slog.InfoContext(
		ctx,
		"I Changed the first one",
	)

	ctx = slogctx.With(
		ctx,
		"key2", 7,
	)

	slog.InfoContext(
		ctx,
		"You can see the second one is now a number",
	)

	slog.WarnContext(
		firstContext,
		"the first context is unchanged",
	)
}

Output

{
    "time": "2025-04-11T01:53:29.677325-06:00",
    "level": "ERROR",
    "msg": "Original Value",
    "Key1": "Val1"
}
{
    "time": "2025-04-11T01:53:29.677446-06:00",
    "level": "INFO",
    "msg": "I Changed the first one",
    "Key1": "IChangedIt",
    "key2": "val2"
}
{
    "time": "2025-04-11T01:53:29.677449-06:00",
    "level": "INFO",
    "msg": "You can see the second one is now a number",
    "Key1": "IChangedIt",
    "key2": 7
}
{
    "time": "2025-04-11T01:53:29.677472-06:00",
    "level": "WARN",
    "msg": "the first context is unchanged",
    "Key1": "Val1"
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AddAttributesToLogger added in v1.0.1

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

AddAttributesToLogger is now an alias for With

func GetLogger added in v1.0.1

func GetLogger(ctx context.Context) *slog.Logger

GetLogger is used to get the context logger It is recommended to use slog context functions instead ex slog.InfoContext(ctx, msg, ...args)

func SetDefaultLogger added in v1.1.0

func SetDefaultLogger(logger *slog.Logger)

SetDefaultLogger sets the default logger for this package (slogctx)

func SetSlogPackageDefault added in v1.1.0

func SetSlogPackageDefault()

Calls slog.SetDefault with a JSONHandler that logs to Stdout wrapped in a ContextHandler

func SetSlogPackageWithOptions added in v1.1.0

func SetSlogPackageWithOptions(writer io.Writer, opts *slog.HandlerOptions)

Calls slog.SetDefault with options passed to a JSONHandler that logs to Stdout wrapped in a ContextHandler

func With added in v1.1.0

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

With is used to add values to the context for logging purposes these args will appear in logs of any child contexts where slogctx.GetLogger(ctx) is called or any slog context functions for example slog.InfoContext(ctx, msg, ...args)

func WithAttrs added in v1.1.0

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

WithAttrs is used to add slog.Attrs to the context for logging purposes these slog.Attrs will appear in logs of any child contexts where slogctx.GetLogger(ctx) is called or any slog context functions for example slog.InfoContext(ctx, msg, ...args)

Types

type ContextHandler added in v1.1.0

type ContextHandler struct {
	// contains filtered or unexported fields
}

ContextHandler enables this package to handle passing values from context to log messages when using the slog context functions ex: slog.InfoContext(ctx, msg, ...args)

func NewContextHandler added in v1.1.0

func NewContextHandler(handler slog.Handler) *ContextHandler

NewContextHandler creates a new ContextHandler that wraps a slog.Handler passed in

func NewJSONContextHandler added in v1.1.0

func NewJSONContextHandler(w io.Writer, opts *slog.HandlerOptions) *ContextHandler

NewJSONContextHandler creates a new ContextHandler that wraps a slog.JSONHandler

func (*ContextHandler) Enabled added in v1.1.0

func (h *ContextHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled is to required implement slog.Handler

func (*ContextHandler) Handle added in v1.1.0

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

Handle is to required implement slog.Handler

func (*ContextHandler) WithAttrs added in v1.1.0

func (h *ContextHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs is required to implement slog.Handler

func (*ContextHandler) WithGroup added in v1.1.0

func (h *ContextHandler) WithGroup(name string) slog.Handler

WithGroup is required to implement slog.Handler

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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