Skip to main content

Slog Handler

The Slog handler provides integration with the log/slog package from the Go standard library, allowing you to automatically mask sensitive data in your logs.

Overview

The Slog handler is a configurable logging handler that applies censoring to log entries and fields, overriding the original values before passing them to the output. It's designed to work with JSON output format, providing structured logging with automatic sensitive data masking.

Basic Usage

Here's a simple example of how to use the Slog handler:

// Define the configuration.  
cfg := censor.Config{
Encoder: censor.EncoderConfig{
DisplayMapType: true,
MaskValue: "[CENSORED]",
// Other configuration options...
},
}

// Initialize a censor instance with the specified configuration.
c, err := censor.NewWithOpts(censor.WithConfig(&cfg))
if err != nil {
// Handle error.
}

// Create and register a new slog handler with the initialized instance.
opts := []sloghandler.Option{sloghandler.WithCensor(c)}
log := slog.New(sloghandler.NewJSONHandler(opts...))

// Use logger as usual.
log.Info("user", slog.Any("payload", payload))
note

The handler currently only supports JSON output format. Text format support is planned for future releases.

Understanding Logger Components

When working with the Slog logger, we can identify several key components:

  • time: The timestamp of the log entry
  • level: The log level (INFO, DEBUG, WARN, etc.)
  • msg: The main log message
  • source: Optional source information (file, line, function)
  • attributes: Additional key-value pairs of data

The handler processes all attribute values to ensure sensitive data is properly masked while maintaining the structure and readability of your logs.

Configuration Options

The Slog handler provides two types of configuration options:

Censor-specific Options

  • WithCensor(censor *censor.Processor): Sets a custom Censor processor instance for the Slog handler

Standard Slog Options

The handler also supports standard slog options that are passed through to the underlying JSON handler:

  • WithOut(w io.Writer): Sets the output destination (defaults to os.Stdout)
  • WithAddSource(): Enables source file and line number information in logs
  • WithLevel(level slog.Leveler): Sets the minimum log level
  • WithReplaceAttr(func(groups []string, a slog.Attr) slog.Attr): Allows custom attribute transformation
note

The standard slog options are not Censor-specific features. They are standard options provided by the log/slog package that we pass through to the underlying JSON handler. These options are processed according to the standard slog logic.

Example with custom configuration:

censorInst := censor.New()
opts := []Option{
WithOut(os.Stdout), // Standard slog option.
WithCensor(censorInst), // Censor-specific option.
WithAddSource(), // Standard slog option.
WithLevel(slog.LevelDebug), // Standard slog option.
WithReplaceAttr(func(groups []string, a slog.Attr) slog.Attr {
if a.Key == "msg" {
return slog.Any("msg", "replaced msg")
}
return a
}), // Standard slog option.
}

handler := NewJSONHandler(opts...)
log := slog.New(handler)
log.Info("user", slog.Any("payload", u))

Supported Logger Methods

The handler fully supports all standard Slog logger methods:

// Basic logging methods.
Info(msg string, args ...any)
Debug(msg string, args ...any)
Warn(msg string, args ...any)
Error(msg string, args ...any)

// With methods.
With(args ...any) *slog.Logger

// Group methods.
WithGroup(name string) *slog.Logger

Important Notes

  1. Performance Considerations: The handler processes all attribute values to ensure sensitive data is properly masked. This may have a slight performance impact compared to standard logging.

Next Steps

  1. Learn about Type Support options
  2. See Configuration for customization options
  3. Check out Examples for real-world usage