logging

package
v0.7.2 Latest Latest
Warning

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

Go to latest
Published: Oct 26, 2025 License: BSD-3-Clause Imports: 8 Imported by: 0

Documentation

Overview

Package logging provides structured logging functionality using slog with colored output. It supports environment-based configuration and context-aware logging patterns. The package is heavily inspired by: https://github.com/google/exposure-notifications-server/blob/main/pkg/logging/logger.go

Example usage:

// Create a logger with specific level
logger := logging.NewLogger("debug", true)
logger.Info("Hello, world!")

// Create logger from environment variables
envLogger := logging.NewLoggerFromEnv()
envLogger.Warn("This is a warning")

// Use context-aware logging
ctx := logging.WithLogger(context.Background(), logger)
ctxLogger := logging.FromContext(ctx)
ctxLogger.Error("Error from context")

// Use default logger
defaultLogger := logging.DefaultLogger()
defaultLogger.Info("Using default logger")

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultLogger

func DefaultLogger() *slog.Logger

DefaultLogger returns the default logger for the package. The logger is initialized once using environment variables and cached for subsequent calls. This is safe for concurrent use and ensures consistent logging configuration across the application.

func FromContext

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

FromContext returns the logger stored in the context. If no logger exists in the context, returns the default logger for the package. This ensures that logging is always available without needing to check for nil.

func NewLogger

func NewLogger(level string, development bool) *slog.Logger

NewLogger creates a new structured logger with the specified log level and development mode. The level parameter accepts "debug", "info", "warn", or "error" (defaults to "info" if invalid). The development parameter determines if the logger should use development-friendly output formatting. Returns a configured slog.Logger instance with colored output using the tint handler.

func NewLoggerFromEnv

func NewLoggerFromEnv() *slog.Logger

NewLoggerFromEnv creates a new logger from environment variables. It reads LOG_LEVEL to determine the logging level and APP_ENV to determine development mode. If APP_ENV is set to "development", development mode is enabled for better formatting. Automatically loads environment variables from .env file if present.

func WithLogger

func WithLogger(ctx context.Context, logger *slog.Logger) context.Context

WithLogger creates a new context with the provided logger attached. This allows for context-aware logging throughout the application call chain. The logger can be retrieved later using FromContext.

Types

This section is empty.

Jump to

Keyboard shortcuts

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