Documentation
ΒΆ
Index ΒΆ
- Variables
- type BaloganConfig
- type Condition
- func All(conditions ...Condition) Condition
- func Always() Condition
- func And(conditions ...Condition) Condition
- func Any(conditions ...Condition) Condition
- func CountBased(maxCount int) Condition
- func EnvEquals(key, value string) Condition
- func EnvExists(key string) Condition
- func Never() Condition
- func Not(condition Condition) Condition
- func Or(conditions ...Condition) Condition
- func RandomSample(percentage int) Condition
- func RateLimit(maxPerSecond int) Condition
- func SampleEveryN(n int) Condition
- func TimeRange(startHour, endHour int) Condition
- type ContextCondition
- type DefaultErrorHandler
- type ErrorHandler
- type Fields
- type FieldsFormatter
- type FileLogWriter
- type JSONFormatter
- type KeyValueFormatter
- type LevelCondition
- type LogLevel
- type LogWriter
- type LogfmtFormatter
- type Logger
- func (l *Logger) Close() error
- func (l *Logger) Debug(args ...interface{})
- func (l *Logger) Debugf(format string, args ...interface{})
- func (l *Logger) Error(args ...interface{})
- func (l *Logger) Errorf(format string, args ...interface{})
- func (l *Logger) Fatal(args ...interface{})
- func (l *Logger) Fatalf(format string, args ...interface{})
- func (l *Logger) GetFields() Fields
- func (l *Logger) Info(args ...interface{})
- func (l *Logger) Infof(format string, args ...interface{})
- func (l *Logger) Log(level LogLevel, args ...interface{})
- func (l *Logger) Logf(level LogLevel, format string, args ...interface{})
- func (l *Logger) Panic(args ...interface{})
- func (l *Logger) Panicf(format string, args ...interface{})
- func (l *Logger) Trace(args ...interface{})
- func (l *Logger) Tracef(format string, args ...interface{})
- func (l *Logger) Warning(args ...interface{})
- func (l *Logger) Warningf(format string, args ...interface{})
- func (l *Logger) When(condition Condition) *Logger
- func (l *Logger) WithContext(ctx context.Context) context.Context
- func (l *Logger) WithContextCondition(condition ContextCondition) *Logger
- func (l *Logger) WithField(key string, value interface{}) *Logger
- func (l *Logger) WithFields(fields Fields) *Logger
- func (l *Logger) WithFieldsFormatter(formatter FieldsFormatter) *Logger
- func (l *Logger) WithJSON() *Logger
- func (l *Logger) WithKeyValue() *Logger
- func (l *Logger) WithKeyValueSeparator(separator string) *Logger
- func (l *Logger) WithLevelCondition(condition LevelCondition) *Logger
- func (l *Logger) WithLogfmt() *Logger
- func (l *Logger) WithTemporaryPrefix(builder ...PrefixBuilderFunc) *Logger
- type PrefixBuilderFunc
- func WithFields(fields Fields) PrefixBuilderFunc
- func WithFieldsFormatter(fields Fields, formatter FieldsFormatter) PrefixBuilderFunc
- func WithJSONFields(fields Fields) PrefixBuilderFunc
- func WithLogLevel(level LogLevel) PrefixBuilderFunc
- func WithLogfmtFields(fields Fields) PrefixBuilderFunc
- func WithTag(tag string) PrefixBuilderFunc
- func WithTimeStamp() PrefixBuilderFunc
- type StdOutLogWriter
Constants ΒΆ
This section is empty.
Variables ΒΆ
var ( // InProduction evaluates to true when ENV environment variable equals "production" InProduction = func() bool { return os.Getenv("ENV") == "production" } // InDevelopment evaluates to true when ENV environment variable equals "development" InDevelopment = func() bool { return os.Getenv("ENV") == "development" } // InTesting evaluates to true when ENV environment variable equals "test" InTesting = func() bool { return os.Getenv("ENV") == "test" } // InStaging evaluates to true when ENV environment variable equals "staging" InStaging = func() bool { return os.Getenv("ENV") == "staging" } // DebugEnabled evaluates to true when DEBUG environment variable equals "true" DebugEnabled = func() bool { return os.Getenv("DEBUG") == "true" } // VerboseMode evaluates to true when VERBOSE environment variable equals "true" VerboseMode = func() bool { return os.Getenv("VERBOSE") == "true" } // WorkingHours evaluates to true during business hours (9 AM to 5 PM) WorkingHours = func() bool { hour := time.Now().Hour() return hour >= 9 && hour <= 17 } // Weekend evaluates to true on Saturday and Sunday Weekend = func() bool { day := time.Now().Weekday() return day == time.Saturday || day == time.Sunday } // Weekday evaluates to true on Monday through Friday (opposite of Weekend) Weekday = func() bool { return !Weekend() } )
Predefined conditions for common logging scenarios. These conditions can be used directly without additional configuration.
var DefaultWriter = NewStdOutLogWriter()
Functions ΒΆ
This section is empty.
Types ΒΆ
type BaloganConfig ΒΆ
type BaloganConfig struct {
Level LogLevel
Writers []LogWriter
Prefixes []PrefixBuilderFunc
Concurrency bool
// Structured logging configuration
Fields Fields
FieldsFormatter FieldsFormatter
}
type Condition ΒΆ
type Condition func() bool
Condition represents a function that determines whether logging should occur. It takes no parameters and returns a boolean indicating if the log message should be processed. This is the most basic type of condition used for simple true/false logic.
Example usage:
condition := func() bool { return os.Getenv("DEBUG") == "true" }
logger.When(condition).Debug("Conditional debug message")
func All ΒΆ
All returns a condition that evaluates to true only when all provided conditions are true. This is an alias for And() provided for better readability in some contexts.
Parameters:
conditions: Variable number of conditions that must all be true.
Example:
logger.When(All(InProduction, HasField("user_id"))).Info("Production user action")
func Always ΒΆ
func Always() Condition
Always returns a condition that always evaluates to true. This condition will allow all log messages to pass through.
Example:
logger.When(Always()).Info("This will always log")
func And ΒΆ
And returns a condition that evaluates to true only when all provided conditions are true. The condition uses short-circuit evaluation, stopping at the first false condition.
Parameters:
conditions: Variable number of conditions that must all be true.
Example:
logger.When(And(InDevelopment, DebugEnabled, WorkingHours)).Debug("Complex condition")
func Any ΒΆ
Any returns a condition that evaluates to true when at least one of the provided conditions is true. This is an alias for Or() provided for better readability in some contexts.
Parameters:
conditions: Variable number of conditions where at least one must be true.
Example:
logger.When(Any(Weekend, After(18))).Info("Leisure time logging")
func CountBased ΒΆ
CountBased returns a condition that allows only a specific number of log messages total. Once the maximum count is reached, the condition will always return false. This is useful for limiting debug output to a specific number of occurrences.
Parameters:
maxCount: Maximum total number of log messages to allow.
Example:
logger.When(CountBased(5)).Debug("This will only log 5 times total")
Note: This condition is thread-safe and maintains state across multiple calls.
func EnvEquals ΒΆ
EnvEquals returns a condition that checks if an environment variable equals a specific value. The condition evaluates to true only when the environment variable matches the expected value.
Parameters:
key: The name of the environment variable to check. value: The expected value of the environment variable.
Example:
logger.When(EnvEquals("LOG_LEVEL", "debug")).Debug("Debug message")
func EnvExists ΒΆ
EnvExists returns a condition that checks if an environment variable is set. The condition evaluates to true when the environment variable exists, regardless of its value.
Parameters:
key: The name of the environment variable to check for existence.
Example:
logger.When(EnvExists("DEBUG")).Info("Debug mode is enabled")
func Never ΒΆ
func Never() Condition
Never returns a condition that always evaluates to false. This condition will block all log messages from being written.
Example:
logger.When(Never()).Info("This will never log")
func Not ΒΆ
Not returns a condition that inverts the result of the provided condition. The condition evaluates to true when the provided condition is false, and vice versa.
Parameters:
condition: The condition to invert.
Example:
logger.When(Not(InProduction)).Debug("Debug in non-production environments")
func Or ΒΆ
Or returns a condition that evaluates to true when at least one of the provided conditions is true. The condition uses short-circuit evaluation, stopping at the first true condition.
Parameters:
conditions: Variable number of conditions where at least one must be true.
Example:
logger.When(Or(InDevelopment, InTesting, DebugEnabled)).Debug("Debug in dev, test, or debug mode")
func RandomSample ΒΆ
RandomSample returns a condition that randomly samples log messages based on percentage. The condition uses pseudo-random sampling based on current time to determine if logging should occur.
Parameters:
percentage: The percentage (0-100) of messages that should be logged.
Values <= 0 will never log, values >= 100 will always log.
Example:
logger.When(RandomSample(10)).Debug("Only 10% of these will be logged")
func RateLimit ΒΆ
RateLimit creates a condition that limits the number of log messages per second. The condition maintains internal state to track message count and resets every second. This is useful for preventing log spam in high-frequency scenarios.
Parameters:
maxPerSecond: Maximum number of log messages allowed per second.
Values <= 0 will never allow logging.
Example:
logger.When(RateLimit(10)).Error("Rate limited error message")
Note: This condition is thread-safe and can be used across multiple goroutines.
func SampleEveryN ΒΆ
SampleEveryN returns a condition that allows every Nth log message to pass through. This provides deterministic sampling with better distribution than random sampling. The first message is always logged, then every Nth message after that.
Parameters:
n: The sampling interval. Every Nth message will be logged. Values <= 1 will allow all messages (same as Always()).
Example:
logger.When(SampleEveryN(10)).Debug("Every 10th debug message will be logged")
Note: This condition is thread-safe and maintains internal counter state.
func TimeRange ΒΆ
TimeRange creates a condition that allows logging only during specified time range. The condition evaluates the current hour and checks if it falls within the specified range. Supports both same-day ranges (9-17) and overnight ranges (22-6).
Parameters:
startHour: The starting hour (0-23) of the allowed time range. endHour: The ending hour (0-23) of the allowed time range.
Example:
logger.When(TimeRange(9, 17)).Info("Business hours only")
logger.When(TimeRange(22, 6)).Error("Night shift logging")
type ContextCondition ΒΆ
ContextCondition represents a function that determines whether logging should occur based on context. It receives a context.Context parameter and returns a boolean indicating if logging should proceed. This is useful for conditions that depend on request-specific or goroutine-local data.
Example usage:
condition := func(ctx context.Context) bool {
return ctx.Value("user_role") == "admin"
}
logger.WithContextCondition(condition).Info("Admin-only message")
func ContextValueEquals ΒΆ
func ContextValueEquals(key interface{}, expectedValue interface{}) ContextCondition
ContextValueEquals returns a context condition that checks if a context value equals an expected value. The condition evaluates to true when the context contains the key and its value matches the expected value.
Parameters:
key: The context key to check. expectedValue: The expected value for comparison.
Example:
logger.WithContextCondition(ContextValueEquals("user_role", "admin")).Info("Admin action")
func HasContextValue ΒΆ
func HasContextValue(key interface{}) ContextCondition
HasContextValue returns a context condition that checks if a specific key exists in the context. The condition evaluates to true when the context contains the specified key with any non-nil value.
Parameters:
key: The context key to check for existence.
Example:
logger.WithContextCondition(HasContextValue("request_id")).Info("Request logged")
type DefaultErrorHandler ΒΆ
type DefaultErrorHandler struct{}
func (*DefaultErrorHandler) Handle ΒΆ
func (h *DefaultErrorHandler) Handle(error)
type ErrorHandler ΒΆ
type ErrorHandler interface {
Handle(err error)
}
type Fields ΒΆ
type Fields map[string]interface{}
Fields represents a map of key-value pairs for structured logging.
func (Fields) WithFields ΒΆ
WithFields returns a new Fields with all given fields merged.
type FieldsFormatter ΒΆ
FieldsFormatter defines how fields should be formatted in log output.
var DefaultFieldsFormatter FieldsFormatter = &KeyValueFormatter{}
DefaultFieldsFormatter is the default formatter for fields.
type FileLogWriter ΒΆ
type FileLogWriter struct {
// contains filtered or unexported fields
}
FileLogWriter writes log messages to a file.
func NewFileLogWriter ΒΆ
func NewFileLogWriter(filename string) (*FileLogWriter, error)
NewFileLogWriter creates a new FileLogWriter.
func (*FileLogWriter) Close ΒΆ
func (w *FileLogWriter) Close() error
type JSONFormatter ΒΆ
type JSONFormatter struct{}
JSONFormatter formats fields as JSON.
func (*JSONFormatter) Format ΒΆ
func (f *JSONFormatter) Format(fields Fields) string
type KeyValueFormatter ΒΆ
type KeyValueFormatter struct {
Separator string
}
KeyValueFormatter formats fields as key=value pairs.
func (*KeyValueFormatter) Format ΒΆ
func (f *KeyValueFormatter) Format(fields Fields) string
type LevelCondition ΒΆ
LevelCondition represents a function that determines whether logging should occur based on log level and fields. It receives the log level and the current logger fields, returning a boolean for conditional logic. This is useful for complex conditions that depend on both the severity and the structured data.
Example usage:
condition := func(level LogLevel, fields Fields) bool {
return level >= ErrorLevel && fields["service"] == "payment"
}
logger.WithLevelCondition(condition).Error("Payment service error")
func FieldEquals ΒΆ
func FieldEquals(fieldName string, expectedValue interface{}) LevelCondition
FieldEquals returns a level condition that checks if a field equals a specific value. The condition evaluates to true when the field exists and its value matches the expected value.
Parameters:
fieldName: The name of the field to check. expectedValue: The expected value for comparison.
Example:
logger.WithLevelCondition(FieldEquals("environment", "production")).
WithField("environment", "production").Info("Production log")
func HasField ΒΆ
func HasField(fieldName string) LevelCondition
HasField returns a level condition that checks if a specific field exists in the log fields. The condition evaluates to true when the specified field is present, regardless of its value.
Parameters:
fieldName: The name of the field to check for existence.
Example:
logger.WithLevelCondition(HasField("user_id")).WithField("user_id", 123).Info("User action")
func MinLevel ΒΆ
func MinLevel(minLevel LogLevel) LevelCondition
MinLevel returns a level condition that allows logging for levels at or above the minimum level. The condition evaluates to true when the log level is greater than or equal to the minimum level.
Parameters:
minLevel: The minimum log level to allow.
Example:
logger.WithLevelCondition(MinLevel(WarningLevel)).Info("This won't log")
logger.WithLevelCondition(MinLevel(WarningLevel)).Error("This will log")
func OnlyLevel ΒΆ
func OnlyLevel(targetLevel LogLevel) LevelCondition
OnlyLevel returns a level condition that allows logging only for a specific log level. The condition evaluates to true only when the log level exactly matches the target level.
Parameters:
targetLevel: The specific log level to allow.
Example:
logger.WithLevelCondition(OnlyLevel(ErrorLevel)).Log(ErrorLevel, "Only errors")
type LogLevel ΒΆ
type LogLevel int
func (LogLevel) Exit ΒΆ
func (level LogLevel) Exit()
Exit terminates the program with exit code 1. Used internally by Fatal level logging.
func (LogLevel) IsEnabled ΒΆ
IsEnabled checks if the given level should be logged based on the minimum level.
func (LogLevel) Panic ΒΆ
Panic causes a panic with the given message. Used internally by Panic level logging.
func (LogLevel) ShouldExit ΒΆ
ShouldExit returns true if the log level should cause the program to exit.
func (LogLevel) ShouldPanic ΒΆ
ShouldPanic returns true if the log level should cause a panic.
type LogfmtFormatter ΒΆ
type LogfmtFormatter struct{}
LogfmtFormatter formats fields in logfmt style (key=value with proper escaping).
func (*LogfmtFormatter) Format ΒΆ
func (f *LogfmtFormatter) Format(fields Fields) string
type Logger ΒΆ
type Logger struct {
// contains filtered or unexported fields
}
func New ΒΆ
func New(level LogLevel, writer LogWriter, prefixes ...PrefixBuilderFunc) *Logger
The simpliest way to create new Balogan Logger instance.
If writers accept nil, the StdOutLogWriter will be used as a default value.
Balogan does not provide prefixes which will be used as a default value.
func NewFromConfig ΒΆ
func NewFromConfig(cfg *BaloganConfig) *Logger
func (*Logger) Close ΒΆ
Close closes all writers associated with the logger. It ensures that all log messages are flushed and resources are released.
If you use some Writer except StdOutLogWriter we highly recommend to call this method.
Returns:
An error if any of the writers fail to close.
func (*Logger) Debug ΒΆ
func (l *Logger) Debug(args ...interface{})
Debug logs a message at the DEBUG level. It calls the general Log method with the DEBUG level.
Parameters:
args: The arguments to be logged.
func (*Logger) Debugf ΒΆ
Debugf logs a formatted message at the DEBUG level. It calls the general Logf method with the DEBUG level.
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Error ΒΆ
func (l *Logger) Error(args ...interface{})
Error logs a message at the ERROR level. It calls the general Log method with the ERROR level.
Parameters:
args: The arguments to be logged.
func (*Logger) Errorf ΒΆ
Errorf logs a formatted message at the ERROR level. It calls the general Logf method with the ERROR level.
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Fatal ΒΆ
func (l *Logger) Fatal(args ...interface{})
Fatal logs a message at the FATAL level and then exits the program. It calls the general Log method with the FATAL level, then calls os.Exit(1).
Parameters:
args: The arguments to be logged.
func (*Logger) Fatalf ΒΆ
Fatalf logs a formatted message at the FATAL level and then exits the program. It calls the general Logf method with the FATAL level, then calls os.Exit(1).
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Info ΒΆ
func (l *Logger) Info(args ...interface{})
Info logs a message at the INFO level. It calls the general Log method with the INFO level. Parameters:
args: The arguments to be logged.
func (*Logger) Infof ΒΆ
Infof logs a formatted message at the INFO level. It calls the general Logf method with the INFO level.
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Log ΒΆ
Log logs a message at the specified level. It checks if the log level is enabled, then writes the message with provided prefixes.
Parameters:
level: The log level of the message. args: The arguments to be converted to a string message.
func (*Logger) Logf ΒΆ
Logf logs a formatted message at the specified level. It checks if the log level is enabled, then writes the message with provided prefixes.
Parameters:
level: The log level of the message. format: The format string for the message. args: The arguments for the format string.
func (*Logger) Panic ΒΆ
func (l *Logger) Panic(args ...interface{})
Panic logs a message at the PANIC level and then panics. It calls the general Log method with the PANIC level, then calls panic().
Parameters:
args: The arguments to be logged.
func (*Logger) Panicf ΒΆ
Panicf logs a formatted message at the PANIC level and then panics. It calls the general Logf method with the PANIC level, then calls panic().
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Trace ΒΆ
func (l *Logger) Trace(args ...interface{})
Trace logs a message at the TRACE level. It calls the general Log method with the TRACE level.
Parameters:
args: The arguments to be logged.
func (*Logger) Tracef ΒΆ
Tracef logs a formatted message at the TRACE level. It calls the general Logf method with the TRACE level.
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) Warning ΒΆ
func (l *Logger) Warning(args ...interface{})
Warning logs a message at the WARNING level. It calls the general Log method with the WARNING level.
Parameters:
args: The arguments to be logged.
func (*Logger) Warningf ΒΆ
Warningf logs a formatted message at the WARNING level. It calls the general Logf method with the WARNING level.
Parameters:
format: The format string for the message. args: The arguments for the format string.
func (*Logger) When ΒΆ added in v1.1.1
When returns a new Logger instance that only logs when the condition is true. This is the main method for applying conditional logging.
Parameters:
condition: The condition that determines whether logging should occur.
Example:
logger.When(InDevelopment).Debug("This only logs in development")
func (*Logger) WithContextCondition ΒΆ added in v1.1.1
func (l *Logger) WithContextCondition(condition ContextCondition) *Logger
WithContextCondition returns a new Logger instance with a context-based condition. The condition receives the context for evaluation.
Parameters:
condition: The context condition that determines whether logging should occur.
Example:
logger.WithContextCondition(HasContextValue("user_id")).Info("User action")
func (*Logger) WithField ΒΆ
WithField returns a new Logger instance with the specified field added. The new logger inherits all configuration from the current logger.
Parameters:
key: The field key. value: The field value.
func (*Logger) WithFields ΒΆ
WithFields returns a new Logger instance with the specified fields added. The new logger inherits all configuration from the current logger.
Parameters:
fields: A map of field key-value pairs to add.
func (*Logger) WithFieldsFormatter ΒΆ
func (l *Logger) WithFieldsFormatter(formatter FieldsFormatter) *Logger
WithFieldsFormatter returns a new Logger instance with the specified fields formatter. This allows changing how fields are formatted in log output.
Parameters:
formatter: The FieldsFormatter to use for formatting fields.
func (*Logger) WithJSON ΒΆ
WithJSON returns a new Logger instance configured to format fields as JSON. This is a convenient shortcut for WithFieldsFormatter(&JSONFormatter{}).
Example:
logger.WithJSON().WithField("user", "john").Info("User logged in")
// Output: INFO {"user":"john"} User logged in
func (*Logger) WithKeyValue ΒΆ
WithKeyValue returns a new Logger instance configured to format fields as key=value pairs. This is a convenient shortcut for WithFieldsFormatter(&KeyValueFormatter{}). This is the default format, so this method is mainly useful for explicitly switching back from another format.
Example:
logger.WithKeyValue().WithField("user", "john").Info("User logged in")
// Output: INFO user=john User logged in
func (*Logger) WithKeyValueSeparator ΒΆ
WithKeyValueSeparator returns a new Logger instance configured to format fields as key=value pairs with a custom separator between pairs.
Parameters:
separator: The separator to use between key=value pairs.
Example:
logger.WithKeyValueSeparator(" | ").WithFields(Fields{"a": 1, "b": 2}).Info("Test")
// Output: INFO a=1 | b=2 Test
func (*Logger) WithLevelCondition ΒΆ added in v1.1.1
func (l *Logger) WithLevelCondition(condition LevelCondition) *Logger
WithLevelCondition returns a new Logger instance with a level-based condition. The condition receives the log level and fields for evaluation.
Parameters:
condition: The level condition that determines whether logging should occur.
Example:
logger.WithLevelCondition(OnlyLevel(ErrorLevel)).Error("Only error level")
func (*Logger) WithLogfmt ΒΆ
WithLogfmt returns a new Logger instance configured to format fields in logfmt style. This is a convenient shortcut for WithFieldsFormatter(&LogfmtFormatter{}).
Example:
logger.WithLogfmt().WithField("user", "john doe").Info("User logged in")
// Output: INFO user="john doe" User logged in
func (*Logger) WithTemporaryPrefix ΒΆ
func (l *Logger) WithTemporaryPrefix(builder ...PrefixBuilderFunc) *Logger
Creates new Balogan Logger instance ith previous conifg except prefixes. Accept additional prefixes which will be added to the end of prefix part of log message.
Provided prefixes DO NOT APPLY for Balogan Logger instance from which the method was called.
type PrefixBuilderFunc ΒΆ
func WithFields ΒΆ
func WithFields(fields Fields) PrefixBuilderFunc
WithFields returns a PrefixBuilderFunc that formats the given fields.
func WithFieldsFormatter ΒΆ
func WithFieldsFormatter(fields Fields, formatter FieldsFormatter) PrefixBuilderFunc
WithFieldsFormatter returns a PrefixBuilderFunc that formats fields using the specified formatter.
func WithJSONFields ΒΆ
func WithJSONFields(fields Fields) PrefixBuilderFunc
WithJSONFields returns a PrefixBuilderFunc that formats fields as JSON.
func WithLogLevel ΒΆ
func WithLogLevel(level LogLevel) PrefixBuilderFunc
func WithLogfmtFields ΒΆ
func WithLogfmtFields(fields Fields) PrefixBuilderFunc
WithLogfmtFields returns a PrefixBuilderFunc that formats fields in logfmt style.
func WithTag ΒΆ
func WithTag(tag string) PrefixBuilderFunc
func WithTimeStamp ΒΆ
func WithTimeStamp() PrefixBuilderFunc
type StdOutLogWriter ΒΆ
type StdOutLogWriter struct{}
func NewStdOutLogWriter ΒΆ
func NewStdOutLogWriter() *StdOutLogWriter
func (*StdOutLogWriter) Close ΒΆ
func (w *StdOutLogWriter) Close() error