logger

package
v0.8.6 Latest Latest
Warning

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

Go to latest
Published: Jan 3, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	// Reset and basic colors.
	Reset = "\033[0m"

	// Text styles.
	Bold      = "\033[1m"
	Dim       = "\033[2m"
	Italic    = "\033[3m"
	Underline = "\033[4m"

	// Foreground colors.
	Black   = "\033[30m"
	Red     = "\033[31m"
	Green   = "\033[32m"
	Yellow  = "\033[33m"
	Blue    = "\033[34m"
	Magenta = "\033[35m"
	Cyan    = "\033[36m"
	White   = "\033[37m"

	// Bright foreground colors.
	BrightBlack   = "\033[90m"
	BrightRed     = "\033[91m"
	BrightGreen   = "\033[92m"
	BrightYellow  = "\033[93m"
	BrightBlue    = "\033[94m"
	BrightMagenta = "\033[95m"
	BrightCyan    = "\033[96m"
	BrightWhite   = "\033[97m"

	// Background colors.
	BgBlack   = "\033[40m"
	BgRed     = "\033[41m"
	BgGreen   = "\033[42m"
	BgYellow  = "\033[43m"
	BgBlue    = "\033[44m"
	BgMagenta = "\033[45m"
	BgCyan    = "\033[46m"
	BgWhite   = "\033[47m"
)

Extended ANSI color codes and styles.

Variables

View Source
var (
	// Basic type constructors.
	String = func(key, val string) Field {
		return ZapField{zap.String(key, val)}
	}

	Int = func(key string, val int) Field {
		return ZapField{zap.Int(key, val)}
	}

	Int8 = func(key string, val int8) Field {
		return ZapField{zap.Int8(key, val)}
	}

	Int16 = func(key string, val int16) Field {
		return ZapField{zap.Int16(key, val)}
	}

	Int32 = func(key string, val int32) Field {
		return ZapField{zap.Int32(key, val)}
	}

	Int64 = func(key string, val int64) Field {
		return ZapField{zap.Int64(key, val)}
	}

	Uint = func(key string, val uint) Field {
		return ZapField{zap.Uint(key, val)}
	}

	Uint8 = func(key string, val uint8) Field {
		return ZapField{zap.Uint8(key, val)}
	}

	Uint16 = func(key string, val uint16) Field {
		return ZapField{zap.Uint16(key, val)}
	}

	Uint32 = func(key string, val uint32) Field {
		return ZapField{zap.Uint32(key, val)}
	}

	Uint64 = func(key string, val uint64) Field {
		return ZapField{zap.Uint64(key, val)}
	}

	Float32 = func(key string, val float32) Field {
		return ZapField{zap.Float32(key, val)}
	}

	Float64 = func(key string, val float64) Field {
		return ZapField{zap.Float64(key, val)}
	}

	Bool = func(key string, val bool) Field {
		return ZapField{zap.Bool(key, val)}
	}

	// Time and duration constructors.
	Time = func(key string, val time.Time) Field {
		return ZapField{zap.Time(key, val)}
	}

	Duration = func(key string, val time.Duration) Field {
		return ZapField{zap.Duration(key, val)}
	}

	// Error constructor.
	Error = func(err error) Field {
		return ZapField{zap.Error(err)}
	}

	// Advanced constructors.
	Stringer = func(key string, val fmt.Stringer) Field {
		return ZapField{zap.Stringer(key, val)}
	}

	Any = func(key string, val any) Field {
		return ZapField{zap.Any(key, val)}
	}

	Namespace = func(key string) Field {
		return ZapField{zap.Namespace(key)}
	}

	Binary = func(key string, val []byte) Field {
		return ZapField{zap.Binary(key, val)}
	}

	ByteString = func(key string, val []byte) Field {
		return ZapField{zap.ByteString(key, val)}
	}

	Reflect = func(key string, val any) Field {
		return ZapField{zap.Reflect(key, val)}
	}

	Complex64 = func(key string, val complex64) Field {
		return ZapField{zap.Complex64(key, val)}
	}

	Complex128 = func(key string, val complex128) Field {
		return ZapField{zap.Complex128(key, val)}
	}

	Object = func(key string, val zapcore.ObjectMarshaler) Field {
		return ZapField{zap.Object(key, val)}
	}

	Array = func(key string, val zapcore.ArrayMarshaler) Field {
		return ZapField{zap.Array(key, val)}
	}

	Stack = func(key string) Field {
		return ZapField{zap.Stack(key)}
	}

	Strings = func(key string, val []string) Field {
		return ZapField{zap.Strings(key, val)}
	}
)

