Documentation
¶
Overview ¶
Package logz provides a flexible and structured logging utility for Go applications.
It wraps the standard library's slog package to provide a consistent interface (Logger) that supports different log levels, structured data, context-aware logging, and integration with custom error types like apperr.AppErr.
Example usage:
logz.MustInit()
logger := logz.Global()
logger.Info("logz: iniciando aplicación", "version", "1.0.0")
if err != nil {
logger.LogError("logz: fallo al procesar petición", err)
}
Index ¶
- Constants
- func Fatal(logger Logger, msg string, err error, args ...any)
- func GetRequestID(ctx context.Context) string
- func WithField(ctx context.Context, key string, value any) context.Context
- func WithFields(ctx context.Context, fields map[string]any) context.Context
- func WithRequestID(ctx context.Context, id string) context.Context
- type Logger
Constants ¶
const ( // EnvLogLevel is the environment variable to set the minimum log level (e.g., DEBUG, INFO, WARN, ERROR). EnvLogLevel = "LOG_LEVEL" // EnvLogJSON is the environment variable to enable JSON output (set to "true" or "1"). EnvLogJSON = "LOG_JSON_OUTPUT" )
Variables ¶
This section is empty.
Functions ¶
func Fatal ¶ added in v1.0.0
Fatal logs at ERROR level and exits the process with code 1. It is a package-level function rather than an interface method so that Logger implementations (e.g. test mocks) do not need to call os.Exit.
func GetRequestID ¶
GetRequestID retrieves the correlation ID from the context, if present.
func WithFields ¶
WithFields adds multiple key-value pairs to the context for logging.
Types ¶
type Logger ¶
type Logger interface {
// Debug logs a message at DEBUG level.
Debug(msg string, args ...any)
// Info logs a message at INFO level.
Info(msg string, args ...any)
// Warn logs a message at WARN level.
Warn(msg string, args ...any)
// Error logs a message at ERROR level with an attached error.
Error(msg string, err error, args ...any)
// LogError logs an error, automatically extracting code and context if it's an apperr.AppErr.
LogError(msg string, err error, args ...any)
// With returns a new Logger with the given attributes.
With(args ...any) Logger
// WithContext returns a new Logger that includes values from the context.
WithContext(ctx context.Context) Logger
}
Logger defines the interface for our application logging.
func New ¶
New creates a new Logger from the given slog.Handler. staticArgs are added as permanent fields on every log entry. This is the primary constructor — prefer constructor injection over the global singleton pattern.
func NewFromEnv ¶ added in v1.0.0
NewFromEnv creates a Logger configured from environment variables (LOG_LEVEL, LOG_JSON_OUTPUT). This is a convenience constructor for bootstrapping in main.go.