logger

package
v1.41.2 Latest Latest
Warning

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

Go to latest
Published: Sep 1, 2025 License: Apache-2.0 Imports: 31 Imported by: 200

Documentation

Overview

Package logger provides a flexible logging interface with support for multiple backends (logrus, slog) and various output formats.

The package offers a global logger instance that can be configured with different log levels, output formats, and additional context values.

Basic Usage:

logger.Infof("Server started on port %d", 8080)
logger.Debugf("Processing request: %s", requestID)
logger.Errorf("Failed to connect to database: %v", err)

With Context Values:

log := logger.GetLogger().WithValues("user", userID, "request", requestID)
log.Infof("Processing user request")

Named Loggers:

dbLogger := logger.GetLogger().Named("database")
apiLogger := logger.GetLogger().Named("api")

Log Levels:

logger.SetLogLevel(logger.Debug)  // Enable debug logging
logger.SetLogLevel(logger.Trace)  // Enable trace logging

The package supports standard log levels (Info, Debug, Error, etc.) plus extended trace levels (Trace, Trace1-4) for fine-grained debugging.

Index

Constants

View Source
const (
	Cyan = cyan + Normal

	Magenta   = magenta + Normal
	DarkWhite = "\x1b[38;5;244m"
	Normal    = "m"
	Reset     = "\x1b[0m"
)

Variables

View Source
var CommonRedactedHeaders = []string{
	"Authorization*", "Bearer*", "Session*", "*Cookie", "*Token", "*-Secret", "*-Key",
	"Password", "Passwd", "Pwd",
}
View Source
var SensitiveHeaders = []string{
	"Authorization",
	"Set-Cookie",
	"Cookie",
	"Proxy-Authorization",
	"Cookie",
}
View Source
var SensitiveKeys = []string{"user", "pass", "key", "token", "username", "password"}
View Source
var SkipFrameContains = []string{
	"gorm.io",
	"golang.org/toolchain",
}
View Source
var SkipFrameSuffixes = []string{
	"logger/slog.go",
	"logger/default.go",
	"logger/caller.go",
	"gorm/logger.go",
	"golang.org/toolchain",
}
View Source
var SlogFatal = slog.LevelError + 1
View Source
var SlogTraceLevel slog.Level = slog.LevelDebug - 1

Functions

func BindFlags added in v1.4.0

func BindFlags(flags *pflag.FlagSet)

BindFlags add flags to an existing flag set, note that this is not an actual binding which occurs later during initialization

func BrightF added in v1.26.0

func BrightF(msg string, args ...interface{}) string

func Caller added in v1.26.0

func Caller(skip ...int) string

Caller return the file name and line number of the current file

func CallerPC added in v1.26.0

func CallerPC(skip ...int) uintptr

func Configure added in v1.41.1

func Configure(flags Flags)

func Debugf

func Debugf(format string, args ...interface{})

Debugf logs a debug message with formatting support. These messages are only shown when debug logging is enabled.

func Errorf

func Errorf(format string, args ...interface{})

Errorf logs an error message with formatting support. Use this for errors that need attention but don't terminate the program.

func Fatalf

func Fatalf(format string, args ...interface{})

Fatalf logs a fatal error message and terminates the program. Use this for unrecoverable errors.

func GetCaller added in v1.27.0

func GetCaller(pc ...uintptr) string

func GetNamedLoggingLevels added in v1.26.2

func GetNamedLoggingLevels() (levels map[string]string)

func Infof

func Infof(format string, args ...interface{})

Infof logs an informational message with formatting support. These are general informational messages about normal operations.

func IsDebugEnabled

func IsDebugEnabled() bool

IsDebugEnabled returns true if debug level logging is enabled.

func IsJsonLogs added in v1.20.1

func IsJsonLogs() bool

func IsLevelEnabled added in v1.20.1

func IsLevelEnabled(level int) bool

IsLevelEnabled returns true if the specified verbosity level is enabled.

Example:

if logger.IsLevelEnabled(3) {
    // Perform expensive operation only if logging at level 3
}

func IsSensitiveKey added in v1.30.0

func IsSensitiveKey(v string) bool

func IsTraceEnabled

func IsTraceEnabled() bool

IsTraceEnabled returns true if trace level logging is enabled.

func NewHttpLogger added in v1.29.0

func NewHttpLogger(logger Logger, rt http.RoundTripper) http.RoundTripper

NewHttpLogger creates an HTTP logger that logs at predefined levels. Deprecated: Use NewHttpLoggerWithLevels for more control over logging levels.

Default behavior:

  • Headers and timing: Requires log level 5 (Trace3)
  • Request body: Requires log level 6 (Trace4)
  • Response body: Requires log level 7

func NewHttpLoggerWithLevels added in v1.40.2

func NewHttpLoggerWithLevels(logger Logger, rt http.RoundTripper, headerLevel, bodyLevel LogLevel) http.RoundTripper

NewHttpLoggerWithLevels creates an HTTP logger with configurable log levels for headers and body.