Enhanced field constructors that return wrapped fields.

View Source
var (
	// HTTP-related fields.
	HTTPMethod = func(method string) Field {
		return String("http.method", method)
	}

	HTTPStatus = func(status int) Field {
		return Int("http.status", status)
	}

	HTTPPath = func(path string) Field {
		return String("http.path", path)
	}

	HTTPURL = func(url *url.URL) Field {
		if url == nil {
			return String("http.url", "")
		}

		return String("http.url", url.String())
	}

	HTTPUserAgent = func(userAgent string) Field {
		return String("http.user_agent", userAgent)
	}

	// Database-related fields.
	DatabaseQuery = func(query string) Field {
		return String("db.query", query)
	}

	DatabaseTable = func(table string) Field {
		return String("db.table", table)
	}

	DatabaseRows = func(rows int64) Field {
		return Int64("db.rows", rows)
	}

	// Service-related fields.
	ServiceName = func(name string) Field {
		return String("service.name", name)
	}

	ServiceVersion = func(version string) Field {
		return String("service.version", version)
	}

	ServiceEnvironment = func(env string) Field {
		return String("service.environment", env)
	}

	// Performance-related fields.
	LatencyMs = func(latency time.Duration) Field {
		return Float64("latency.ms", float64(latency.Nanoseconds())/1e6)
	}

	MemoryUsage = func(bytes int64) Field {
		return Int64("memory.usage", bytes)
	}

	// Custom field constructors.
	Custom = func(key string, value any) Field {
		return CustomField{key: key, value: value}
	}

	Lazy = func(key string, valueFunc func() any) Field {
		return LazyField{key: key, valueFunc: valueFunc}
	}

	// Conditional field - only adds field if condition is true.
	Conditional = func(condition bool, key string, value any) Field {
		if condition {
			return Custom(key, value)
		}

		return nil
	}

	// Nullable field - only adds field if value is not nil.
	Nullable = func(key string, value any) Field {
		if value != nil {
			return Custom(key, value)
		}

		return nil
	}
)

Additional utility field constructors.

View Source
var (
	// Request context fields.
	RequestID = func(ctx context.Context) Field {
		if id := RequestIDFromContext(ctx); id != "" {
			return String("request_id", id)
		}

		return nil
	}

	TraceID = func(ctx context.Context) Field {
		if id := TraceIDFromContext(ctx); id != "" {
			return String("trace_id", id)
		}

		return nil
	}

	UserID = func(ctx context.Context) Field {
		if id := UserIDFromContext(ctx); id != "" {
			return String("user_id", id)
		}

		return nil
	}

	// Combined context fields.
	ContextFields = func(ctx context.Context) []Field {
		var fields []Field
		if id := RequestIDFromContext(ctx); id != "" {
			fields = append(fields, String("request_id", id))
		}
		if id := TraceIDFromContext(ctx); id != "" {
			fields = append(fields, String("trace_id", id))
		}
		if id := UserIDFromContext(ctx); id != "" {
			fields = append(fields, String("user_id", id))
		}

		return fields
	}
)

Context-aware field constructors.

