Documentation
¶
Overview ¶
Package logger provides structured logging with OpenTelemetry trace integration.
This package offers multiple logging configurations for different deployment scenarios:
- Text logging to stderr with optional timestamp removal for systemd
- OTLP (OpenTelemetry Protocol) logging for observability pipelines
- Multi-logger setup that outputs to both text and OTLP simultaneously
- Context-aware logging with trace ID correlation
The package automatically detects systemd environments and adjusts timestamp handling accordingly. It supports debug level configuration via environment variables and provides compatibility bridges for legacy logging interfaces.
Key features:
- Automatic OpenTelemetry trace and span ID inclusion in log entries
- Configurable log levels via DEBUG environment variable (with optional prefix)
- Systemd-compatible output (no timestamps when INVOCATION_ID is present)
- Thread-safe logger setup with sync.Once protection
- Context propagation for request-scoped logging
Environment variables:
- LOG_LEVEL: Set stderr log level (DEBUG, INFO, WARN, ERROR) (configurable prefix via ConfigPrefix)
- OTLP_LOG_LEVEL: Set OTLP log level independently (configurable prefix via ConfigPrefix)
- DEBUG: Enable debug level logging for backward compatibility (configurable prefix via ConfigPrefix)
- INVOCATION_ID: Systemd detection for timestamp handling
Index ¶
- Variables
- func FromContext(ctx context.Context) *slog.Logger
- func NewContext(ctx context.Context, l *slog.Logger) context.Context
- func NewStdLog(key string, debug bool, log *slog.Logger) *stdLoggerish
- func ParseLevel(level string) (slog.Level, error)
- func SetLevel(level slog.Level)
- func SetOTLPLevel(level slog.Level)
- func Setup() *slog.Logger
- func SetupMultiLogger() *slog.Logger
- func SetupOLTP() *slog.Logger
Constants ¶
This section is empty.
Variables ¶
var ( // Level controls the log level for the default stderr logger. // Can be changed at runtime to adjust logging verbosity. Level = new(slog.LevelVar) // Info by default // OTLPLevel controls the log level for OTLP output. // Can be changed independently from the stderr logger level. OTLPLevel = new(slog.LevelVar) // Info by default )
var ConfigPrefix = ""
ConfigPrefix allows customizing the environment variable prefix for configuration. When set, environment variables like DEBUG become {ConfigPrefix}_DEBUG. This enables multiple services to have independent logging configuration.
Functions ¶
func FromContext ¶
FromContext retrieves a logger from the context. If no logger is stored in the context, it returns the default logger from Setup().
This function provides a safe way to access context-scoped loggers without needing to check for nil values. It ensures that logging is always available, falling back to the application's standard logger configuration.
Example:
log := logger.FromContext(ctx)
log.Info("processing request") // Uses context logger or default
func NewContext ¶
NewContext stores a logger in the context for request-scoped logging. This enables passing request-specific loggers (e.g., with request IDs, user context, or other correlation data) through the call stack.
Use this to create context-aware logging where different parts of the application can access the same enriched logger instance.
Example:
logger := slog.With("request_id", requestID)
ctx := logger.NewContext(ctx, logger)
// Pass ctx to downstream functions
func NewStdLog ¶
NewStdLog creates a legacy-compatible logger that bridges to structured logging. This is useful for third-party libraries that expect a standard log.Logger interface.
Parameters:
- key: Prefix added to all log messages for identification
- debug: If true, logs at debug level; otherwise logs at info level
- log: Underlying slog.Logger (uses Setup() if nil)
The returned logger implements Println, Printf, and Fatalf methods.
func ParseLevel ¶ added in v0.5.2
ParseLevel converts a string log level to slog.Level. Supported levels: "DEBUG", "INFO", "WARN", "ERROR" (case insensitive). Returns an error for unrecognized level strings.
func SetLevel ¶ added in v0.5.2
SetLevel sets the log level for the default stderr logger. This affects the primary application logger returned by Setup().
func SetOTLPLevel ¶ added in v0.5.2
SetOTLPLevel sets the log level for OTLP output. This affects the logger returned by SetupOLTP() and the OTLP portion of SetupMultiLogger().
func Setup ¶
Setup creates and returns the standard text logger for the application. This is the primary logging function that most applications should use.
Features:
- Text formatting to stderr with human-readable output
- Automatic OpenTelemetry trace_id and span_id inclusion when available
- Systemd compatibility: omits timestamps when INVOCATION_ID environment variable is present
- Debug level support via DEBUG environment variable (respects ConfigPrefix)
- Thread-safe initialization with sync.Once
On first call, this logger becomes the slog default logger. If SetupMultiLogger() has been called previously, Setup() returns the multi-logger instead of the text logger.
The logger automatically detects execution context:
- Systemd: Removes timestamps (systemd adds its own)
- Debug mode: Enables debug level logging based on environment variables
- OpenTelemetry: Includes trace correlation when tracing is active
func SetupMultiLogger ¶ added in v0.3.0
SetupMultiLogger creates a logger that outputs to both text (stderr) and OTLP simultaneously. This is useful for services that need both human-readable logs and structured observability data.
The multi-logger combines:
- Text handler: Stderr output with OpenTelemetry trace integration
- OTLP handler: Structured logs sent via OpenTelemetry Protocol
On first call, this logger becomes the default logger returned by Setup(). The function is thread-safe and uses sync.Once to ensure single initialization.
func SetupOLTP ¶ added in v0.3.0
SetupOLTP creates a logger that sends structured logs via OpenTelemetry Protocol. This logger is designed for observability pipelines and log aggregation systems.
The OTLP logger formats log messages similarly to the text logger for better compatibility with Loki + Grafana, while still providing structured attributes. Log attributes are available both in the message format and as OTLP attributes.
This logger does not become the default logger and must be used explicitly. It requires OpenTelemetry tracing configuration to be set up via the tracing package.
See: https://github.com/grafana/loki/issues/14788 for formatting rationale.
Types ¶
This section is empty.