API Reference
5 minute read
Complete API reference for all public types and methods in the logging package.
Core Functions
New
func New(opts ...Option) (*Logger, error)
Creates a new Logger with the given options. Returns an error if configuration is invalid.
Parameters:
opts- Variadic list of configuration options.
Returns:
*Logger- Configured logger instance.error- Configuration error, if any.
Example:
logger, err := logging.New(
logging.WithJSONHandler(),
logging.WithLevel(logging.LevelInfo),
)
if err != nil {
log.Fatalf("failed to create logger: %v", err)
}
MustNew
func MustNew(opts ...Option) *Logger
Creates a new Logger or panics on error. Use for initialization where errors are fatal.
Parameters:
opts- Variadic list of configuration options
Returns:
*Logger- Configured logger instance
Panics:
- If configuration is invalid
Example:
logger := logging.MustNew(
logging.WithJSONHandler(),
logging.WithLevel(logging.LevelInfo),
)
NewContextLogger
func NewContextLogger(ctx context.Context, logger *Logger) *ContextLogger
Creates a context-aware logger that automatically extracts trace and span IDs from OpenTelemetry context.
Parameters:
ctx- Context to extract trace information from.logger- Base Logger instance.
Returns:
*ContextLogger- Context-aware logger.
Example:
cl := logging.NewContextLogger(ctx, logger)
cl.Info("processing request") // Includes trace_id and span_id
Logger Type
Logging Methods
Debug
func (l *Logger) Debug(msg string, args ...any)
Logs a debug message with structured attributes.
Parameters:
msg- Log messageargs- Key-value pairs (must be even number of arguments)
Example:
logger.Debug("cache lookup", "key", cacheKey, "hit", true)
Info
func (l *Logger) Info(msg string, args ...any)
Logs an informational message with structured attributes.
Parameters:
msg- Log messageargs- Key-value pairs
Example:
logger.Info("server started", "port", 8080, "version", "v1.0.0")
Warn
func (l *Logger) Warn(msg string, args ...any)
Logs a warning message with structured attributes.
Parameters:
msg- Log messageargs- Key-value pairs
Example:
logger.Warn("high memory usage", "used_mb", 8192, "threshold_mb", 10240)
Error
func (l *Logger) Error(msg string, args ...any)
Logs an error message with structured attributes. Errors bypass log sampling.
Parameters:
msg- Log messageargs- Key-value pairs
Example:
logger.Error("database connection failed", "error", err, "retry_count", 3)
Convenience Methods
LogRequest
func (l *Logger) LogRequest(r *http.Request, extra ...any)
Logs an HTTP request with standard fields (method, path, remote, user_agent, query).
Parameters:
r- HTTP requestextra- Additional key-value pairs
Example:
logger.LogRequest(r, "status", 200, "duration_ms", 45)
LogError
func (l *Logger) LogError(err error, msg string, extra ...any)
Logs an error with automatic error field.
Parameters:
err- Error to logmsg- Log messageextra- Additional key-value pairs
Example:
logger.LogError(err, "operation failed", "operation", "INSERT", "table", "users")
LogDuration
func (l *Logger) LogDuration(msg string, start time.Time, extra ...any)
Logs operation duration with automatic duration_ms and duration fields.
Parameters:
msg- Log messagestart- Operation start timeextra- Additional key-value pairs
Example:
start := time.Now()
// ... operation ...
logger.LogDuration("processing completed", start, "items", 100)
ErrorWithStack
func (l *Logger) ErrorWithStack(msg string, err error, includeStack bool, extra ...any)
Logs an error with optional stack trace.
Parameters:
msg- Log messageerr- Error to logincludeStack- Whether to capture and include stack traceextra- Additional key-value pairs
Example:
logger.ErrorWithStack("critical failure", err, true, "user_id", userID)
Context Methods
Logger
func (l *Logger) Logger() *slog.Logger
Returns the underlying slog.Logger for advanced usage.
Returns:
*slog.Logger- Underlying logger
Example:
slogger := logger.Logger()
With
func (l *Logger) With(args ...any) *slog.Logger
Returns a slog.Logger with additional attributes that persist across log calls.
Parameters:
args- Key-value pairs to add as persistent attributes
Returns:
*slog.Logger- Logger with added attributes
Example:
requestLogger := logger.With("request_id", "req-123", "user_id", "user-456")
requestLogger.Info("processing") // Includes request_id and user_id
WithGroup
func (l *Logger) WithGroup(name string) *slog.Logger
Returns a slog.Logger with a group name for nested attributes.
Parameters:
name- Group name
Returns:
*slog.Logger- Logger with group
Example:
dbLogger := logger.WithGroup("database")
dbLogger.Info("query", "sql", "SELECT * FROM users")
// Output: {...,"database":{"sql":"SELECT * FROM users"}}
Configuration Methods
SetLevel
func (l *Logger) SetLevel(level Level) error
Dynamically changes the minimum log level at runtime.
Parameters:
level- New log level
Returns:
error-ErrCannotChangeLevelif using custom logger
Example:
if err := logger.SetLevel(logging.LevelDebug); err != nil {
log.Printf("failed to change level: %v", err)
}
Level
func (l *Logger) Level() Level
Returns the current minimum log level.
Returns:
Level- Current log level
Example:
currentLevel := logger.Level()
fmt.Printf("Current level: %s\n", currentLevel)
Metadata Methods
ServiceName
func (l *Logger) ServiceName() string
Returns the configured service name.
Returns:
string- Service name, or empty if not configured
ServiceVersion
func (l *Logger) ServiceVersion() string
Returns the configured service version.
Returns:
string- Service version, or empty if not configured
Environment
func (l *Logger) Environment() string
Returns the configured environment.
Returns:
string- Environment, or empty if not configured
Lifecycle Methods
IsEnabled
func (l *Logger) IsEnabled() bool
Returns true if logging is enabled (not shut down).
Returns:
bool- Whether logger is active
DebugInfo
func (l *Logger) DebugInfo() map[string]any
Returns diagnostic information about logger state.
Returns:
map[string]any- Diagnostic information
Example:
info := logger.DebugInfo()
fmt.Printf("Handler: %s\n", info["handler_type"])
fmt.Printf("Level: %s\n", info["level"])
Shutdown
func (l *Logger) Shutdown(ctx context.Context) error
Gracefully shuts down the logger, flushing any buffered logs.
Parameters:
ctx- Context for timeout control
Returns:
error- Shutdown error, if any
Example:
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := logger.Shutdown(ctx); err != nil {
fmt.Fprintf(os.Stderr, "shutdown error: %v\n", err)
}
ContextLogger Type
Logging Methods
Debug
func (cl *ContextLogger) Debug(msg string, args ...any)
Logs a debug message with automatic trace correlation.
Info
func (cl *ContextLogger) Info(msg string, args ...any)
Logs an info message with automatic trace correlation.
Warn
func (cl *ContextLogger) Warn(msg string, args ...any)
Logs a warning message with automatic trace correlation.
Error
func (cl *ContextLogger) Error(msg string, args ...any)
Logs an error message with automatic trace correlation.
Context Methods
Logger
func (cl *ContextLogger) Logger() *slog.Logger
Returns the underlying slog.Logger.
Returns:
*slog.Logger- Underlying logger
TraceID
func (cl *ContextLogger) TraceID() string
Returns the trace ID if available.
Returns:
string- Trace ID, or empty if not available
Example:
if traceID := cl.TraceID(); traceID != "" {
fmt.Printf("Trace ID: %s\n", traceID)
}
SpanID
func (cl *ContextLogger) SpanID() string
Returns the span ID if available.
Returns:
string- Span ID, or empty if not available
With
func (cl *ContextLogger) With(args ...any) *slog.Logger
Returns a slog.Logger with additional attributes.
Parameters:
args- Key-value pairs
Returns:
*slog.Logger- Logger with added attributes
Next Steps
- See Options for all configuration options
- Check Testing Utilities for test helpers
- Review Troubleshooting for common issues
For usage guides, see the Logging Guide.
Feedback
Was this page helpful?
Glad to hear it! Please tell us how we can improve.
Sorry to hear that. Please tell us how we can improve.