View Source
var (
	// HTTPRequestGroup creates a group of HTTP request fields.
	HTTPRequestGroup = func(method, path, userAgent string, status int) *FieldGroup {
		return NewFieldGroup(
			HTTPMethod(method),
			HTTPPath(path),
			HTTPUserAgent(userAgent),
			HTTPStatus(status),
		)
	}

	// DatabaseQueryGroup creates a group of database query fields.
	DatabaseQueryGroup = func(query, table string, rows int64, duration time.Duration) *FieldGroup {
		return NewFieldGroup(
			DatabaseQuery(query),
			DatabaseTable(table),
			DatabaseRows(rows),
			Duration("query_duration", duration),
		)
	}

	// ServiceInfoGroup creates a group of service information fields.
	ServiceInfoGroup = func(name, version, environment string) *FieldGroup {
		return NewFieldGroup(
			ServiceName(name),
			ServiceVersion(version),
			ServiceEnvironment(environment),
		)
	}
)

Predefined field groups.

View Source
var (
	DebugColors = ColorScheme{
		Level:     Dim + Cyan,
		Timestamp: Dim + BrightBlack,
		Message:   Cyan,
		Fields:    Dim + Cyan,
		Key:       BrightCyan,
		Value:     Cyan,
	}

	InfoColors = ColorScheme{
		Level:     Bold + Green,
		Timestamp: Dim + BrightBlack,
		Message:   White,
		Fields:    Green,
		Key:       BrightGreen,
		Value:     Green,
	}

	WarnColors = ColorScheme{
		Level:     Bold + Yellow,
		Timestamp: Dim + BrightBlack,
		Message:   Yellow,
		Fields:    Yellow,
		Key:       BrightYellow,
		Value:     Yellow,
	}

	ErrorColors = ColorScheme{
		Level:     Bold + Red,
		Timestamp: Dim + BrightBlack,
		Message:   BrightRed,
		Fields:    Red,
		Key:       BrightRed,
		Value:     Red,
	}

	FatalColors = ColorScheme{
		Level:     Bold + BgRed + White,
		Timestamp: Dim + BrightBlack,
		Message:   Bold + Magenta,
		Fields:    Magenta,
		Key:       BrightMagenta,
		Value:     Magenta,
	}
)

Log level color schemes.

Functions

func ConditionalLog

func ConditionalLog(condition bool, logger Logger, level string, msg string, fields ...Field)

ConditionalLog logs only if condition is true.

func FieldMap

func FieldMap(fields []Field) map[string]any

FieldMap creates a map representation of fields for debugging.

func FieldsToZap

func FieldsToZap(fields []Field) []zap.Field

FieldsToZap converts Field interfaces to zap.Field efficiently.

func LogPanic

func LogPanic(logger Logger, recovered any)

LogPanic logs a panic with stack trace.

func LogPanicWithFields

func LogPanicWithFields(logger Logger, recovered any, fields ...Field)

LogPanicWithFields logs a panic with additional fields.

func Must

func Must(err error, logger Logger, msg string, fields ...Field)

Must wraps a function call and logs any error fatally.

func MustNotNil

func MustNotNil(value any, logger Logger, msg string, fields ...Field)

MustNotNil logs fatally if value is nil.

func RequestIDFromContext

func RequestIDFromContext(ctx context.Context) string

RequestIDFromContext extracts the request ID from the context.

func SetGlobalLogger

func SetGlobalLogger(l Logger)

SetGlobalLogger sets the global logger instance.

func TraceIDFromContext

func TraceIDFromContext(ctx context.Context) string

TraceIDFromContext extracts the trace ID from the context.

func Track

func Track(ctx context.Context, name string) func()

Track logs the execution time of a function.

func TrackWithFields

func TrackWithFields(ctx context.Context, name string, fields ...Field) func()

TrackWithFields logs the execution time with additional fields.

func TrackWithLogger

func TrackWithLogger(logger Logger, name string) func()

TrackWithLogger logs the execution time using a specific logger.

func UserIDFromContext

func UserIDFromContext(ctx context.Context) string

