loggers

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Apr 12, 2026 License: Apache-2.0 Imports: 5 Imported by: 3

README

CI Go Report Card GoDoc

loggers

import "github.com/go-coldbrew/log/loggers"

Package loggers provides loggers implementation for log package

Index

Constants

These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `logs.New()`.

const (
    // ErrorLevel level. Logs. Used for errors that should definitely be noted.
    // Commonly used for hooks to send errors to an error tracking service.
    ErrorLevel = iota
    // WarnLevel level. Non-critical entries that deserve eyes.
    WarnLevel
    // InfoLevel level. General operational entries about what's going on inside the
    // application.
    InfoLevel
    // DebugLevel level. Usually only enabled when debugging. Very verbose logging.
    DebugLevel
)

MessageKey is the conventional key used for the log message across all backends.

const MessageKey = "msg"

Variables

AllLevels A constant exposing all logging levels

var AllLevels = []Level{
    ErrorLevel,
    WarnLevel,
    InfoLevel,
    DebugLevel,
}

DefaultOptions stores all default options in loggers package These options are used by all loggers

var (
    DefaultOptions = Options{
        ReplaceStdLogger:   false,
        JSONLogs:           true,
        Level:              InfoLevel,
        TimestampFieldName: "@timestamp",
        LevelFieldName:     "level",
        CallerInfo:         true,
        CallerFileDepth:    2,
        CallerFieldName:    "caller",
    }
)

func AddToLogContext

func AddToLogContext(ctx context.Context, key string, value any) context.Context

AddToLogContext adds log fields to context. Any info added here will be added to all logs using this context. If ctx is nil, context.Background() is used.

Example

AddToLogContext adds structured fields at the lower level, useful when building custom logger integrations or interceptors.

package main

import (
	"context"

	"github.com/go-coldbrew/log"
	"github.com/go-coldbrew/log/loggers"
)

func main() {
	ctx := context.Background()

	// Add structured fields that propagate through the interceptor chain
	ctx = loggers.AddToLogContext(ctx, "service", "payment-gateway")
	ctx = loggers.AddToLogContext(ctx, "trace_id", "abc-def-123")

	// These fields appear in every log line that uses this context
	log.Info(ctx, "msg", "charge initiated", "amount", 1999, "currency", "USD")
}

func FetchCallerInfo

func FetchCallerInfo(skip int, depth int) (function string, file string, line int)

FetchCallerInfo fetches function name, file name and line number from stack skip is the number of stack frames to ascend, with 0 identifying the caller of FetchCallerInfo. depth is the depth of file to use in caller info

type BaseLogger

BaseLogger is the interface that needs to be implemented by client loggers.

Deprecated: Implement slog.Handler instead and use log.NewHandlerWithInner to compose it with ColdBrew's context field injection. BaseLogger is kept for backward compatibility and will be removed in a future major version.

type BaseLogger interface {
    // Log logs a message at the given level. The args are key-value pairs.
    // The key must be a string, while the value can be of any type.
    // The message is logged with the given level.
    // Level is the level of the log message.
    // Skip is the number of stack frames to skip before getting the file name and line number.
    // If skip is 0, the file and line of the caller of Log is logged.
    // ctx is the context of the log message. It is used to pass the context fields to the logger
    Log(ctx context.Context, level Level, skip int, args ...any)
    // SetLevel sets the level of the logger
    SetLevel(level Level)
    // GetLevel gets the level of the logger
    GetLevel() Level
}

type Level

Level type

type Level uint32

func ParseLevel
func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the log level constant.

func (Level) String
func (level Level) String() string

Convert the Level to a string. E.g. ErrorLevel becomes "error".

type LogFields

LogFields contains all fields that have to be added to logs. It wraps *options.Options to share the same RequestContext storage, eliminating a separate context.WithValue allocation per request. LogFields should be obtained via FromContext or AddToLogContext; the zero value is safe but acts as a no-op.

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

func FromContext
func FromContext(ctx context.Context) *LogFields

FromContext fetches log fields from provided context.

func (*LogFields) Add
func (o *LogFields) Add(key string, value any)

Add adds or modifies a log field.

func (*LogFields) Del
func (o *LogFields) Del(key string)

Del deletes a log field entry.

func (*LogFields) Delete
func (o *LogFields) Delete(key any)

Delete is a sync.Map-compatible alias for Del.

func (*LogFields) Load
func (o *LogFields) Load(key any) (any, bool)

Load retrieves a value by key.

func (*LogFields) Range
func (o *LogFields) Range(f func(key, value any) bool)

