Documentation
¶
Overview ¶
Package log provides a high-performance logging library with advanced features including rate limiting, buffering, event grouping, and configurable output formats.
Buffering Control ¶
The library supports both buffered and unbuffered logging modes:
Buffered Mode (default):
- Messages are queued in a buffer and processed asynchronously
- High throughput with minimal impact on application performance
- Messages may be dropped if buffer is full (backpressure handling)
- Suitable for high-frequency logging scenarios
Unbuffered Mode:
- Messages are written directly to the output with rate limiting
- Immediate writing ensures no message loss due to buffering
- Lower throughput but guaranteed message delivery
- Suitable for critical logging where message loss is unacceptable
Environment Variables ¶
The following environment variables control logging behavior:
- LOG_DISABLE_BUFFERING: Set to "true", "1", or "yes" to disable buffering
- LOG_BUFFER_SIZE: Buffer size for buffered mode (default: 100000)
- LOG_RATE_LIMIT: Rate limit in messages per second (default: 50000)
- LOG_RATE_BURST: Burst size for rate limiting (default: 10000)
- LOG_GROUP_WINDOW: Event grouping window in seconds (default: 1)
- LOG_DROP_REPORT_INTERVAL: Drop report interval in seconds (default: 10)
- LOG_LEVEL: Log level (debug, info, warn, error, fatal, panic)
- LOG_FORMAT: Output format (json, console)
Usage Examples ¶
Basic usage with default configuration:
logger := log.NewLogger().Build() logger.Info().Msg("This is a buffered log message") logger.Close() // Flush remaining messages
Configure with builder pattern:
logger := log.NewLogger(). WithoutBuffering(). WithGroupWindow(5 * time.Second). AsJSON(). Build() logger.Info().Msg("This message is written immediately with 5s grouping")
Disable buffering via environment variable:
os.Setenv("LOG_DISABLE_BUFFERING", "true") logger := log.NewLogger().Build() logger.Info().Msg("This message is written immediately")
Create unbuffered logger with builder:
logger := log.NewLogger().WithoutBuffering().Build() logger.Info().Msg("This message is written immediately")
Unbuffered with grouping disabled:
logger := log.NewLogger().WithoutBuffering().WithoutGrouping().Build() logger.Info().Msg("No buffering, no grouping")
Package log provides global logger functionality and state management. This file contains all global logger objects and functions that were moved from log.go to improve code organization and maintainability.
Index ¶
- Constants
- Variables
- func AllLogFormatsStrings() []string
- func Close()
- func Debug(packageName string, msg any)
- func Debugf(packageName string, format string, msg ...any)
- func Error(packageName string, err error, msg any)
- func Errorf(packageName string, err error, format string, msg ...any)
- func EventHash(event []byte) string
- func Fatal(packageName string, err error, msg any)
- func Fatalf(packageName string, err error, format string, msg ...any)
- func Flush()
- func GroupEvents(events [][]byte) map[uint64][][]byte
- func Hash(data []byte) uint64
- func Info(packageName string, msg any)
- func Infof(packageName string, format string, msg ...any)
- func IsValidLogFormat(s string) bool
- func Panic(packageName string, err error, msg any)
- func Panicf(packageName string, err error, format string, msg ...any)
- func PreferredWriter() io.Writer
- func PrettyYaml(data any) ([]byte, error)
- func PrettyYamlString(data any) string
- func Print(packageName string, msg any)
- func Printf(packageName string, format string, msg ...any)
- func SetGlobalLogger(logger *CustomLogger)
- func SetGlobalLoggerBuilder(builder *LoggerBuilder)
- func SetGlobalLoggerLogFormat(logFormat string) error
- func SetGlobalLoggerLogLevel(level string) error
- func Trace(packageName string, msg any)
- func Tracef(packageName string, format string, msg ...any)
- func Warn(packageName string, msg any)
- func Warnf(packageName string, format string, msg ...any)
- type BufferedRateLimitedWriter
- type CustomLogger
- type GoLoggingV1Backend
- type LogFormat
- type LoggerBuilder
- func (lb *LoggerBuilder) AsJSON() *LoggerBuilder
- func (lb *LoggerBuilder) Build() *CustomLogger
- func (lb *LoggerBuilder) WithBufferSize(size int) *LoggerBuilder
- func (lb *LoggerBuilder) WithDropReportInterval(interval time.Duration) *LoggerBuilder
- func (lb *LoggerBuilder) WithGroupWindow(window time.Duration) *LoggerBuilder
- func (lb *LoggerBuilder) WithLogLevel(level zerolog.Level) *LoggerBuilder
- func (lb *LoggerBuilder) WithLogLevelString(level string) *LoggerBuilder
- func (lb *LoggerBuilder) WithOutput(output io.Writer) *LoggerBuilder
- func (lb *LoggerBuilder) WithRateBurst(burst int) *LoggerBuilder
- func (lb *LoggerBuilder) WithRateLimit(limit int) *LoggerBuilder
- func (lb *LoggerBuilder) WithoutBuffering() *LoggerBuilder
- func (lb *LoggerBuilder) WithoutGrouping() *LoggerBuilder
Constants ¶
const ( // ENV_LOG_LEVEL is the environment variable for the log level. ENV_LOG_LEVEL = "LOG_LEVEL" // ENV_LOG_FORMAT is the environment variable for the log format. ENV_LOG_FORMAT = "LOG_FORMAT" // ENV_LOG_BUFFER_SIZE is the environment variable for the log buffer size. ENV_LOG_BUFFER_SIZE = "LOG_BUFFER_SIZE" // ENV_LOG_RATE_LIMIT is the environment variable for the log rate limit. ENV_LOG_RATE_LIMIT = "LOG_RATE_LIMIT" // messages per second // ENV_LOG_RATE_BURST is the environment variable for the log rate burst size. ENV_LOG_RATE_BURST = "LOG_RATE_BURST" // burst size // ENV_LOG_DROP_REPORT_INTERVAL is the environment variable for the log drop report interval. ENV_LOG_DROP_REPORT_INTERVAL = "LOG_DROP_REPORT_INTERVAL" // seconds between drop reports // ENV_LOG_GROUP_WINDOW is the environment variable for the log event grouping window. ENV_LOG_GROUP_WINDOW = "LOG_GROUP_WINDOW" // seconds for event grouping window // ENV_LOG_DISABLE_BUFFERING is the environment variable to disable buffering. ENV_LOG_DISABLE_BUFFERING = "LOG_DISABLE_BUFFERING" // set to "true" to disable buffering // DEFAULT_BUFFER_SIZE is the default buffer size for the logger. DEFAULT_BUFFER_SIZE = 100000 // High throughput: 100K buffer // DEFAULT_RATE_LIMIT is the default rate limit for the logger in messages per second. DEFAULT_RATE_LIMIT = 50000 // High throughput: 50K msgs/sec // DEFAULT_RATE_BURST is the default rate burst for the logger. DEFAULT_RATE_BURST = 10000 // High throughput: 10K burst // DEFAULT_DROP_REPORT_INTERVAL is the default interval in seconds for reporting dropped messages. DEFAULT_DROP_REPORT_INTERVAL = 10 // Report drops every 10 seconds // DEFAULT_GROUP_WINDOW is the default window in seconds for grouping similar events. DEFAULT_GROUP_WINDOW = 1 // Group events over 1 second window // KEY_PKG is the key used for the package name in log fields. KEY_PKG = "pkg" )
Variables ¶
var ( // ParseLevel parses a string into a zerolog.Level. It's a convenience wrapper around zerolog.ParseLevel. ParseLevel = zerolog.ParseLevel // DebugLevel defines the debug log level. DebugLevel = zerolog.DebugLevel // InfoLevel defines the info log level. InfoLevel = zerolog.InfoLevel // WarnLevel defines the warn log level. WarnLevel = zerolog.WarnLevel // ErrorLevel defines the error log level. ErrorLevel = zerolog.ErrorLevel // FatalLevel defines the fatal log level. FatalLevel = zerolog.FatalLevel // PanicLevel defines the panic log level. PanicLevel = zerolog.PanicLevel // NoLevel defines an absent log level. NoLevel = zerolog.NoLevel // Disabled disables the logger. Disabled = zerolog.Disabled // TraceLevel defines the trace log level. TraceLevel = zerolog.TraceLevel )
var AllLogFormats = [_logFormatCount]LogFormat{ LOG_FORMAT_CONSOLE, LOG_FORMAT_JSON, }
AllLogFormats is a list of all supported LogFormat values.
Functions ¶
func AllLogFormatsStrings ¶ added in v1.2.0
func AllLogFormatsStrings() []string
AllLogFormatsStrings returns a slice of strings representing all supported log formats.
func Close ¶ added in v1.2.0
func Close()
Close closes the global Logger instance, ensuring cleanup of its resources. This should be called when the application is shutting down to flush any buffered logs.
func EventHash ¶ added in v1.3.0
EventHash is a helper function that computes the hash of an event and returns it as a string. This can be used for logging or debugging purposes to identify events.
func Fatalf ¶
Fatalf logs a formatted message at FatalLevel with the given package name and error, then exits.
func Flush ¶ added in v1.6.0
func Flush()
Flush ensures all buffered messages in the global Logger are written to the output. This is useful when you want to force immediate output without closing the logger.
func GroupEvents ¶ added in v1.3.0
GroupEvents groups the given events by their hash value computed from the event data. It returns a map where the key is the hash value and the value is a slice of events (byte slices) that correspond to the same hash.
func Hash ¶ added in v1.3.0
Hash computes the hash of the given byte slice using the FNV-1a algorithm. It returns the hash value as an uint64.
func IsValidLogFormat ¶ added in v1.2.0
IsValidLogFormat checks if a given string is a valid log format.
func Panicf ¶
Panicf logs a formatted message at PanicLevel with the given package name and error, then panics.
func PreferredWriter ¶
PreferredWriter returns an io.Writer that writes to both a new bytes.Buffer and os.Stderr. This is typically used for console logging to capture output for testing or other purposes while still printing to the standard error stream.
func PrettyYaml ¶
PrettyYaml marshals the given data into a YAML string with an indent of 2 spaces. It uses github.com/goccy/go-yaml for marshaling.
func PrettyYamlString ¶
PrettyYamlString is a convenience wrapper around PrettyYaml that returns the YAML as a string. If an error occurs during marshaling, it returns an empty string.
func Print ¶
Print logs a message at NoLevel (effectively always printing) with the given package name. It explicitly sets a "level" field to "-" in the output.
func Printf ¶
Printf logs a formatted message at NoLevel (effectively always printing) with the given package name. It explicitly sets a "level" field to "-" in the output.
func SetGlobalLogger ¶ added in v1.6.0
func SetGlobalLogger(logger *CustomLogger)
SetGlobalLogger replaces the global Logger with a new one. This allows users to configure the global logger with custom settings while ensuring that subsequent calls to SetGlobalLoggerLogFormat preserve those settings.
func SetGlobalLoggerBuilder ¶ added in v1.6.0
func SetGlobalLoggerBuilder(builder *LoggerBuilder)
SetGlobalLoggerBuilder replaces the global Logger with a new one built from the provided builder. This allows users to configure the global logger with custom settings while ensuring that subsequent calls to SetGlobalLoggerLogFormat preserve those settings.
func SetGlobalLoggerLogFormat ¶ added in v1.6.0
SetGlobalLoggerLogFormat sets the log format for the global Logger. It parses the provided logFormat string and updates the Logger's underlying writer to either a console writer or a JSON writer. This preserves all other configuration settings of the global logger. Returns an error if the logFormat string is invalid.
func SetGlobalLoggerLogLevel ¶ added in v1.6.0
SetGlobalLoggerLogLevel sets the global log level for the default Logger. If the provided level string is empty, it defaults to InfoLevel. It returns an error if the level string is invalid. This preserves all other configuration settings of the global logger.
Types ¶
type BufferedRateLimitedWriter ¶ added in v1.2.0
type BufferedRateLimitedWriter struct {
// contains filtered or unexported fields
}
BufferedRateLimitedWriter wraps an io.Writer with rate limiting and buffering. It ensures that logs are written at a controlled pace and buffers messages to handle bursts, dropping messages if the buffer is full and reporting drops. It also supports event grouping to reduce duplicate log noise.
func (*BufferedRateLimitedWriter) Close ¶ added in v1.2.0
func (w *BufferedRateLimitedWriter) Close() error
Close closes the BufferedRateLimitedWriter, ensuring all buffered messages are processed and the drop reporter is stopped.
func (*BufferedRateLimitedWriter) Flush ¶ added in v1.6.0
func (w *BufferedRateLimitedWriter) Flush()
Flush ensures all buffered messages are written to the target. This is useful when you want to force immediate output without closing the writer.
func (*BufferedRateLimitedWriter) Write ¶ added in v1.2.0
func (w *BufferedRateLimitedWriter) Write(p []byte) (int, error)
Write writes the provided byte slice to the buffer. It implements io.Writer. If the buffer is full, messages are dropped, and the drop count is incremented. It starts the processor and drop reporter on the first write. If buffering is disabled, writes directly to the target with rate limiting.
type CustomLogger ¶
CustomLogger wraps zerolog.Logger to provide additional functionalities like rate limiting, buffering, and custom formatting.
func (*CustomLogger) Close ¶ added in v1.2.0
func (l *CustomLogger) Close()
Close closes the CustomLogger and its underlying BufferedRateLimitedWriter.
func (*CustomLogger) Flush ¶ added in v1.6.0
func (l *CustomLogger) Flush()
Flush ensures all buffered messages are written to the output. This is useful when you want to force immediate output without closing the logger.
func (*CustomLogger) SetZerologLogger ¶ added in v1.6.0
func (l *CustomLogger) SetZerologLogger(logger zerolog.Logger)
SetZerologLogger replaces the underlying zerolog.Logger instance in the CustomLogger.
type GoLoggingV1Backend ¶ added in v1.1.0
type GoLoggingV1Backend struct{}
go-logging compatibility GoLoggingV1Backend implements the logging.Backend interface to bridge go-logging.v1 with this log package.
func (*GoLoggingV1Backend) Log ¶ added in v1.1.0
func (b *GoLoggingV1Backend) Log(level go_logging_v1.Level, calldepth int, rec *go_logging_v1.Record) error
Log implements the logging.Backend interface for go-logging.v1. It maps go-logging levels to the corresponding log functions in this package.
type LogFormat ¶
type LogFormat int
LogFormat defines the available log output formats.
func ParseLogFormat ¶
ParseLogFormat converts a string representation of a log format into a LogFormat type. It returns LOG_FORMAT_CONSOLE if the string is empty or "console", LOG_FORMAT_JSON if the string is "json". It returns an error for any other invalid input.
type LoggerBuilder ¶ added in v1.6.0
type LoggerBuilder struct {
// contains filtered or unexported fields
}
LoggerBuilder provides a fluent interface for configuring and building CustomLogger instances.
func GlobalLoggerBuilder ¶ added in v1.6.0
func GlobalLoggerBuilder() *LoggerBuilder
GlobalLoggerBuilder returns the global logger builder instance. This allows users to access the current configuration and modify it if needed.
func NewLogger ¶
func NewLogger() *LoggerBuilder
NewLogger creates a new LoggerBuilder with default configuration. This is the only constructor function - all other configurations are done through the builder pattern.
func (*LoggerBuilder) AsJSON ¶ added in v1.6.0
func (lb *LoggerBuilder) AsJSON() *LoggerBuilder
AsJSON forces JSON output format regardless of environment settings.
func (*LoggerBuilder) Build ¶ added in v1.6.0
func (lb *LoggerBuilder) Build() *CustomLogger
Build creates and returns the configured CustomLogger instance.
func (*LoggerBuilder) WithBufferSize ¶ added in v1.6.0
func (lb *LoggerBuilder) WithBufferSize(size int) *LoggerBuilder
WithBufferSize sets the buffer size for the logger.
func (*LoggerBuilder) WithDropReportInterval ¶ added in v1.6.2
func (lb *LoggerBuilder) WithDropReportInterval(interval time.Duration) *LoggerBuilder
WithDropReportInterval sets the interval for reporting dropped messages. Use 0 for default from environment, negative values to disable drop reporting.
func (*LoggerBuilder) WithGroupWindow ¶ added in v1.6.0
func (lb *LoggerBuilder) WithGroupWindow(window time.Duration) *LoggerBuilder
WithGroupWindow sets the event grouping window duration. Use 0 for default from environment, negative values to disable grouping.
func (*LoggerBuilder) WithLogLevel ¶ added in v1.6.0
func (lb *LoggerBuilder) WithLogLevel(level zerolog.Level) *LoggerBuilder
WithLogLevel sets the log level.
func (*LoggerBuilder) WithLogLevelString ¶ added in v1.6.0
func (lb *LoggerBuilder) WithLogLevelString(level string) *LoggerBuilder
WithLogLevelString sets the log level from a string.
func (*LoggerBuilder) WithOutput ¶ added in v1.6.0
func (lb *LoggerBuilder) WithOutput(output io.Writer) *LoggerBuilder
WithOutput sets the output writer for the logger.
func (*LoggerBuilder) WithRateBurst ¶ added in v1.6.0
func (lb *LoggerBuilder) WithRateBurst(burst int) *LoggerBuilder
WithRateBurst sets the rate burst size for the logger.
func (*LoggerBuilder) WithRateLimit ¶ added in v1.6.0
func (lb *LoggerBuilder) WithRateLimit(limit int) *LoggerBuilder
WithRateLimit sets the rate limit (messages per second) for the logger.
func (*LoggerBuilder) WithoutBuffering ¶ added in v1.6.0
func (lb *LoggerBuilder) WithoutBuffering() *LoggerBuilder
WithoutBuffering disables buffering for the logger.
func (*LoggerBuilder) WithoutGrouping ¶ added in v1.6.0
func (lb *LoggerBuilder) WithoutGrouping() *LoggerBuilder
WithoutGrouping disables event grouping for the logger.