UserIDFromContext extracts the user ID from the context.

func ValidateField

func ValidateField(field Field) error

ValidateField validates a field and returns an error if invalid.

func WithLogger

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

WithLogger adds a logger to the context.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds a request ID to the context.

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID adds a trace ID to the context.

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds a user ID to the context.

Types

type BeautifulColorScheme added in v0.3.0

type BeautifulColorScheme struct {
	Debug     string
	Info      string
	Warn      string
	Error     string
	Fatal     string
	Banner    string
	Text      string
	Secondary string
	Caller    string
	Dim       string
	Reset     string
}

BeautifulColorScheme defines the color palette for beautiful output.

func DefaultBeautifulColorScheme added in v0.3.0

func DefaultBeautifulColorScheme() *BeautifulColorScheme

DefaultBeautifulColorScheme provides a modern minimalist color scheme.

type BeautifulLogger added in v0.3.0

type BeautifulLogger struct {
	// contains filtered or unexported fields
}

BeautifulLogger is a visually appealing alternative logger implementation with CLI-style output, caller information, and configurable formatting.

func NewBeautifulLogger added in v0.3.0

func NewBeautifulLogger(name string) *BeautifulLogger

NewBeautifulLogger creates a new beautiful logger with defaults.

func NewBeautifulLoggerCompact added in v0.3.0

func NewBeautifulLoggerCompact(name string) *BeautifulLogger

NewBeautifulLoggerCompact creates a compact logger optimized for high-frequency logs.

func NewBeautifulLoggerJSON added in v0.3.0

func NewBeautifulLoggerJSON(name string) *BeautifulLogger

NewBeautifulLoggerJSON creates a logger similar to JSON output (caller, fields, timestamp).

func NewBeautifulLoggerMinimal added in v0.3.0

func NewBeautifulLoggerMinimal(name string) *BeautifulLogger

NewBeautifulLoggerMinimal creates an ultra-minimal logger.

func (*BeautifulLogger) Debug added in v0.3.0

func (bl *BeautifulLogger) Debug(msg string, fields ...Field)

func (*BeautifulLogger) Debugf added in v0.3.0

func (bl *BeautifulLogger) Debugf(template string, args ...any)

func (*BeautifulLogger) Error added in v0.3.0

func (bl *BeautifulLogger) Error(msg string, fields ...Field)

func (*BeautifulLogger) Errorf added in v0.3.0

func (bl *BeautifulLogger) Errorf(template string, args ...any)

func (*BeautifulLogger) Fatal added in v0.3.0

func (bl *BeautifulLogger) Fatal(msg string, fields ...Field)

func (*BeautifulLogger) Fatalf added in v0.3.0

func (bl *BeautifulLogger) Fatalf(template string, args ...any)

func (*BeautifulLogger) Info added in v0.3.0

func (bl *BeautifulLogger) Info(msg string, fields ...Field)

func (*BeautifulLogger) Infof added in v0.3.0

func (bl *BeautifulLogger) Infof(template string, args ...any)

func (*BeautifulLogger) Named added in v0.3.0

func (bl *BeautifulLogger) Named(name string) Logger

func (*BeautifulLogger) Sugar added in v0.3.0

func (bl *BeautifulLogger) Sugar() SugarLogger

func (*BeautifulLogger) Sync added in v0.3.0

func (bl *BeautifulLogger) Sync() error

func (*BeautifulLogger) Warn added in v0.3.0

func (bl *BeautifulLogger) Warn(msg string, fields ...Field)

func (*BeautifulLogger) Warnf added in v0.3.0

func (bl *BeautifulLogger) Warnf(template string, args ...any)

func (*BeautifulLogger) With added in v0.3.0

func (bl *BeautifulLogger) With(fields ...Field) Logger

func (*BeautifulLogger) WithContext added in v0.3.0

func (bl *BeautifulLogger) WithContext(ctx context.Context) Logger