Range calls f sequentially for each key and value in the map. If f returns false, Range stops the iteration. The callback may safely call Add/Del on the same LogFields instance. Uses a slice snapshot for efficient iteration over small field counts.

func (*LogFields) Store
func (o *LogFields) Store(key, value any)

Store is a sync.Map-compatible alias for Add.

type Option

Option defines an option for BaseLogger

type Option func(*Options)

func WithCallerFieldName
func WithCallerFieldName(name string) Option

WithCallerFieldName sets the name of callerinfo field

func WithCallerFileDepth
func WithCallerFileDepth(depth int) Option

WithCallerFileDepth sets the depth of file to use in caller info

func WithCallerInfo
func WithCallerInfo(callerInfo bool) Option

WithCallerInfo enables/disables adding caller info to logs

func WithJSONLogs
func WithJSONLogs(json bool) Option

WithJSONLogs enables/disables json logs

func WithLevel
func WithLevel(level Level) Option

WithLevel sets the log level

func WithLevelFieldName
func WithLevelFieldName(name string) Option

WithLevelFieldName sets the name of the level field in logs

func WithReplaceStdLogger
func WithReplaceStdLogger(replaceStdLogger bool) Option

WithReplaceStdLogger enables/disables replacing std logger

func WithTimestampFieldName
func WithTimestampFieldName(name string) Option

WithTimestampFieldName sets the name of the time stamp field in logs

type Options

Options contain all common options for BaseLoggers

type Options struct {
    // ReplaceStdLogger replaces std logger with this logger
    ReplaceStdLogger bool
    // JSONLogs enables/disables json logs
    JSONLogs bool
    // Level is the level of the logger
    Level Level
    // TimestampFieldName is the name of the timestamp field in logs
    TimestampFieldName string
    // LevelFieldName is the name of the level field in logs
    LevelFieldName string
    // CallerInfo enables/disables adding caller info to logs
    CallerInfo bool
    // CallerFileDepth is the depth of file to use in caller info
    CallerFileDepth int
    // CallerFieldName is the name of callerinfo field
    CallerFieldName string
}

func GetDefaultOptions
func GetDefaultOptions() Options

GetDefaultOptions fetches loggers default options

Generated by gomarkdoc

Documentation

Overview

Package loggers provides loggers implementation for log package

Index

Examples

Constants

View Source
const (
	// ErrorLevel level. Logs. Used for errors that should definitely be noted.
	// Commonly used for hooks to send errors to an error tracking service.
	ErrorLevel = iota
	// WarnLevel level. Non-critical entries that deserve eyes.
	WarnLevel
	// InfoLevel level. General operational entries about what's going on inside the
	// application.
	InfoLevel
	// DebugLevel level. Usually only enabled when debugging. Very verbose logging.
	DebugLevel
)

These are the different logging levels. You can set the logging level to log on your instance of logger, obtained with `logs.New()`.

View Source
const MessageKey = "msg"

MessageKey is the conventional key used for the log message across all backends.

Variables

AllLevels A constant exposing all logging levels

View Source
var (
	DefaultOptions = Options{
		ReplaceStdLogger:   false,
		JSONLogs:           true,
		Level:              InfoLevel,
		TimestampFieldName: "@timestamp",
		LevelFieldName:     "level",
		CallerInfo:         true,
		CallerFileDepth:    2,
		CallerFieldName:    "caller",
	}
)

DefaultOptions stores all default options in loggers package These options are used by all loggers

Functions

func AddToLogContext

func AddToLogContext(ctx context.Context, key string, value any) context.Context

AddToLogContext adds log fields to context. Any info added here will be added to all logs using this context. If ctx is nil, context.Background() is used.

Example

AddToLogContext adds structured fields at the lower level, useful when building custom logger integrations or interceptors.

package main

import (
	"context"

	"github.com/go-coldbrew/log"
	"github.com/go-coldbrew/log/loggers"
)

func main() {
	ctx := context.Background()

	// Add structured fields that propagate through the interceptor chain
	ctx = loggers.AddToLogContext(ctx, "service", "payment-gateway")
	ctx = loggers.AddToLogContext(ctx, "trace_id", "abc-def-123")

	// These fields appear in every log line that uses this context
	log.Info(ctx, "msg", "charge initiated", "amount", 1999, "currency", "USD")
}

func FetchCallerInfo

func FetchCallerInfo(skip int, depth int) (function string, file string, line int)