Parameters:

  • logger: The logger instance to use
  • rt: The underlying RoundTripper to wrap
  • headerLevel: Minimum log level required to log headers, timing, and TLS info
  • bodyLevel: Minimum log level required to log request/response bodies

Example:

// Log headers at debug level (-v) and bodies at trace level (-vv)
transport := NewHttpLoggerWithLevels(logger, http.DefaultTransport, logger.Debug, logger.Trace)

func Pretty added in v1.26.0

func Pretty(v any) string

func PrettyYAML added in v1.30.5

func PrettyYAML(s string) string

func Prettyf added in v1.3.0

func Prettyf(msg string, obj interface{})

Prettyf logs a trace message with a pretty-printed representation of the given object. Useful for debugging complex data structures.

Example:

logger.Prettyf("User data:", userStruct) // Logs formatted struct

func PrintableSecret added in v1.26.3

func PrintableSecret(secret string) string

PrintableSecret returns an approximation of a secret, so that it is possible to compare the secrets rudimentally e.g. for "john-doe-jane" it will return ***e Secrets smaller than 10 characters will always return *** These secrets

func SanitizeHeaders added in v1.29.0

func SanitizeHeaders(headers http.Header, redactedHeaders ...string) http.Header

func Secretf added in v1.3.0

func Secretf(format string, args ...interface{})

Secretf logs a trace message after attempting to strip any secrets from the text. It automatically redacts common secret patterns like passwords, tokens, and API keys.

Example:

logger.Secretf("Connecting with password=%s", password) // password will be redacted

func SetLogger added in v1.20.0

func SetLogger(logger Logger)

SetLogger replaces the global logger instance. Use this to configure a custom logger implementation.

func Stacktrace added in v1.26.0

func Stacktrace() string

func StripSecrets added in v1.26.3

func StripSecrets(text string) string

StripSecrets takes a URL, YAML or INI formatted text and removes any potentially secret data as denoted by keys containing "pass" or "secret" or exact matches for "key" the last character of the secret is kept to aid in troubleshooting

func StripSecretsFromMap added in v1.30.5

func StripSecretsFromMap[V comparable](m map[string]V) map[string]any

func Tracef

func Tracef(format string, args ...interface{})

Tracef logs a trace message with formatting support. These are very detailed messages for troubleshooting, only shown at trace level.

func UseCobraFlags added in v1.40.2

func UseCobraFlags(flags *pflag.FlagSet)

UseCobraFlags initializes the logger using values from parsed cobra flags. This should be called after cobra has parsed the command line arguments.

func UseSlog added in v1.26.0

func UseSlog()

func Warnf

func Warnf(format string, args ...interface{})

Warnf logs a warning message with formatting support. These are messages about potentially harmful situations.

Types

type Flags added in v1.41.1

type Flags struct {
	Color, ReportCaller, JsonLogs, LogToStderr bool
	Level                                      string
	LevelCount                                 int
}

type LogLevel added in v1.26.0

type LogLevel int

LogLevel represents the severity of a log message. Higher values indicate more verbose logging.

const (
	Debug  LogLevel = 1
	Trace  LogLevel = 2
	Trace1 LogLevel = 3
	Trace2 LogLevel = 4
	Trace3 LogLevel = 5
	Trace4 LogLevel = 6
	Info   LogLevel = 0
	Warn   LogLevel = -1
	Error  LogLevel = -2
	Fatal  LogLevel = -3
	Silent LogLevel = 10
)

func FromSlogLevel added in v1.26.0

func FromSlogLevel(level slog.Level) LogLevel

func ParseLevel added in v1.26.0

func ParseLevel(logger Logger, level any) LogLevel

func (LogLevel) Slog added in v1.26.0

func (level LogLevel) Slog() slog.Level

func (LogLevel) String added in v1.27.0

func (l LogLevel) String() string

type Logger

type Logger interface {
	Warnf(format string, args ...interface{})
	Infof(format string, args ...interface{})
	Errorf(format string, args ...interface{})
	Debugf(format string, args ...interface{})
	Tracef(format string, args ...interface{})
	Fatalf(format string, args ...interface{})
	// WithValues returns a new Logger with additional key-value pairs
	// that will be included in all subsequent log messages.
	//
	// Example:
	//   log := logger.WithValues("component", "auth", "version", "1.0")
	//   log.Infof("User logged in") // Will include component=auth version=1.0
	WithValues(keysAndValues ...interface{}) Logger
	IsTraceEnabled() bool
	IsDebugEnabled() bool
	IsLevelEnabled(level LogLevel) bool
	GetLevel() LogLevel
	SetLogLevel(level any)
	SetMinLogLevel(level any)
	// V returns a Verbose logger that only logs if the specified level is enabled.
	// Level can be an integer or a named level (Debug, Trace, etc.).
	//
	// Example:
	//   logger.V(2).Infof("This only logs at verbosity 2+")
	//   logger.V(logger.Trace).Infof("This only logs at trace level")
	V(level any) Verbose
	WithV(level any) Logger
	// Named returns a new Logger with the specified name added to the logging context.
	// This helps identify which component or subsystem generated the log.
	//
	// Example:
	//   dbLogger := logger.Named("database")
	//   dbLogger.Infof("Connected to database") // Logs with name="database"
	Named(name string) Logger
	WithoutName() Logger
	WithSkipReportLevel(i int) Logger
	GetSlogLogger() *slog.Logger
}