func (*BeautifulLogger) WithFormatConfig added in v0.3.0

func (bl *BeautifulLogger) WithFormatConfig(cfg FormatConfig) *BeautifulLogger

WithFormatConfig sets the format configuration.

func (*BeautifulLogger) WithLevel added in v0.3.0

func (bl *BeautifulLogger) WithLevel(level zapcore.Level) *BeautifulLogger

WithLevel sets the log level.

func (*BeautifulLogger) WithMinimalist added in v0.3.0

func (bl *BeautifulLogger) WithMinimalist(minimalist bool) *BeautifulLogger

WithMinimalist enables ultra-minimal output.

func (*BeautifulLogger) WithShowCaller added in v0.3.0

func (bl *BeautifulLogger) WithShowCaller(show bool) *BeautifulLogger

WithShowCaller enables/disables caller information.

func (*BeautifulLogger) WithShowTimestamp added in v0.3.0

func (bl *BeautifulLogger) WithShowTimestamp(show bool) *BeautifulLogger

WithShowTimestamp enables/disables timestamp.

type ColorScheme

type ColorScheme struct {
	Level     string
	Timestamp string
	Message   string
	Fields    string
	Key       string
	Value     string
}

ColorScheme defines colors for different log components.

type ColoredWriteSyncer

type ColoredWriteSyncer struct {
	zapcore.WriteSyncer
}

ColoredWriteSyncer wraps WriteSyncer to add full-line coloring and fix spacing.

func (*ColoredWriteSyncer) Write

func (w *ColoredWriteSyncer) Write(p []byte) (n int, err error)

Write implements io.Writer with enhanced line coloring and spacing fixes.

type CustomField

type CustomField struct {
	// contains filtered or unexported fields
}

CustomField represents a field with custom key-value pairs.

func (CustomField) Key

func (f CustomField) Key() string

Key returns the field's key.

func (CustomField) Value

func (f CustomField) Value() any

Value returns the field's value.

func (CustomField) ZapField

func (f CustomField) ZapField() zap.Field

ZapField converts to zap.Field.

type ErrorHandler

type ErrorHandler struct {
	// contains filtered or unexported fields
}

ErrorHandler provides a callback-based error handler with logging.

func NewErrorHandler

func NewErrorHandler(logger Logger, callback func(error)) *ErrorHandler

NewErrorHandler creates a new error handler.

func (*ErrorHandler) Handle

func (eh *ErrorHandler) Handle(err error, msg string, fields ...Field)

Handle handles an error by logging it and calling the callback.

func (*ErrorHandler) HandleWithLevel

func (eh *ErrorHandler) HandleWithLevel(err error, level string, msg string, fields ...Field)

HandleWithLevel handles an error at a specific log level.

type Field

type Field interface {
	Key() string
	Value() any
	// ZapField returns the underlying zap.Field for efficient conversion
	ZapField() zap.Field
}

Field represents a structured log field.

func MergeFields

func MergeFields(fieldSlices ...[]Field) []Field

MergeFields merges multiple field slices into one.

func NewField

func NewField(key string, value any) Field

NewField creates a new field.

func SanitizeFields

func SanitizeFields(fields []Field) []Field

SanitizeFields removes nil and invalid fields.

func WrapZapField

func WrapZapField(zapField zap.Field) Field

WrapZapField wraps a zap.Field to implement the Field interface.

func WrapZapFields

func WrapZapFields(zapFields []zap.Field) []Field

WrapZapFields wraps multiple zap.Fields.

type FieldGroup

type FieldGroup struct {
	// contains filtered or unexported fields
}

FieldGroup represents a group of related fields.

func NewFieldGroup

func NewFieldGroup(fields ...Field) *FieldGroup

NewFieldGroup creates a new field group.

func (*FieldGroup) Add

func (fg *FieldGroup) Add(fields ...Field) *FieldGroup

Add adds fields to the group.

func (*FieldGroup) Fields

func (fg *FieldGroup) Fields() []Field

