# README
log
import "github.com/brpaz/lib-go/log"
Package log provides a structured logging interface for Go applications.
It is designed to be simple to use and easy to configure. The package provides a generic Logger interface that can be implemented by various logging adapters. Built-in adapters include Zap (high-performance production logging), InMemory (log capturing for testing), and Noop (no-operation logging).
Key Features: - Adapters:
- Zap: A high-performance, production-ready logging adapter.
- InMemory: Suitable for testing or in-memory log capturing.
- **Noop**: A no-operation adapter, ideal for disabling logging.
- Profiles:
- ProfileDevelopment: Configures the logger for development environments, with human-readable log formats and more verbose output.
- ProfileProduction: Optimized for production, using structured and minimal logs.
- Formats:
- json: Logs are output in structured JSON format for log aggregators.
- fmt: Logs are output in a human-readable format for development.
Example Usage:
package main
import (
"context"
"errors"
"github.com/brpaz/lib-go/log"
)
func main() {
logger, err := log.New(
log.WithAdapter("zap"),
log.WithLevel("debug"),
log.WithProfile(log.ProfileProduction),
log.WithFormat(log.FormatJSON),
)
if err != nil {
panic(errors.Join(err, errors.New("failed to create logger")))
}
defer logger.Sync()
// Use the logger
logger.Info(context.Background(), "Application started", log.String("env", "production"))
}
Index
- Constants
- Variables
- func ContextWithLogger(parentCtx context.Context, logger Logger) context.Context
- func ReplaceGlobals(logger Logger) func()
- type Field
- type InMemoryLogEntry
- type InMemoryLogger
- func NewInMemory(level Level) *InMemoryLogger
- func (l *InMemoryLogger) Debug(ctx context.Context, msg string, fields ...Field)
- func (l *InMemoryLogger) Entries() []InMemoryLogEntry
- func (l *InMemoryLogger) Error(ctx context.Context, msg string, fields ...Field)
- func (l *InMemoryLogger) GetLevel() Level
- func (l *InMemoryLogger) Info(ctx context.Context, msg string, fields ...Field)
- func (l *InMemoryLogger) SetLevel(level Level) error
- func (l *InMemoryLogger) Sync() error
- func (l *InMemoryLogger) Warn(ctx context.Context, msg string, fields ...Field)
- func (l *InMemoryLogger) With(fields ...Field) Logger
- type Level
- type Logger
- type LoggerOpt
- type LoggerOpts
- type NopLogger
- func NewNop() *NopLogger
- func (l *NopLogger) Debug(ctx context.Context, msg string, fields ...Field)
- func (l *NopLogger) Error(ctx context.Context, msg string, fields ...Field)
- func (l *NopLogger) GetLevel() Level
- func (l *NopLogger) Info(ctx context.Context, msg string, fields ...Field)
- func (l *NopLogger) SetLevel(level Level) error
- func (l *NopLogger) Sync() error
- func (l *NopLogger) Warn(ctx context.Context, msg string, fields ...Field)
- func (l *NopLogger) With(fields ...Field) Logger
- type ZapAdapter
- func NewZap(opts ZapLoggerOpts) (*ZapAdapter, error)
- func (l *ZapAdapter) Debug(ctx context.Context, msg string, fields ...Field)
- func (l *ZapAdapter) Error(ctx context.Context, msg string, fields ...Field)
- func (l *ZapAdapter) GetLevel() Level
- func (l *ZapAdapter) Info(ctx context.Context, msg string, fields ...Field)
- func (l *ZapAdapter) SetLevel(level Level) error
- func (l *ZapAdapter) Sync() error
- func (l *ZapAdapter) Warn(ctx context.Context, msg string, fields ...Field)
- func (l *ZapAdapter) With(fields ...Field) Logger
- type ZapLoggerOpts
Constants
Constants for available profiles, adapters, and formats.
const (
ProfileDevelopment = "dev"
ProfileProduction = "prod"
AdapterZap = "zap"
AdapterNop = "nop"
AdapterInMemory = "in-memory"
FormatJSON = "json"
FormatLogFmt = "logfmt"
)
Variables
var (
Bool = zap.Bool
Int = zap.Int
Int64 = zap.Int64
Float64 = zap.Float64
String = zap.String
Duration = zap.Duration
Float32 = zap.Float32
Float64p = zap.Float64p
Error = zap.Error
Any = zap.Any
)
var (
ErrInvalidProfile = errors.New("invalid log profile")
ErrInvalidFormat = errors.New("invalid log format")
ErrInvalidAdapter = errors.New("invalid log adapter")
)
ErrInvalidLevel is returned when an invalid log level is provided.
var ErrInvalidLevel = errors.New("logger: invalid log level")
func ContextWithLogger
func ContextWithLogger(parentCtx context.Context, logger Logger) context.Context
ContextWithLogger returns a new context with the provided logger instance. This is useful for associating a specific logger with the given context.
func ReplaceGlobals
func ReplaceGlobals(logger Logger) func()
ReplaceGlobals replaces the global Logger and returns a function to restore the original values. It's safe for concurrent use.
type Field
Field defines a structured log attribute that allows to add additional information to a log entry in a type-safe way. To avoid reinventing the wheel, this is just a wrapper around slog.Attr, from the slog package. We can changhe the underlying implementation in the future if needed, but the interface for the rest of the application will remain the same.
type Field = zap.Field
func ExtractTraceIDFieldsFromContext
func ExtractTraceIDFieldsFromContext(ctx context.Context) []Field
ExtractTraceIDFieldsFromContext extracts trace-related fields from the given context if OpenTelemetry tracing information is available. The extracted fields include "traceId" and "spanId". Returns an empty slice if no valid trace context is found.
type InMemoryLogEntry
InMemoryLogEntry represents a single log entry.
type InMemoryLogEntry struct {
Timestamp time.Time
Message string
Level string
Fields []Field
}
func (*InMemoryLogEntry) GetField
func (e *InMemoryLogEntry) GetField(key string) (Field, bool)
GetField retrieves a field by its key from the log entry.
type InMemoryLogger
InMemoryLogger stores log entries in memory for testing purposes.
type InMemoryLogger struct {
// contains filtered or unexported fields
}
func NewInMemory
func NewInMemory(level Level) *InMemoryLogger
NewInMemory creates and returns a new instance of InMemoryLogger with the provided log level. Usage:
package main
import (
"context"
"github.com/brpaz/lib-go/log"
)
func main() {
logger := log.NewInMemory(log.LevelInfo)
logger.Info(context.Background(), "Application started")
entries := logger.Entries()
for _, entry := range entries {
fmt.Println(entry.Message)
}
}
func (*InMemoryLogger) Debug
func (l *InMemoryLogger) Debug(ctx context.Context, msg string, fields ...Field)
Debug logs a debug message.
func (*InMemoryLogger) Entries
func (l *InMemoryLogger) Entries() []InMemoryLogEntry
Entries returns all the log entries stored by the logger.
func (*InMemoryLogger) Error
func (l *InMemoryLogger) Error(ctx context.Context, msg string, fields ...Field)
Error logs an error message.
func (*InMemoryLogger) GetLevel
func (l *InMemoryLogger) GetLevel() Level
GetLevel retrieves the current log level of the logger.
func (*InMemoryLogger) Info
func (l *InMemoryLogger) Info(ctx context.Context, msg string, fields ...Field)
Info logs an informational message.
func (*InMemoryLogger) SetLevel
func (l *InMemoryLogger) SetLevel(level Level) error
SetLevel updates the logger's log level.
func (*InMemoryLogger) Sync
func (l *InMemoryLogger) Sync() error
Sync simulates synchronizing the logger (no-op for InMemoryLogger).
func (*InMemoryLogger) Warn
func (l *InMemoryLogger) Warn(ctx context.Context, msg string, fields ...Field)
Warn logs a warning message.
func (*InMemoryLogger) With
func (l *InMemoryLogger) With(fields ...Field) Logger
With returns a new logger instance with the additional fields.
type Level
Level defines all available log levels for log messages.
type Level int
Log levels supported by the application.
const (
LevelDebug Level = iota
LevelInfo
LevelWarn
LevelError
)
func LevelFromString
func LevelFromString(level string) (Level, error)
LevelFromString returns the log level from a string representation. It performs a case-insensitive comparison and returns an error for invalid levels.
func (Level) String
func (p Level) String() string
String returns the string representation of a logging level. If the level is invalid, it returns "unknown".
type Logger
Logger is a generic interface that defines the methods required by a logger.
type Logger interface {
Info(ctx context.Context, msg string, fields ...Field)
Warn(ctx context.Context, msg string, fields ...Field)
Error(ctx context.Context, msg string, fields ...Field)
Debug(ctx context.Context, msg string, fields ...Field)
SetLevel(level Level) error
GetLevel() Level
With(fields ...Field) Logger
Sync() error
}
func FromContext
func FromContext(ctx context.Context) Logger
FromContext retrieves the logger instance from the provided context. If no logger is present in the context, it falls back to the global logger.
func L
func L() Logger
L retrieves the global logger instance. If no logger is set, returns a no-op logger.
func New
func New(options ...LoggerOpt) (Logger, error)
New creates a new logger instance using the provided options. Example:
package main
import (
"context"
"github.com/brpaz/lib-go/log"
)
func main() {
logger, err := log.New(
log.WithAdapter("zap"),
log.WithLevel(log.LevelDebug),
log.WithProfile(log.ProfileProduction),
log.WithFormat(log.FormatJSON),
)
if err != nil {
panic(errors.Join(err, errors.New("failed to create logger")))
}
defer logger.Sync()
logger.Info(context.Background(), "Application started", log.String("env", "production"))
}
type LoggerOpt
LoggerOpt is a functional option type to configure the logger.
type LoggerOpt func(*LoggerOpts)
func WithAdapter
func WithAdapter(adapter string) LoggerOpt
WithAdapter sets the logger adapter to be used by the logger.
func WithFormat
func WithFormat(format string) LoggerOpt
WithFormat specifies the log format to be used by the logger. Supported formats are json and console. This option will be only applicable for the Zap adapter.
func WithLevel
func WithLevel(level Level) LoggerOpt
WithLevel sets the log level in the options.
func WithProfile
func WithProfile(profile string) LoggerOpt
WithProfile sets the logger profile in the options (e.g., dev, prod).
type LoggerOpts
LoggerOpts specifies the options that can be used to configure the logger instance.
type LoggerOpts struct {
Adapter string
Level Level
Profile string
Format string
}
func (*LoggerOpts) Validate
func (opts *LoggerOpts) Validate() error
Validate checks if the provided Logger options are valid.
type NopLogger
NopLogger is a no-op logger implementation.
type NopLogger struct{}
func NewNop
func NewNop() *NopLogger
NewNop returns a new instance of the no-op logger.
func (*NopLogger) Debug
func (l *NopLogger) Debug(ctx context.Context, msg string, fields ...Field)
Debug does nothing for the no-op logger.
func (*NopLogger) Error
func (l *NopLogger) Error(ctx context.Context, msg string, fields ...Field)
Error does nothing for the no-op logger.
func (*NopLogger) GetLevel
func (l *NopLogger) GetLevel() Level
GetLevel always returns LevelInfo for the no-op logger.
func (*NopLogger) Info
func (l *NopLogger) Info(ctx context.Context, msg string, fields ...Field)
Info does nothing for the no-op logger.
func (*NopLogger) SetLevel
func (l *NopLogger) SetLevel(level Level) error
SetLevel does nothing for the no-op logger.
func (*NopLogger) Sync
func (l *NopLogger) Sync() error
Sync does nothing for the no-op logger.
func (*NopLogger) Warn
func (l *NopLogger) Warn(ctx context.Context, msg string, fields ...Field)
Warn does nothing for the no-op logger.
func (*NopLogger) With
func (l *NopLogger) With(fields ...Field) Logger
With returns the same no-op logger instance.
type ZapAdapter
ZapAdapter is a wrapper around zap.Logger that implements the Logger interface.
type ZapAdapter struct {
ZapL *zap.Logger
AtomicLevel zap.AtomicLevel
}
func NewZap
func NewZap(opts ZapLoggerOpts) (*ZapAdapter, error)
NewZap creates a new Zap logger instance with the provided options.
func (*ZapAdapter) Debug
func (l *ZapAdapter) Debug(ctx context.Context, msg string, fields ...Field)
Debug logs a message at the debug level.
func (*ZapAdapter) Error
func (l *ZapAdapter) Error(ctx context.Context, msg string, fields ...Field)
Error logs a message at the error level.
func (*ZapAdapter) GetLevel
func (l *ZapAdapter) GetLevel() Level
GetLevel retrieves the current logging level.
func (*ZapAdapter) Info
func (l *ZapAdapter) Info(ctx context.Context, msg string, fields ...Field)
Info logs a message at the info level.
func (*ZapAdapter) SetLevel
func (l *ZapAdapter) SetLevel(level Level) error
SetLevel updates the logging level dynamically.
func (*ZapAdapter) Sync
func (l *ZapAdapter) Sync() error
Sync flushes any buffered log entries.
func (*ZapAdapter) Warn
func (l *ZapAdapter) Warn(ctx context.Context, msg string, fields ...Field)
Warn logs a message at the warning level.
func (*ZapAdapter) With
func (l *ZapAdapter) With(fields ...Field) Logger
With creates a new logger instance with additional fields.
type ZapLoggerOpts
ZapLoggerOpts specifies options to configure the Zap logger instance.
type ZapLoggerOpts struct {
Level Level
Profile string
Format string
}
func DefaultZapLoggerOpts
func DefaultZapLoggerOpts() ZapLoggerOpts
DefaultZapLoggerOpts returns a copy of the default logger options.
func (ZapLoggerOpts) Validate
func (o ZapLoggerOpts) Validate() error
Generated by gomarkdoc