Logger is the main interface for logging operations. It provides methods for different log levels and supports structured logging with key-value pairs.

func StandardLogger

func StandardLogger() Logger

StandardLogger returns the current global logger instance. This is equivalent to GetLogger().

func WithValues added in v1.4.2

func WithValues(keysAndValues ...interface{}) Logger

WithValues returns a new logger with additional key-value pairs. These values will be included in all log messages from the returned logger.

Example:

userLogger := logger.WithValues("user_id", 123, "session", "abc")
userLogger.Infof("User action") // Logs with user_id=123 session=abc

type SlogLogger added in v1.26.0

type SlogLogger struct {
	*slog.Logger
	Prefix string
	Level  *slog.LevelVar
	Parent *SlogLogger
	// contains filtered or unexported fields
}

func GetLogger added in v1.26.0

func GetLogger(names ...string) *SlogLogger

GetLogger returns a logger instance, optionally with the specified names. If no names are provided, returns the root logger. Multiple names create a hierarchical logger (e.g., GetLogger("app", "db") creates "app.db").

Example:

dbLogger := logger.GetLogger("database")
apiLogger := logger.GetLogger("api", "v1")

func GetSlogLogger added in v1.26.0

func GetSlogLogger() SlogLogger

func New added in v1.26.0

func New(prefix string) *SlogLogger

func (SlogLogger) DebugLevels added in v1.28.0

func (s SlogLogger) DebugLevels()

func (SlogLogger) Debugf added in v1.26.0

func (s SlogLogger) Debugf(format string, args ...interface{})

func (SlogLogger) Errorf added in v1.26.0

func (s SlogLogger) Errorf(format string, args ...interface{})

func (SlogLogger) Fatalf added in v1.26.0

func (s SlogLogger) Fatalf(format string, args ...interface{})

func (SlogLogger) GetLevel added in v1.26.0

func (s SlogLogger) GetLevel() LogLevel

func (SlogLogger) GetSlogLogger added in v1.26.0

func (s SlogLogger) GetSlogLogger() *slog.Logger

func (SlogLogger) Infof added in v1.26.0

func (s SlogLogger) Infof(format string, args ...interface{})

func (SlogLogger) IsDebugEnabled added in v1.26.0

func (s SlogLogger) IsDebugEnabled() bool

func (SlogLogger) IsLevelEnabled added in v1.26.0

func (s SlogLogger) IsLevelEnabled(level LogLevel) bool

func (SlogLogger) IsTraceEnabled added in v1.26.0

func (s SlogLogger) IsTraceEnabled() bool

func (SlogLogger) Named added in v1.26.0

func (s SlogLogger) Named(name string) Logger

func (SlogLogger) Prettyf added in v1.26.0

func (s SlogLogger) Prettyf(msg string, obj interface{})

func (SlogLogger) Secretf added in v1.26.0

func (s SlogLogger) Secretf(format string, args ...interface{})

func (SlogLogger) SetLogLevel added in v1.26.0

func (s SlogLogger) SetLogLevel(level any)

func (SlogLogger) SetMinLogLevel added in v1.26.0

func (s SlogLogger) SetMinLogLevel(level any)

func (SlogLogger) Tracef added in v1.26.0

func (s SlogLogger) Tracef(format string, args ...interface{})

func (SlogLogger) V added in v1.26.0

func (s SlogLogger) V(level any) Verbose

func (SlogLogger) Warnf added in v1.26.0

func (s SlogLogger) Warnf(format string, args ...interface{})

func (SlogLogger) WithSkipReportLevel added in v1.26.0

func (s SlogLogger) WithSkipReportLevel(i int) Logger

func (SlogLogger) WithV added in v1.26.0

func (s SlogLogger) WithV(level any) Logger

func (SlogLogger) WithValues added in v1.26.0

func (s SlogLogger) WithValues(keysAndValues ...interface{}) Logger

func (SlogLogger) WithoutName added in v1.26.0

func (s SlogLogger) WithoutName() Logger

type Verbose added in v1.5.1

type Verbose interface {
	io.Writer
	Infof(format string, args ...interface{})
	WithFilter(filters ...string) Verbose
	Enabled() bool
}

Verbose provides conditional logging based on verbosity levels. It's returned by Logger.V() and only logs if the specified level is enabled.

Example:

// Only logs if verbosity is 2 or higher
logger.V(2).Infof("Detailed debug information: %v", data)

func V added in v1.5.1

func V(level any) Verbose

V returns a verbose logger for conditional logging at the specified level. The level can be an integer or a LogLevel constant.

Example:

logger.V(2).Infof("Detailed info") // Only logs at verbosity 2+

Jump to

Keyboard shortcuts

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