Fields returns all fields in the group.

func (*FieldGroup) ZapFields

func (fg *FieldGroup) ZapFields() []zap.Field

ZapFields converts all fields to zap.Fields.

type FormatConfig added in v0.3.0

type FormatConfig struct {
	// Timestamp options
	ShowTimestamp   bool
	TimestampFormat string // "15:04:05", "2006-01-02 15:04:05.000", "unix", "unixmillis"

	// Caller options (file:line information)
	ShowCaller     bool
	CallerFormat   string // "short" (file:line), "full" (package/file:line), "path" (full path)
	SkipCallerPath int    // Number of levels to skip in call stack (default 3)

	// Field options
	ShowFields     bool
	FieldsFormat   string // "tree" (├─), "inline" (key=value), "json"
	MaxFieldLength int    // Max length per field value (0 = unlimited)

	// Logger name options
	ShowLoggerName bool

	// Output format
	ShowEmojis bool // Show emoji icons
	Minimalist bool // Ultra-minimal output
}

FormatConfig controls what components are shown in the output.

func DefaultFormatConfig added in v0.3.0

func DefaultFormatConfig() FormatConfig

DefaultFormatConfig provides sensible defaults.

type LazyField

type LazyField struct {
	// contains filtered or unexported fields
}

LazyField represents a field that evaluates its value lazily.

func (LazyField) Key

func (f LazyField) Key() string

Key returns the field's key.

func (LazyField) Value

func (f LazyField) Value() any

Value returns the field's value (evaluated lazily).

func (LazyField) ZapField

func (f LazyField) ZapField() zap.Field

ZapField converts to zap.Field.

type LogEntry

type LogEntry struct {
	Level   string
	Message string
	Fields  map[string]any
	Time    time.Time
}

LogEntry represents a log entry.

type LogLevel

type LogLevel string
const (
	LevelInfo  LogLevel = "info"
	LevelWarn  LogLevel = "warn"
	LevelError LogLevel = "error"
	LevelFatal LogLevel = "fatal"
	LevelDebug LogLevel = "debug"
)

type Logger

type Logger interface {
	// Logging levels
	Debug(msg string, fields ...Field)
	Info(msg string, fields ...Field)
	Warn(msg string, fields ...Field)
	Error(msg string, fields ...Field)
	Fatal(msg string, fields ...Field)

	// Formatted logging
	Debugf(template string, args ...any)
	Infof(template string, args ...any)
	Warnf(template string, args ...any)
	Errorf(template string, args ...any)
	Fatalf(template string, args ...any)

	// Context and enrichment
	With(fields ...Field) Logger
	WithContext(ctx context.Context) Logger
	Named(name string) Logger

	// Sugar logger
	Sugar() SugarLogger

	// Utilities
	Sync() error
}

Logger represents the logging interface.

func DatabaseQueryLogger

func DatabaseQueryLogger(logger Logger, query, table string, rows int64, duration time.Duration) Logger

DatabaseQueryLogger creates a logger with database query fields.

func GetGlobalLogger

func GetGlobalLogger() Logger

GetGlobalLogger returns the global logger instance.

func HTTPRequestLogger

func HTTPRequestLogger(logger Logger, method, path, userAgent string, status int) Logger

HTTPRequestLogger creates a logger with HTTP request fields.

func LoggerFromContext

func LoggerFromContext(ctx context.Context) Logger

LoggerFromContext extracts a logger from the context.

func NewDevelopmentLogger

func NewDevelopmentLogger() Logger

NewDevelopmentLogger creates a development logger with enhanced colors.

func NewDevelopmentLoggerWithLevel

func NewDevelopmentLoggerWithLevel(level zapcore.Level) Logger

NewDevelopmentLoggerWithLevel creates a development logger with specified level.

func NewLogger

func NewLogger(config LoggingConfig) Logger

NewLogger creates a new logger with the given configuration.

func NewNoopLogger