FetchCallerInfo fetches function name, file name and line number from stack skip is the number of stack frames to ascend, with 0 identifying the caller of FetchCallerInfo. depth is the depth of file to use in caller info

Types

type BaseLogger deprecated

type BaseLogger interface {
	// Log logs a message at the given level. The args are key-value pairs.
	// The key must be a string, while the value can be of any type.
	// The message is logged with the given level.
	// Level is the level of the log message.
	// Skip is the number of stack frames to skip before getting the file name and line number.
	// If skip is 0, the file and line of the caller of Log is logged.
	// ctx is the context of the log message. It is used to pass the context fields to the logger
	Log(ctx context.Context, level Level, skip int, args ...any)
	// SetLevel sets the level of the logger
	SetLevel(level Level)
	// GetLevel gets the level of the logger
	GetLevel() Level
}

BaseLogger is the interface that needs to be implemented by client loggers.

Deprecated: Implement slog.Handler instead and use log.NewHandlerWithInner to compose it with ColdBrew's context field injection. BaseLogger is kept for backward compatibility and will be removed in a future major version.

type Level

type Level uint32

Level type

func ParseLevel

func ParseLevel(lvl string) (Level, error)

ParseLevel takes a string level and returns the log level constant.

func (Level) String

func (level Level) String() string

Convert the Level to a string. E.g. ErrorLevel becomes "error".

type LogFields

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

LogFields contains all fields that have to be added to logs. It wraps *options.Options to share the same RequestContext storage, eliminating a separate context.WithValue allocation per request. LogFields should be obtained via FromContext or AddToLogContext; the zero value is safe but acts as a no-op.

func FromContext

func FromContext(ctx context.Context) *LogFields

FromContext fetches log fields from provided context.

func (*LogFields) Add

func (o *LogFields) Add(key string, value any)

Add adds or modifies a log field.

func (*LogFields) Del

func (o *LogFields) Del(key string)

Del deletes a log field entry.

func (*LogFields) Delete added in v0.2.9

func (o *LogFields) Delete(key any)

Delete is a sync.Map-compatible alias for Del.

func (*LogFields) Load added in v0.2.9

func (o *LogFields) Load(key any) (any, bool)

Load retrieves a value by key.

func (*LogFields) Range added in v0.2.9

func (o *LogFields) Range(f func(key, value any) bool)

Range calls f sequentially for each key and value in the map. If f returns false, Range stops the iteration. The callback may safely call Add/Del on the same LogFields instance. Uses a slice snapshot for efficient iteration over small field counts.

func (*LogFields) Store added in v0.2.9

func (o *LogFields) Store(key, value any)

Store is a sync.Map-compatible alias for Add.

type Option

type Option func(*Options)

Option defines an option for BaseLogger

func WithCallerFieldName

func WithCallerFieldName(name string) Option

WithCallerFieldName sets the name of callerinfo field

func WithCallerFileDepth

func WithCallerFileDepth(depth int) Option

WithCallerFileDepth sets the depth of file to use in caller info

func WithCallerInfo

func WithCallerInfo(callerInfo bool) Option

WithCallerInfo enables/disables adding caller info to logs

func WithJSONLogs

func WithJSONLogs(json bool) Option

WithJSONLogs enables/disables json logs

func WithLevel added in v0.2.8

func WithLevel(level Level) Option

WithLevel sets the log level

func WithLevelFieldName

func WithLevelFieldName(name string) Option

WithLevelFieldName sets the name of the level field in logs

func WithReplaceStdLogger

func WithReplaceStdLogger(replaceStdLogger bool) Option

WithReplaceStdLogger enables/disables replacing std logger

func WithTimestampFieldName

func WithTimestampFieldName(name string) Option

WithTimestampFieldName sets the name of the time stamp field in logs

type Options

type Options struct {
	// ReplaceStdLogger replaces std logger with this logger
	ReplaceStdLogger bool
	// JSONLogs enables/disables json logs
	JSONLogs bool
	// Level is the level of the logger
	Level Level
	// TimestampFieldName is the name of the timestamp field in logs
	TimestampFieldName string
	// LevelFieldName is the name of the level field in logs
	LevelFieldName string
	// CallerInfo enables/disables adding caller info to logs
	CallerInfo bool
	// CallerFileDepth is the depth of file to use in caller info
	CallerFileDepth int
	// CallerFieldName is the name of callerinfo field
	CallerFieldName string
}

Options contain all common options for BaseLoggers

func GetDefaultOptions

func GetDefaultOptions() Options

GetDefaultOptions fetches loggers default options

Jump to

Keyboard shortcuts

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