func NewNoopLogger() Logger

NewNoopLogger creates a logger that does nothing.

func NewProductionLogger

func NewProductionLogger() Logger

NewProductionLogger creates a production logger.

func NewTestLogger

func NewTestLogger() Logger

func ServiceLogger

func ServiceLogger(logger Logger, name, version, environment string) Logger

ServiceLogger creates a logger with service information fields.

type LoggingConfig

type LoggingConfig struct {
	Level       LogLevel `env:"FORGE_LOG_LEVEL"   mapstructure:"level"       yaml:"level"`
	Format      string   `env:"FORGE_LOG_FORMAT"  mapstructure:"format"      yaml:"format"`
	Environment string   `env:"FORGE_ENVIRONMENT" mapstructure:"environment" yaml:"environment"`
	Output      string   `env:"FORGE_LOG_OUTPUT"  mapstructure:"output"      yaml:"output"`
}

LoggingConfig represents logging configuration.

type LoggingWriter

type LoggingWriter struct {
	// contains filtered or unexported fields
}

LoggingWriter is an io.Writer that logs each write.

func NewLoggingWriter

func NewLoggingWriter(logger Logger, level string) *LoggingWriter

NewLoggingWriter creates a new logging writer.

func (*LoggingWriter) Write

func (lw *LoggingWriter) Write(p []byte) (n int, err error)

Write implements io.Writer.

type PerformanceMonitor

type PerformanceMonitor struct {
	// contains filtered or unexported fields
}

PerformanceMonitor helps monitor performance metrics.

func NewPerformanceMonitor

func NewPerformanceMonitor(logger Logger, operation string) *PerformanceMonitor

NewPerformanceMonitor creates a new performance monitor.

func (*PerformanceMonitor) Finish

func (pm *PerformanceMonitor) Finish()

Finish logs the completion of the monitored operation.

func (*PerformanceMonitor) FinishWithError

func (pm *PerformanceMonitor) FinishWithError(err error)

FinishWithError logs the completion of the monitored operation with an error.

func (*PerformanceMonitor) WithField

func (pm *PerformanceMonitor) WithField(field Field) *PerformanceMonitor

WithField adds a field to the performance monitor.

func (*PerformanceMonitor) WithFields

func (pm *PerformanceMonitor) WithFields(fields ...Field) *PerformanceMonitor

WithFields adds multiple fields to the performance monitor.

type StructuredLog

type StructuredLog struct {
	// contains filtered or unexported fields
}

StructuredLog provides a fluent interface for structured logging.

func NewStructuredLog

func NewStructuredLog(logger Logger) *StructuredLog

NewStructuredLog creates a new structured log.

func (*StructuredLog) Debug

func (sl *StructuredLog) Debug(msg string)

Debug logs at debug level.

func (*StructuredLog) Error

func (sl *StructuredLog) Error(msg string)

Error logs at error level.

func (*StructuredLog) Fatal

func (sl *StructuredLog) Fatal(msg string)

Fatal logs at fatal level.

func (*StructuredLog) Info

func (sl *StructuredLog) Info(msg string)

Info logs at info level.

func (*StructuredLog) Logger

func (sl *StructuredLog) Logger() Logger

Logger returns a logger with all accumulated fields.

func (*StructuredLog) Warn

func (sl *StructuredLog) Warn(msg string)

Warn logs at warn level.

func (*StructuredLog) WithContext

func (sl *StructuredLog) WithContext(ctx context.Context) *StructuredLog

WithContext adds context fields to the structured log.

func (*StructuredLog) WithDatabaseQuery

func (sl *StructuredLog) WithDatabaseQuery(query, table string, rows int64, duration time.Duration) *StructuredLog

WithDatabaseQuery adds database query fields.

func (*StructuredLog) WithField

func (sl *StructuredLog) WithField(field Field) *StructuredLog

WithField adds a field to the structured log.

func (*StructuredLog) WithFields

func (sl *StructuredLog) WithFields(fields ...Field) *StructuredLog

WithFields adds multiple fields to the structured log.

func (*StructuredLog) WithGroup

func (sl *StructuredLog) WithGroup(group *FieldGroup) *StructuredLog

WithGroup adds a field group to the structured log.

func (*StructuredLog) WithHTTPRequest

func (sl *StructuredLog) WithHTTPRequest(method, path, userAgent string, status int) *StructuredLog

WithHTTPRequest adds HTTP request fields.

func (*StructuredLog) WithService

func (sl *StructuredLog) WithService(name, version, environment string) *StructuredLog

WithService adds service information fields.

type SugarLogger

type SugarLogger interface {
	Debugw(msg string, keysAndValues ...any)
	Infow(msg string, keysAndValues ...any)
	Warnw(msg string, keysAndValues ...any)
	Errorw(msg string, keysAndValues ...any)
	Fatalw(msg string, keysAndValues ...any)

	With(args ...any) SugarLogger
}

SugarLogger provides a more flexible API.

type TestLogger

type TestLogger struct {
	// contains filtered or unexported fields
}

TestLogger provides a test logger implementation.

func (*TestLogger) AssertHasLog

func (tl *TestLogger) AssertHasLog(level, message string) bool

AssertLogs checks if expected logs were recorded (only works with TestLogger).

func (*TestLogger) Clear

func (tl *TestLogger) Clear()

Clear clears all log entries.

func (*TestLogger) CountLogs

func (tl *TestLogger) CountLogs(level string) int

CountLogs returns count of logs at a specific level.

func (*TestLogger) Debug

func (tl *TestLogger) Debug(msg string, fields ...Field)

Debug logs a debug message.

func (*TestLogger) Debugf

func (tl *TestLogger) Debugf(template string, args ...any)

func (*TestLogger) Error

func (tl *TestLogger) Error(msg string, fields ...Field)

Error logs an error message.

func (*TestLogger) Errorf

func (tl *TestLogger) Errorf(template string, args ...any)

func (*TestLogger) Fatal

func (tl *TestLogger) Fatal(msg string, fields ...Field)

func (*TestLogger) Fatalf

func (tl *TestLogger) Fatalf(template string, args ...any)

func (*TestLogger) GetLogs

func (tl *TestLogger) GetLogs() []LogEntry

GetLogs returns all logged entries.

func (*TestLogger) GetLogsByLevel

func (tl *TestLogger) GetLogsByLevel(level string) []LogEntry

GetLogsByLevel returns logs filtered by level.

func (*TestLogger) Info

func (tl *TestLogger) Info(msg string, fields ...Field)

Info logs an info message.

func (*TestLogger) Infof

func (tl *TestLogger) Infof(template string, args ...any)

func (*TestLogger) Named

func (tl *TestLogger) Named(name string) Logger

func (*TestLogger) Sugar

func (tl *TestLogger) Sugar() SugarLogger

func (*TestLogger) Sync

func (tl *TestLogger) Sync() error

func (*TestLogger) Warn

func (tl *TestLogger) Warn(msg string, fields ...Field)

Warn logs a warning message.

func (*TestLogger) Warnf

func (tl *TestLogger) Warnf(template string, args ...any)

func (*TestLogger) With

func (tl *TestLogger) With(fields ...Field) Logger

func (*TestLogger) WithContext

func (tl *TestLogger) WithContext(ctx context.Context) Logger

WithContext returns a logger with context.

type ZapField

type ZapField struct {
	// contains filtered or unexported fields
}

ZapField wraps a zap.Field and implements the Field interface.

func (ZapField) Key

func (f ZapField) Key() string

Key returns the field's key.

func (ZapField) Value

func (f ZapField) Value() any

Value returns the field's value.

func (ZapField) ZapField

func (f ZapField) ZapField() zap.Field

ZapField returns the underlying zap.Field.

Jump to

Keyboard shortcuts

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