Loading documentation...
Loading documentation...
Loading documentation...
Complete API documentation for the logs package.
Import Path: github.com/kolosys/helix/logs
Package logs provides a high-performance, context-aware structured logging library.
Features:
Basic usage:
log := logs.New()
log.Info("server started", logs.Int("port", 8080))With context:
log.InfoContext(ctx, "request processed", logs.Duration("latency", time.Since(start)))
RequestIDKey
RequestID is a common field key for request IDs.
const RequestIDKey = "request_id"TraceIDKey
TraceID is a common field key for trace IDs.
const TraceIDKey = "trace_id"UserIDKey
UserID is a common field key for user IDs.
const UserIDKey = "user_id"AlwaysSampler always allows logging.
// Create a new AlwaysSampler
alwayssampler := AlwaysSampler{
}type AlwaysSampler struct {
}Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Builder provides a fluent/chainable API for building log entries. It accumulates fields and then emits a log entry when a level method is called.
// Create a new Builder
builder := Builder{
}type Builder struct {
}Bool adds a bool field.
func Bool(key string, value bool) FieldParameters:
key (string)value (bool)Returns:
Debug logs at debug level.
func (*Builder) Debug(msg string)Parameters:
msg (string)Returns: None
Err adds an error field with key "error".
func (*Builder) Err(err error) *BuilderParameters:
err (error)Returns:
Error logs at error level.
func (*Builder) Error(msg string)Parameters:
msg (string)Returns: None
Fatal logs at fatal level and exits.
func Fatal(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Float64 adds a float64 field.
func Float64(key string, value float64) FieldParameters:
key (string)value (float64)Returns:
Info logs at info level.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Int adds an int field.
func (*Builder) Int(key string, value int) *BuilderParameters:
key (string)value (int)Returns:
Int64 adds an int64 field.
func Int64(key string, value int64) FieldParameters:
key (string)value (int64)Returns:
Log logs at the specified level.
func (*Builder) Log(level Level, msg string)Parameters:
level (Level)msg (string)Returns: None
Msg is an alias for Info (zerolog-style).
func (*Builder) Msg(msg string)Parameters:
msg (string)Returns: None
Panic logs at panic level and panics.
func (*Builder) Panic(msg string)Parameters:
msg (string)Returns: None
Send logs with an empty message (zerolog-style).
func (*Builder) Send()Parameters: None
Returns: None
Str adds a string field.
func (*Builder) Str(key, value string) *BuilderParameters:
key (string)value (string)Returns:
Trace logs at trace level.
func (*Builder) Trace(msg string)Parameters:
msg (string)Returns: None
Uint adds a uint field.
func (*Builder) Uint(key string, value uint) *BuilderParameters:
key (string)value (uint)Returns:
Uint64 adds a uint64 field.
func Uint64(key string, value uint64) FieldParameters:
key (string)value (uint64)Returns:
Warn logs at warn level.
func Warn(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
With adds a field to the builder using auto-detection.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
WithContext sets the context for the log entry.
func (*Builder) WithContext(ctx context.Context) *BuilderParameters:
ctx (context.Context)Returns:
WithError adds an error field.
func (*Builder) WithError(err error) *BuilderParameters:
err (error)Returns:
WithField adds a typed field to the builder.
func (*Builder) WithField(f Field) *BuilderParameters:
f (Field)Returns:
WithFields adds multiple typed fields to the builder.
func WithFields(fields ...Field) OptionParameters:
fields (...Field)Returns:
CompositeSampler combines multiple samplers with AND logic.
// Create a new CompositeSampler
compositesampler := CompositeSampler{
}type CompositeSampler struct {
}NewCompositeSampler creates a sampler that requires all samplers to pass.
func NewCompositeSampler(samplers ...Sampler) *CompositeSamplerParameters:
samplers (...Sampler)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
CountSampler logs every Nth occurrence.
// Create a new CountSampler
countsampler := CountSampler{
}type CountSampler struct {
}NewCountSampler creates a sampler that logs every Nth occurrence.
func NewCountSampler(n int) *CountSamplerParameters:
n (int)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Entry represents a log entry.
// Create a new Entry
entry := Entry{
Level: Level{},
Time: /* value */,
Message: "example",
Fields: [],
Caller: "example",
Stack: "example",
}type Entry struct {
Level Level
Time time.Time
Message string
Fields []Field
Caller string
Stack string
}| Field | Type | Description |
|---|---|---|
| Level | Level | |
| Time | time.Time | |
| Message | string | |
| Fields | []Field | |
| Caller | string | |
| Stack | string |
GetField returns the field with the given key, or an empty field if not found.
func (*Entry) GetField(key string) (Field, bool)Parameters:
key (string)Returns:
GetString returns the string value of a field, or empty string if not found.
func (*Entry) GetString(key string) stringParameters:
key (string)Returns:
HasField returns true if the entry has a field with the given key.
func (*Entry) HasField(key string) boolParameters:
key (string)Returns:
ErrorBuilder provides a fluent API for logging errors.
// Create a new ErrorBuilder
errorbuilder := ErrorBuilder{
}type ErrorBuilder struct {
}Debug logs at debug level if error is not nil.
func (*ErrorBuilder) Debug(msg string)Parameters:
msg (string)Returns: None
Error logs at error level if error is not nil.
func (*ErrorBuilder) Error(msg string)Parameters:
msg (string)Returns: None
Fatal logs at fatal level if error is not nil and exits.
func Fatal(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Info logs at info level if error is not nil.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Trace logs at trace level if error is not nil.
func Trace(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Warn logs at warn level if error is not nil.
func (*Builder) Warn(msg string)Parameters:
msg (string)Returns: None
With adds a field to the error builder.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
WithField adds a typed field.
func (*Builder) WithField(f Field) *BuilderParameters:
f (Field)Returns:
WithFields adds multiple fields.
func WithFields(fields ...Field) OptionParameters:
fields (...Field)Returns:
ErrorHook collects errors for inspection.
// Create a new ErrorHook
errorhook := ErrorHook{
}type ErrorHook struct {
}NewErrorHook creates a hook that collects error entries.
func NewErrorHook(maxEntries int) *ErrorHookParameters:
maxEntries (int)Returns:
Clear clears collected errors.
func (*ErrorHook) Clear()Parameters: None
Returns: None
Errors returns collected errors.
func (*ErrorHook) Errors() []EntryParameters: None
Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Field represents a structured log field.
// Create a new Field
field := Field{
Key: "example",
Type: FieldType{},
Int: 42,
Uint: 42,
Float: 3.14,
String: "example",
Interface: any{},
}type Field struct {
Key string
Type FieldType
Int int64
Uint uint64
Float float64
String string
Interface any
}| Field | Type | Description |
|---|---|---|
| Key | string | |
| Type | FieldType | |
| Int | int64 | |
| Uint | uint64 | |
| Float | float64 | |
| String | string | |
| Interface | any |
Any creates a field with any value.
func Any(key string, value any) FieldParameters:
key (string)value (any)Returns:
Bool creates a bool field.
func (*Builder) Bool(key string, value bool) *BuilderParameters:
key (string)value (bool)Returns:
Bytes creates a []byte field.
func Bytes(key string, value []byte) FieldParameters:
key (string)value ([]byte)Returns:
Duration creates a time.Duration field.
func Duration(key string, value time.Duration) FieldParameters:
key (string)value (time.Duration)Returns:
Err creates an error field with key "error".
func (*Builder) Err(err error) *BuilderParameters:
err (error)Returns:
ErrChain creates a field that unwraps the error chain.
func ErrChain(err error) FieldParameters:
err (error)Returns:
ErrWithStack creates an error field with stack trace.
func ErrWithStack(err error) FieldParameters:
err (error)Returns:
FieldsFromContext extracts fields from the context.
func FieldsFromContext(ctx context.Context) []FieldParameters:
ctx (context.Context)Returns:
Float32 creates a float32 field.
func Float32(key string, value float32) FieldParameters:
key (string)value (float32)Returns:
Float64 creates a float64 field.
func (*Builder) Float64(key string, value float64) *BuilderParameters:
key (string)value (float64)Returns:
Int creates an int field.
func Int(key string, value int) FieldParameters:
key (string)value (int)Returns:
Int16 creates an int16 field.
func Int16(key string, value int16) FieldParameters:
key (string)value (int16)Returns:
Int32 creates an int32 field.
func Int32(key string, value int32) FieldParameters:
key (string)value (int32)Returns:
Int64 creates an int64 field.
func Int64(key string, value int64) FieldParameters:
key (string)value (int64)Returns:
Int8 creates an int8 field.
func Int8(key string, value int8) FieldParameters:
key (string)value (int8)Returns:
JSON creates a field that will be JSON-encoded.
func JSON(key string, value any) FieldParameters:
key (string)value (any)Returns:
NamedErr creates an error field with a custom key.
func NamedErr(key string, err error) FieldParameters:
key (string)err (error)Returns:
Namespace creates a namespace field for grouping.
func Namespace(key string) FieldParameters:
key (string)Returns:
Object creates a field from any value, attempting to extract structure. For structs, it extracts fields. For other types, it uses Any.
func Object(key string, v any) FieldParameters:
key (string)v (any)Returns:
Stack creates a field containing a stack trace.
func Stack(key string) FieldParameters:
key (string)Returns:
String creates a string field.
func String(key, value string) FieldParameters:
key (string)value (string)Returns:
Stringer creates a field from a fmt.Stringer.
func Stringer(key string, value fmt.Stringer) FieldParameters:
key (string)value (fmt.Stringer)Returns:
Strings creates a string slice field.
func Strings(key string, values []string) FieldParameters:
key (string)values ([]string)Returns:
Struct creates fields from a struct's exported fields. It uses json tags for field names if available, otherwise uses the field name. Nested structs are flattened with dot notation.
func Struct(key string, v any) FieldParameters:
key (string)v (any)Returns:
StructFlat creates multiple top-level fields from a struct's exported fields. Unlike Struct, this doesn't nest under a key - fields are added directly.
func StructFlat(v any) []FieldParameters:
v (any)Returns:
Time creates a time.Time field.
func Time(key string, value time.Time) FieldParameters:
key (string)value (time.Time)Returns:
Uint creates a uint field.
func Uint(key string, value uint) FieldParameters:
key (string)value (uint)Returns:
Uint16 creates a uint16 field.
func Uint16(key string, value uint16) FieldParameters:
key (string)value (uint16)Returns:
Uint32 creates a uint32 field.
func Uint32(key string, value uint32) FieldParameters:
key (string)value (uint32)Returns:
Uint64 creates a uint64 field.
func (*Builder) Uint64(key string, value uint64) *BuilderParameters:
key (string)value (uint64)Returns:
Uint8 creates a uint8 field.
func Uint8(key string, value uint8) FieldParameters:
key (string)value (uint8)Returns:
V creates a field with automatic type detection. This is a convenience function for when you don't want to specify the type.
func V(key string, value any) FieldParameters:
key (string)value (any)Returns:
StringValue returns the field value as a string.
func (Field) StringValue() stringParameters: None
Returns:
Value returns the field value as an interface{}.
func (Field) Value() anyParameters: None
Returns:
FieldType represents the type of a field value.
// Example usage of FieldType
var value FieldType
// Initialize with appropriate valuetype FieldType uint8FileHook writes entries to a file.
// Create a new FileHook
filehook := FileHook{
}type FileHook struct {
*WriterHook
}| Field | Type | Description |
|---|---|---|
| **WriterHook | *WriterHook |
NewFileHook creates a hook that writes to a file.
func NewFileHook(path string, formatter Formatter, levels ...Level) (*FileHook, error)Parameters:
path (string)formatter (Formatter)levels (...Level)Returns:
Close closes the file.
func (*Logger) Close() errorParameters: None
Returns:
FilterHook conditionally fires another hook.
// Create a new FilterHook
filterhook := FilterHook{
}type FilterHook struct {
}NewFilterHook creates a hook that conditionally fires.
func NewFilterHook(hook Hook, filter func(*Entry) bool) *FilterHookParameters:
hook (Hook)filter (func(*Entry) bool)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
FirstNSampler logs only the first N occurrences.
// Create a new FirstNSampler
firstnsampler := FirstNSampler{
}type FirstNSampler struct {
}NewFirstNSampler creates a sampler that logs only the first N occurrences.
func NewFirstNSampler(n int) *FirstNSamplerParameters:
n (int)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Formatter formats log entries.
// Example implementation of Formatter
type MyFormatter struct {
// Add your fields here
}
func (m MyFormatter) Format(param1 *Entry) []byte {
// Implement your logic here
return
}
type Formatter interface {
Format(entry *Entry) ([]byte, error)
}| Method | Description |
|---|
FuncHook wraps a function as a hook.
// Create a new FuncHook
funchook := FuncHook{
}type FuncHook struct {
}NewFuncHook creates a hook from a function.
func NewFuncHook(fn func(*Entry), levels ...Level) *FuncHookParameters:
fn (func(*Entry))levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Hook is called when a log entry is written.
// Example implementation of Hook
type MyHook struct {
// Add your fields here
}
func (m MyHook) Fire(param1 *Entry) {
// Implement your logic here
return
}
func (m MyHook) Levels() []Level {
// Implement your logic here
return
}
type Hook interface {
Fire(entry *Entry)
Levels() []Level
}| Method | Description |
|---|
JSONFormatter formats logs as JSON.
// Create a new JSONFormatter
jsonformatter := JSONFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
TimestampKey: "example",
LevelKey: "example",
MessageKey: "example",
CallerKey: "example",
StackKey: "example",
PrettyPrint: true,
EscapeHTML: true,
}type JSONFormatter struct {
TimestampFormat string
DisableTimestamp bool
TimestampKey string
LevelKey string
MessageKey string
CallerKey string
StackKey string
PrettyPrint bool
EscapeHTML bool
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: time.RFC3339Nano |
| DisableTimestamp | bool | DisableTimestamp disables timestamp output. |
| TimestampKey | string | TimestampKey is the key for the timestamp field. Default: "time" |
| LevelKey | string | LevelKey is the key for the level field. Default: "level" |
| MessageKey | string | MessageKey is the key for the message field. Default: "msg" |
| CallerKey | string | CallerKey is the key for the caller field. Default: "caller" |
| StackKey | string | StackKey is the key for the stack trace field. Default: "stack" |
| PrettyPrint | bool | PrettyPrint enables pretty-printed JSON. |
| EscapeHTML | bool | EscapeHTML escapes HTML in JSON strings. |
Format formats an entry as JSON.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
Level represents a log level.
// Example usage of Level
var value Level
// Initialize with appropriate valuetype Level intAllLevels returns all log levels.
func AllLevels() []LevelParameters: None
Returns:
ParseLevel parses a string into a Level.
func ParseLevel(s string) LevelParameters:
s (string)Returns:
Color returns the ANSI color code for the level.
func (Level) Color() stringParameters: None
Returns:
ShortString returns a 4-character representation for alignment.
func (Level) ShortString() stringParameters: None
Returns:
String returns the string representation of a level.
func String(key, value string) FieldParameters:
key (string)value (string)Returns:
LevelHook fires only for specific levels.
// Create a new LevelHook
levelhook := LevelHook{
}type LevelHook struct {
}NewLevelHook creates a hook that only fires for specific levels.
func NewLevelHook(hook Hook, levels ...Level) *LevelHookParameters:
hook (Hook)levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
LevelSampler applies different samplers per level.
// Create a new LevelSampler
levelsampler := LevelSampler{
}type LevelSampler struct {
}NewLevelSampler creates a sampler with per-level configuration.
func NewLevelSampler(fallback Sampler) *LevelSamplerParameters:
fallback (Sampler)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
WithLevel sets the sampler for a specific level.
func WithLevel(level Level) OptionParameters:
level (Level)Returns:
Logger is the main logging interface.
// Create a new Logger
logger := Logger{
}type Logger struct {
}Component creates a component logger from the default logger.
func Component(name string) *LoggerParameters:
name (string)Returns:
Default returns the default logger.
func Default() *LoggerParameters: None
Returns:
LoggerFromContext extracts a logger from the context. Returns the default logger if none is set.
func LoggerFromContext(ctx context.Context) *LoggerParameters:
ctx (context.Context)Returns:
Named creates a named child of the default logger.
func Named(name string) *LoggerParameters:
name (string)Returns:
New creates a new Logger with default settings.
func New(opts ...Option) *LoggerParameters:
opts (...Option)Returns:
With creates a child of the default logger with additional fields.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
AddHook adds a hook to the logger.
func (*Logger) AddHook(hook Hook)Parameters:
hook (Hook)Returns: None
Build returns a new Builder for constructing a log entry.
func (*Logger) Build() *BuilderParameters: None
Returns:
CheckErr logs an error and returns true if err is not nil. Useful in if statements: if log.CheckErr(err, "failed") { return }
func (*Logger) CheckErr(err error, msg string, fields ...Field) boolParameters:
err (error)msg (string)fields (...Field)Returns:
Close closes the logger and flushes any pending async logs.
func (*Logger) Close() errorParameters: None
Returns:
Component creates a named logger for a specific component. This is an alias for Named with a more semantic name.
func Component(name string) *LoggerParameters:
name (string)Returns:
Ctx returns a builder with context set.
func (*Logger) Ctx(ctx context.Context) *BuilderParameters:
ctx (context.Context)Returns:
Debug logs at debug level.
func (*ErrorBuilder) Debug(msg string)Parameters:
msg (string)Returns: None
DebugContext logs at debug level with context.
func (*Logger) DebugContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Debugf logs a formatted message at debug level.
func Debugf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
DebugfContext logs a formatted message at debug level with context.
func (*Logger) DebugfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
Error logs at error level.
func Error(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
ErrorContext logs at error level with context.
func (*Logger) ErrorContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Errorf logs a formatted message at error level.
func Errorf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
ErrorfContext logs a formatted message at error level with context.
func (*Logger) ErrorfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
F returns a builder with fields added using key-value pairs. Keys must be strings, values are auto-detected. Example: log.F("user", "john", "age", 30).Info("created")
func (*Logger) F(keyvals ...any) *BuilderParameters:
keyvals (...any)Returns:
Fatal logs at fatal level and exits.
func (*Builder) Fatal(msg string)Parameters:
msg (string)Returns: None
Fatalf logs a formatted message at fatal level and exits.
func Fatalf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
FullName returns the complete hierarchical name of the logger.
func (*Logger) FullName() stringParameters: None
Returns:
GetLevel returns the current log level.
func (*Logger) GetLevel() LevelParameters: None
Returns:
GetName returns the logger's name, or empty string if not named.
func (*Logger) GetName() stringParameters: None
Returns:
IfErr returns an ErrorBuilder if err is not nil, otherwise returns a no-op builder. This allows for one-liner error logging: log.IfErr(err).With("user", id).Error("failed to create user")
func (*Logger) IfErr(err error) *ErrorBuilderParameters:
err (error)Returns:
Info logs at info level.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
InfoContext logs at info level with context.
func (*Logger) InfoContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Infof logs a formatted message at info level.
func Infof(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
InfofContext logs a formatted message at info level with context.
func (*Logger) InfofContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
IsEnabled returns true if the given level is enabled.
func (*Logger) IsEnabled(level Level) boolParameters:
level (Level)Returns:
Log logs at a specific level.
func (*Logger) Log(level Level, msg string, fields ...Field)Parameters:
level (Level)msg (string)fields (...Field)Returns: None
LogContext logs at a specific level with context.
func (*Logger) LogContext(ctx context.Context, level Level, msg string, fields ...Field)Parameters:
ctx (context.Context)level (Level)msg (string)fields (...Field)Returns: None
LogErr logs an error at error level if not nil. This is a simple one-liner for common error logging. log.LogErr(err, "operation failed")
func (*Logger) LogErr(err error, msg string, fields ...Field)Parameters:
err (error)msg (string)fields (...Field)Returns: None
Module creates a named logger for a module. This is an alias for Named with a more semantic name.
func (*Logger) Module(name string) *LoggerParameters:
name (string)Returns:
MustErr panics if error is not nil, logging the error first.
func (*Logger) MustErr(err error, msg string, fields ...Field)Parameters:
err (error)msg (string)fields (...Field)Returns: None
NameParts returns the name split into parts.
func (*Logger) NameParts() []stringParameters: None
Returns:
Named creates a child logger with a name prefix. Names are joined with dots to create a hierarchy. userLog := log.Named("users") // [users] authLog := userLog.Named("auth") // [users.auth] log.Info("action") // [users.auth] action
func Named(name string) *LoggerParameters:
name (string)Returns:
Panic logs at panic level and panics.
func (*Builder) Panic(msg string)Parameters:
msg (string)Returns: None
Panicf logs a formatted message at panic level and panics.
func Panicf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
Print logs a message at info level (stdlib log compatibility).
func Print(args ...any)Parameters:
args (...any)Returns: None
Printf logs a formatted message at info level (stdlib log compatibility).
func Printf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
Println logs a message at info level (stdlib log compatibility).
func Println(args ...any)Parameters:
args (...any)Returns: None
Service creates a named logger for a service. This is an alias for Named with a more semantic name.
func (*Logger) Service(name string) *LoggerParameters:
name (string)Returns:
SetFormatter sets the formatter.
func (*Logger) SetFormatter(f Formatter)Parameters:
f (Formatter)Returns: None
SetLevel sets the minimum log level.
func (*Logger) SetLevel(level Level)Parameters:
level (Level)Returns: None
SetOutput sets the output writer.
func (*Logger) SetOutput(w io.Writer)Parameters:
w (io.Writer)Returns: None
Trace logs at trace level.
func Trace(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
TraceContext logs at trace level with context.
func (*Logger) TraceContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Tracef logs a formatted message at trace level.
func Tracef(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
TracefContext logs a formatted message at trace level with context.
func (*Logger) TracefContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
Warn logs at warn level.
func Warn(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
WarnContext logs at warn level with context.
func (*Logger) WarnContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Warnf logs a formatted message at warn level.
func Warnf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
WarnfContext logs a formatted message at warn level with context.
func (*Logger) WarnfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
With creates a child logger with additional fields.
func (*Builder) With(key string, value any) *BuilderParameters:
key (string)value (any)Returns:
WrapErr wraps an error with additional context and logs it. Returns the wrapped error for returning from functions. return log.WrapErr(err, "failed to connect", logs.String("host", host))
func (*Logger) WrapErr(err error, msg string, fields ...Field) errorParameters:
err (error)msg (string)fields (...Field)Returns:
WrapErrLevel wraps an error and logs at a specific level.
func (*Logger) WrapErrLevel(level Level, err error, msg string, fields ...Field) errorParameters:
level (Level)err (error)msg (string)fields (...Field)Returns:
MetricsHook tracks log counts by level.
// Create a new MetricsHook
metricshook := MetricsHook{
}type MetricsHook struct {
}NewMetricsHook creates a hook that tracks log counts.
func NewMetricsHook() *MetricsHookParameters: None
Returns:
Count returns the count for a level.
func (*MetricsHook) Count(level Level) uint64Parameters:
level (Level)Returns:
Counts returns all counts.
func (*MetricsHook) Counts() map[Level]uint64Parameters: None
Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Reset resets all counts.
func (*MetricsHook) Reset()Parameters: None
Returns: None
NamedFormatter is a formatter that includes the logger name in output.
// Create a new NamedFormatter
namedformatter := NamedFormatter{
Inner: Formatter{},
Separator: "example",
Brackets: "example",
}type NamedFormatter struct {
Inner Formatter
Separator string
Brackets string
}| Field | Type | Description |
|---|---|---|
| Inner | Formatter | Inner is the formatter to wrap. |
| Separator | string | Separator is placed between the name and message. Default: " " |
| Brackets | string | Brackets wraps the name. Default: "[]" |
Format formats an entry, prefixing with the logger name if present.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
NeverSampler never allows logging.
// Create a new NeverSampler
neversampler := NeverSampler{
}type NeverSampler struct {
}Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
NoopFormatter discards all output.
// Create a new NoopFormatter
noopformatter := NoopFormatter{
}type NoopFormatter struct {
}Format returns nil.
func (*NamedFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
OncePerSampler logs a message only once per duration.
// Create a new OncePerSampler
oncepersampler := OncePerSampler{
}type OncePerSampler struct {
}NewOncePerSampler creates a sampler that logs each message at most once per period.
func NewOncePerSampler(period time.Duration) *OncePerSamplerParameters:
period (time.Duration)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Option configures a Logger.
// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Logger)WithAsync enables asynchronous logging.
func WithAsync(bufferSize int) OptionParameters:
bufferSize (int)Returns:
WithCaller enables caller information in logs.
func WithCaller() OptionParameters: None
Returns:
WithCallerDepth sets the caller stack depth.
func WithCallerDepth(depth int) OptionParameters:
depth (int)Returns:
WithFields adds default fields to all log entries.
func (*Builder) WithFields(fields ...Field) *BuilderParameters:
fields (...Field)Returns:
WithFormatter sets the log formatter.
func WithFormatter(f Formatter) OptionParameters:
f (Formatter)Returns:
WithHooks adds hooks to the logger.
func WithHooks(hooks ...Hook) OptionParameters:
hooks (...Hook)Returns:
WithLevel sets the minimum log level.
func WithLevel(level Level) OptionParameters:
level (Level)Returns:
WithNamedFormat wraps the current formatter to include logger names.
func WithNamedFormat() OptionParameters: None
Returns:
WithOutput sets the output writer.
func WithOutput(w io.Writer) OptionParameters:
w (io.Writer)Returns:
WithSampler sets a sampler for rate limiting logs.
func WithSampler(s Sampler) OptionParameters:
s (Sampler)Returns:
WithStackTrace enables stack traces for error and above.
func WithStackTrace() OptionParameters: None
Returns:
PrettyFormatter formats logs with colors and alignment for development.
// Create a new PrettyFormatter
prettyformatter := PrettyFormatter{
TimestampFormat: "example",
ShowCaller: true,
ShowTimestamp: true,
}type PrettyFormatter struct {
TimestampFormat string
ShowCaller bool
ShowTimestamp bool
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: "15:04:05.000" |
| ShowCaller | bool | ShowCaller shows caller information. |
| ShowTimestamp | bool | ShowTimestamp shows timestamps. |
Format formats an entry in a pretty, colorful format.
func (*NamedFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
RandomSampler samples a percentage of logs.
// Create a new RandomSampler
randomsampler := RandomSampler{
}type RandomSampler struct {
}NewRandomSampler creates a sampler that logs a percentage of entries. percentage should be between 0 and 100.
func NewRandomSampler(percentage int) *RandomSamplerParameters:
percentage (int)Returns:
Sample implements Sampler using a simple modulo for deterministic "random" sampling.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
RateSampler limits logs to a certain rate per message.
// Create a new RateSampler
ratesampler := RateSampler{
}type RateSampler struct {
}NewRateSampler creates a sampler that limits log rate per message. rate is the number of logs allowed per window. burst is the initial burst allowance.
func NewRateSampler(rate int, window time.Duration) *RateSamplerParameters:
rate (int)window (time.Duration)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
WithBurst sets the burst allowance.
func (*RateSampler) WithBurst(burst int) *RateSamplerParameters:
burst (int)Returns:
Sampler determines if a log entry should be emitted.
// Example implementation of Sampler
type MySampler struct {
// Add your fields here
}
func (m MySampler) Sample(param1 Level, param2 string) bool {
// Implement your logic here
return
}
type Sampler interface {
Sample(level Level, msg string) bool
}| Method | Description |
|---|
TextFormatter formats logs as text.
// Create a new TextFormatter
textformatter := TextFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
DisableColors: true,
DisableQuoting: true,
QuoteEmptyFields: true,
FullTimestamp: true,
PadLevelText: true,
FieldSeparator: "example",
KeyValueSeparator: "example",
}type TextFormatter struct {
TimestampFormat string
DisableTimestamp bool
DisableColors bool
DisableQuoting bool
QuoteEmptyFields bool
FullTimestamp bool
PadLevelText bool
FieldSeparator string
KeyValueSeparator string
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: "2006-01-02T15:04:05.000Z07:00" |
| DisableTimestamp | bool | DisableTimestamp disables timestamp output. |
| DisableColors | bool | DisableColors disables ANSI colors. |
| DisableQuoting | bool | DisableQuoting disables quoting of string values. |
| QuoteEmptyFields | bool | QuoteEmptyFields quotes empty field values. |
| FullTimestamp | bool | FullTimestamp shows full timestamp instead of relative time. |
| PadLevelText | bool | PadLevelText pads level text for alignment. |
| FieldSeparator | string | FieldSeparator is the separator between fields. Default: " " |
| KeyValueSeparator | string | KeyValueSeparator is the separator between key and value. Default: "=" |
Format formats an entry as text.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
WriterHook writes entries to an io.Writer.
// Create a new WriterHook
writerhook := WriterHook{
}type WriterHook struct {
}NewWriterHook creates a hook that writes to an io.Writer.
func NewWriterHook(w io.Writer, formatter Formatter, levels ...Level) *WriterHookParameters:
w (io.Writer)formatter (Formatter)levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
CtxDebug logs at debug level using the logger from context.
func CtxDebug(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxDebug
result := CtxDebug(/* parameters */)CtxError logs at error level using the logger from context.
func CtxError(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxError
result := CtxError(/* parameters */)CtxInfo logs at info level using the logger from context.
func CtxInfo(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxInfo
result := CtxInfo(/* parameters */)CtxTrace logs at trace level using the logger from context.
func CtxTrace(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxTrace
result := CtxTrace(/* parameters */)CtxWarn logs at warn level using the logger from context.
func CtxWarn(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxWarn
result := CtxWarn(/* parameters */)Debug logs at debug level using the default logger.
func (*Builder) Debug(msg string)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string |
Returns: None
Example:
// Example usage of Debug
result := Debug(/* parameters */)Debugf logs a formatted message at debug level.
func Debugf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Debugf
result := Debugf(/* parameters */)Error logs at error level using the default logger.
func Error(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Error
result := Error(/* parameters */)Errorf logs a formatted message at error level.
func Errorf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Errorf
result := Errorf(/* parameters */)Fatal logs at fatal level using the default logger and exits.
func (*Builder) Fatal(msg string)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string |
Returns: None
Example:
// Example usage of Fatal
result := Fatal(/* parameters */)Fatalf logs a formatted message at fatal level and exits.
func Fatalf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Fatalf
result := Fatalf(/* parameters */)Info logs at info level using the default logger.
func Info(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Info
result := Info(/* parameters */)Infof logs a formatted message at info level.
func Infof(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Infof
result := Infof(/* parameters */)Must logs and panics if error is not nil. Useful for initialization code. db := log.Must(sql.Open("postgres", dsn))
func Must(l *Logger, val T, err error) TParameters:
| Parameter | Type | Description |
|---|---|---|
l | *Logger | |
val | T | |
err | error |
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of Must
result := Must(/* parameters */)Panic logs at panic level using the default logger and panics.
func Panic(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Panic
result := Panic(/* parameters */)Panicf logs a formatted message at panic level and panics.
func Panicf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Panicf
result := Panicf(/* parameters */)Print logs a message at info level.
func Print(args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
args | ...any |
Returns: None
Example:
// Example usage of Print
result := Print(/* parameters */)Printf logs a formatted message at info level.
func Printf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Printf
result := Printf(/* parameters */)Println logs a message at info level.
func Println(args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
args | ...any |
Returns: None
Example:
// Example usage of Println
result := Println(/* parameters */)SetDefault sets the default logger.
func SetDefault(l *Logger)Parameters:
| Parameter | Type | Description |
|---|---|---|
l | *Logger |
Returns: None
Example:
// Example usage of SetDefault
result := SetDefault(/* parameters */)SetDefaultFormatter sets the default formatter.
func SetDefaultFormatter(f Formatter)Parameters:
| Parameter | Type | Description |
|---|---|---|
f | Formatter |
Returns: None
Example:
// Example usage of SetDefaultFormatter
result := SetDefaultFormatter(/* parameters */)SetDefaultLevel sets the default level.
func SetDefaultLevel(level Level)Parameters:
| Parameter | Type | Description |
|---|---|---|
level | Level |
Returns: None
Example:
// Example usage of SetDefaultLevel
result := SetDefaultLevel(/* parameters */)Trace logs at trace level using the default logger.
func Trace(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Trace
result := Trace(/* parameters */)Tracef logs a formatted message at trace level.
func Tracef(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Tracef
result := Tracef(/* parameters */)Warn logs at warn level using the default logger.
func Warn(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Warn
result := Warn(/* parameters */)Warnf logs a formatted message at warn level.
func Warnf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Warnf
result := Warnf(/* parameters */)WithFields adds fields to the context that will be included in all logs.
func WithContextFields(ctx context.Context, fields ...Field) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
fields | ...Field |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithContextFields
result := WithContextFields(/* parameters */)WithLogger attaches a logger to the context.
func WithLogger(ctx context.Context, logger *Logger) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
logger | *Logger |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithLogger
result := WithLogger(/* parameters */)WithRequestID adds a request ID to the context.
func WithRequestID(ctx context.Context, requestID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
requestID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithRequestID
result := WithRequestID(/* parameters */)WithTraceID adds a trace ID to the context.
func WithTraceID(ctx context.Context, traceID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
traceID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithTraceID
result := WithTraceID(/* parameters */)WithUserID adds a user ID to the context.
func WithUserID(ctx context.Context, userID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
userID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithUserID
result := WithUserID(/* parameters */)Complete API documentation for the logs package.
Import Path: github.com/kolosys/helix/logs
Package logs provides a high-performance, context-aware structured logging library.
Features:
Basic usage:
log := logs.New()
log.Info("server started", logs.Int("port", 8080))With context:
log.InfoContext(ctx, "request processed", logs.Duration("latency", time.Since(start)))
RequestIDKey
RequestID is a common field key for request IDs.
const RequestIDKey = "request_id"TraceIDKey
TraceID is a common field key for trace IDs.
const TraceIDKey = "trace_id"UserIDKey
UserID is a common field key for user IDs.
const UserIDKey = "user_id"AlwaysSampler always allows logging.
// Create a new AlwaysSampler
alwayssampler := AlwaysSampler{
}type AlwaysSampler struct {
}Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Builder provides a fluent/chainable API for building log entries. It accumulates fields and then emits a log entry when a level method is called.
// Create a new Builder
builder := Builder{
}type Builder struct {
}Bool adds a bool field.
func Bool(key string, value bool) FieldParameters:
key (string)value (bool)Returns:
Debug logs at debug level.
func (*Builder) Debug(msg string)Parameters:
msg (string)Returns: None
Err adds an error field with key "error".
func (*Builder) Err(err error) *BuilderParameters:
err (error)Returns:
Error logs at error level.
func (*Builder) Error(msg string)Parameters:
msg (string)Returns: None
Fatal logs at fatal level and exits.
func Fatal(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Float64 adds a float64 field.
func Float64(key string, value float64) FieldParameters:
key (string)value (float64)Returns:
Info logs at info level.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Int adds an int field.
func (*Builder) Int(key string, value int) *BuilderParameters:
key (string)value (int)Returns:
Int64 adds an int64 field.
func Int64(key string, value int64) FieldParameters:
key (string)value (int64)Returns:
Log logs at the specified level.
func (*Builder) Log(level Level, msg string)Parameters:
level (Level)msg (string)Returns: None
Msg is an alias for Info (zerolog-style).
func (*Builder) Msg(msg string)Parameters:
msg (string)Returns: None
Panic logs at panic level and panics.
func (*Builder) Panic(msg string)Parameters:
msg (string)Returns: None
Send logs with an empty message (zerolog-style).
func (*Builder) Send()Parameters: None
Returns: None
Str adds a string field.
func (*Builder) Str(key, value string) *BuilderParameters:
key (string)value (string)Returns:
Trace logs at trace level.
func (*Builder) Trace(msg string)Parameters:
msg (string)Returns: None
Uint adds a uint field.
func (*Builder) Uint(key string, value uint) *BuilderParameters:
key (string)value (uint)Returns:
Uint64 adds a uint64 field.
func Uint64(key string, value uint64) FieldParameters:
key (string)value (uint64)Returns:
Warn logs at warn level.
func Warn(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
With adds a field to the builder using auto-detection.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
WithContext sets the context for the log entry.
func (*Builder) WithContext(ctx context.Context) *BuilderParameters:
ctx (context.Context)Returns:
WithError adds an error field.
func (*Builder) WithError(err error) *BuilderParameters:
err (error)Returns:
WithField adds a typed field to the builder.
func (*Builder) WithField(f Field) *BuilderParameters:
f (Field)Returns:
WithFields adds multiple typed fields to the builder.
func WithFields(fields ...Field) OptionParameters:
fields (...Field)Returns:
CompositeSampler combines multiple samplers with AND logic.
// Create a new CompositeSampler
compositesampler := CompositeSampler{
}type CompositeSampler struct {
}NewCompositeSampler creates a sampler that requires all samplers to pass.
func NewCompositeSampler(samplers ...Sampler) *CompositeSamplerParameters:
samplers (...Sampler)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
CountSampler logs every Nth occurrence.
// Create a new CountSampler
countsampler := CountSampler{
}type CountSampler struct {
}NewCountSampler creates a sampler that logs every Nth occurrence.
func NewCountSampler(n int) *CountSamplerParameters:
n (int)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Entry represents a log entry.
// Create a new Entry
entry := Entry{
Level: Level{},
Time: /* value */,
Message: "example",
Fields: [],
Caller: "example",
Stack: "example",
}type Entry struct {
Level Level
Time time.Time
Message string
Fields []Field
Caller string
Stack string
}| Field | Type | Description |
|---|---|---|
| Level | Level | |
| Time | time.Time | |
| Message | string | |
| Fields | []Field | |
| Caller | string | |
| Stack | string |
GetField returns the field with the given key, or an empty field if not found.
func (*Entry) GetField(key string) (Field, bool)Parameters:
key (string)Returns:
GetString returns the string value of a field, or empty string if not found.
func (*Entry) GetString(key string) stringParameters:
key (string)Returns:
HasField returns true if the entry has a field with the given key.
func (*Entry) HasField(key string) boolParameters:
key (string)Returns:
ErrorBuilder provides a fluent API for logging errors.
// Create a new ErrorBuilder
errorbuilder := ErrorBuilder{
}type ErrorBuilder struct {
}Debug logs at debug level if error is not nil.
func (*ErrorBuilder) Debug(msg string)Parameters:
msg (string)Returns: None
Error logs at error level if error is not nil.
func (*ErrorBuilder) Error(msg string)Parameters:
msg (string)Returns: None
Fatal logs at fatal level if error is not nil and exits.
func Fatal(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Info logs at info level if error is not nil.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Trace logs at trace level if error is not nil.
func Trace(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
Warn logs at warn level if error is not nil.
func (*Builder) Warn(msg string)Parameters:
msg (string)Returns: None
With adds a field to the error builder.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
WithField adds a typed field.
func (*Builder) WithField(f Field) *BuilderParameters:
f (Field)Returns:
WithFields adds multiple fields.
func WithFields(fields ...Field) OptionParameters:
fields (...Field)Returns:
ErrorHook collects errors for inspection.
// Create a new ErrorHook
errorhook := ErrorHook{
}type ErrorHook struct {
}NewErrorHook creates a hook that collects error entries.
func NewErrorHook(maxEntries int) *ErrorHookParameters:
maxEntries (int)Returns:
Clear clears collected errors.
func (*ErrorHook) Clear()Parameters: None
Returns: None
Errors returns collected errors.
func (*ErrorHook) Errors() []EntryParameters: None
Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Field represents a structured log field.
// Create a new Field
field := Field{
Key: "example",
Type: FieldType{},
Int: 42,
Uint: 42,
Float: 3.14,
String: "example",
Interface: any{},
}type Field struct {
Key string
Type FieldType
Int int64
Uint uint64
Float float64
String string
Interface any
}| Field | Type | Description |
|---|---|---|
| Key | string | |
| Type | FieldType | |
| Int | int64 | |
| Uint | uint64 | |
| Float | float64 | |
| String | string | |
| Interface | any |
Any creates a field with any value.
func Any(key string, value any) FieldParameters:
key (string)value (any)Returns:
Bool creates a bool field.
func (*Builder) Bool(key string, value bool) *BuilderParameters:
key (string)value (bool)Returns:
Bytes creates a []byte field.
func Bytes(key string, value []byte) FieldParameters:
key (string)value ([]byte)Returns:
Duration creates a time.Duration field.
func Duration(key string, value time.Duration) FieldParameters:
key (string)value (time.Duration)Returns:
Err creates an error field with key "error".
func (*Builder) Err(err error) *BuilderParameters:
err (error)Returns:
ErrChain creates a field that unwraps the error chain.
func ErrChain(err error) FieldParameters:
err (error)Returns:
ErrWithStack creates an error field with stack trace.
func ErrWithStack(err error) FieldParameters:
err (error)Returns:
FieldsFromContext extracts fields from the context.
func FieldsFromContext(ctx context.Context) []FieldParameters:
ctx (context.Context)Returns:
Float32 creates a float32 field.
func Float32(key string, value float32) FieldParameters:
key (string)value (float32)Returns:
Float64 creates a float64 field.
func (*Builder) Float64(key string, value float64) *BuilderParameters:
key (string)value (float64)Returns:
Int creates an int field.
func Int(key string, value int) FieldParameters:
key (string)value (int)Returns:
Int16 creates an int16 field.
func Int16(key string, value int16) FieldParameters:
key (string)value (int16)Returns:
Int32 creates an int32 field.
func Int32(key string, value int32) FieldParameters:
key (string)value (int32)Returns:
Int64 creates an int64 field.
func Int64(key string, value int64) FieldParameters:
key (string)value (int64)Returns:
Int8 creates an int8 field.
func Int8(key string, value int8) FieldParameters:
key (string)value (int8)Returns:
JSON creates a field that will be JSON-encoded.
func JSON(key string, value any) FieldParameters:
key (string)value (any)Returns:
NamedErr creates an error field with a custom key.
func NamedErr(key string, err error) FieldParameters:
key (string)err (error)Returns:
Namespace creates a namespace field for grouping.
func Namespace(key string) FieldParameters:
key (string)Returns:
Object creates a field from any value, attempting to extract structure. For structs, it extracts fields. For other types, it uses Any.
func Object(key string, v any) FieldParameters:
key (string)v (any)Returns:
Stack creates a field containing a stack trace.
func Stack(key string) FieldParameters:
key (string)Returns:
String creates a string field.
func String(key, value string) FieldParameters:
key (string)value (string)Returns:
Stringer creates a field from a fmt.Stringer.
func Stringer(key string, value fmt.Stringer) FieldParameters:
key (string)value (fmt.Stringer)Returns:
Strings creates a string slice field.
func Strings(key string, values []string) FieldParameters:
key (string)values ([]string)Returns:
Struct creates fields from a struct's exported fields. It uses json tags for field names if available, otherwise uses the field name. Nested structs are flattened with dot notation.
func Struct(key string, v any) FieldParameters:
key (string)v (any)Returns:
StructFlat creates multiple top-level fields from a struct's exported fields. Unlike Struct, this doesn't nest under a key - fields are added directly.
func StructFlat(v any) []FieldParameters:
v (any)Returns:
Time creates a time.Time field.
func Time(key string, value time.Time) FieldParameters:
key (string)value (time.Time)Returns:
Uint creates a uint field.
func Uint(key string, value uint) FieldParameters:
key (string)value (uint)Returns:
Uint16 creates a uint16 field.
func Uint16(key string, value uint16) FieldParameters:
key (string)value (uint16)Returns:
Uint32 creates a uint32 field.
func Uint32(key string, value uint32) FieldParameters:
key (string)value (uint32)Returns:
Uint64 creates a uint64 field.
func (*Builder) Uint64(key string, value uint64) *BuilderParameters:
key (string)value (uint64)Returns:
Uint8 creates a uint8 field.
func Uint8(key string, value uint8) FieldParameters:
key (string)value (uint8)Returns:
V creates a field with automatic type detection. This is a convenience function for when you don't want to specify the type.
func V(key string, value any) FieldParameters:
key (string)value (any)Returns:
StringValue returns the field value as a string.
func (Field) StringValue() stringParameters: None
Returns:
Value returns the field value as an interface{}.
func (Field) Value() anyParameters: None
Returns:
FieldType represents the type of a field value.
// Example usage of FieldType
var value FieldType
// Initialize with appropriate valuetype FieldType uint8FileHook writes entries to a file.
// Create a new FileHook
filehook := FileHook{
}type FileHook struct {
*WriterHook
}| Field | Type | Description |
|---|---|---|
| **WriterHook | *WriterHook |
NewFileHook creates a hook that writes to a file.
func NewFileHook(path string, formatter Formatter, levels ...Level) (*FileHook, error)Parameters:
path (string)formatter (Formatter)levels (...Level)Returns:
Close closes the file.
func (*Logger) Close() errorParameters: None
Returns:
FilterHook conditionally fires another hook.
// Create a new FilterHook
filterhook := FilterHook{
}type FilterHook struct {
}NewFilterHook creates a hook that conditionally fires.
func NewFilterHook(hook Hook, filter func(*Entry) bool) *FilterHookParameters:
hook (Hook)filter (func(*Entry) bool)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
FirstNSampler logs only the first N occurrences.
// Create a new FirstNSampler
firstnsampler := FirstNSampler{
}type FirstNSampler struct {
}NewFirstNSampler creates a sampler that logs only the first N occurrences.
func NewFirstNSampler(n int) *FirstNSamplerParameters:
n (int)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Formatter formats log entries.
// Example implementation of Formatter
type MyFormatter struct {
// Add your fields here
}
func (m MyFormatter) Format(param1 *Entry) []byte {
// Implement your logic here
return
}
type Formatter interface {
Format(entry *Entry) ([]byte, error)
}| Method | Description |
|---|
FuncHook wraps a function as a hook.
// Create a new FuncHook
funchook := FuncHook{
}type FuncHook struct {
}NewFuncHook creates a hook from a function.
func NewFuncHook(fn func(*Entry), levels ...Level) *FuncHookParameters:
fn (func(*Entry))levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Hook is called when a log entry is written.
// Example implementation of Hook
type MyHook struct {
// Add your fields here
}
func (m MyHook) Fire(param1 *Entry) {
// Implement your logic here
return
}
func (m MyHook) Levels() []Level {
// Implement your logic here
return
}
type Hook interface {
Fire(entry *Entry)
Levels() []Level
}| Method | Description |
|---|
JSONFormatter formats logs as JSON.
// Create a new JSONFormatter
jsonformatter := JSONFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
TimestampKey: "example",
LevelKey: "example",
MessageKey: "example",
CallerKey: "example",
StackKey: "example",
PrettyPrint: true,
EscapeHTML: true,
}type JSONFormatter struct {
TimestampFormat string
DisableTimestamp bool
TimestampKey string
LevelKey string
MessageKey string
CallerKey string
StackKey string
PrettyPrint bool
EscapeHTML bool
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: time.RFC3339Nano |
| DisableTimestamp | bool | DisableTimestamp disables timestamp output. |
| TimestampKey | string | TimestampKey is the key for the timestamp field. Default: "time" |
| LevelKey | string | LevelKey is the key for the level field. Default: "level" |
| MessageKey | string | MessageKey is the key for the message field. Default: "msg" |
| CallerKey | string | CallerKey is the key for the caller field. Default: "caller" |
| StackKey | string | StackKey is the key for the stack trace field. Default: "stack" |
| PrettyPrint | bool | PrettyPrint enables pretty-printed JSON. |
| EscapeHTML | bool | EscapeHTML escapes HTML in JSON strings. |
Format formats an entry as JSON.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
Level represents a log level.
// Example usage of Level
var value Level
// Initialize with appropriate valuetype Level intAllLevels returns all log levels.
func AllLevels() []LevelParameters: None
Returns:
ParseLevel parses a string into a Level.
func ParseLevel(s string) LevelParameters:
s (string)Returns:
Color returns the ANSI color code for the level.
func (Level) Color() stringParameters: None
Returns:
ShortString returns a 4-character representation for alignment.
func (Level) ShortString() stringParameters: None
Returns:
String returns the string representation of a level.
func String(key, value string) FieldParameters:
key (string)value (string)Returns:
LevelHook fires only for specific levels.
// Create a new LevelHook
levelhook := LevelHook{
}type LevelHook struct {
}NewLevelHook creates a hook that only fires for specific levels.
func NewLevelHook(hook Hook, levels ...Level) *LevelHookParameters:
hook (Hook)levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
LevelSampler applies different samplers per level.
// Create a new LevelSampler
levelsampler := LevelSampler{
}type LevelSampler struct {
}NewLevelSampler creates a sampler with per-level configuration.
func NewLevelSampler(fallback Sampler) *LevelSamplerParameters:
fallback (Sampler)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
WithLevel sets the sampler for a specific level.
func WithLevel(level Level) OptionParameters:
level (Level)Returns:
Logger is the main logging interface.
// Create a new Logger
logger := Logger{
}type Logger struct {
}Component creates a component logger from the default logger.
func Component(name string) *LoggerParameters:
name (string)Returns:
Default returns the default logger.
func Default() *LoggerParameters: None
Returns:
LoggerFromContext extracts a logger from the context. Returns the default logger if none is set.
func LoggerFromContext(ctx context.Context) *LoggerParameters:
ctx (context.Context)Returns:
Named creates a named child of the default logger.
func Named(name string) *LoggerParameters:
name (string)Returns:
New creates a new Logger with default settings.
func New(opts ...Option) *LoggerParameters:
opts (...Option)Returns:
With creates a child of the default logger with additional fields.
func With(fields ...Field) *LoggerParameters:
fields (...Field)Returns:
AddHook adds a hook to the logger.
func (*Logger) AddHook(hook Hook)Parameters:
hook (Hook)Returns: None
Build returns a new Builder for constructing a log entry.
func (*Logger) Build() *BuilderParameters: None
Returns:
CheckErr logs an error and returns true if err is not nil. Useful in if statements: if log.CheckErr(err, "failed") { return }
func (*Logger) CheckErr(err error, msg string, fields ...Field) boolParameters:
err (error)msg (string)fields (...Field)Returns:
Close closes the logger and flushes any pending async logs.
func (*Logger) Close() errorParameters: None
Returns:
Component creates a named logger for a specific component. This is an alias for Named with a more semantic name.
func Component(name string) *LoggerParameters:
name (string)Returns:
Ctx returns a builder with context set.
func (*Logger) Ctx(ctx context.Context) *BuilderParameters:
ctx (context.Context)Returns:
Debug logs at debug level.
func (*ErrorBuilder) Debug(msg string)Parameters:
msg (string)Returns: None
DebugContext logs at debug level with context.
func (*Logger) DebugContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Debugf logs a formatted message at debug level.
func Debugf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
DebugfContext logs a formatted message at debug level with context.
func (*Logger) DebugfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
Error logs at error level.
func Error(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
ErrorContext logs at error level with context.
func (*Logger) ErrorContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Errorf logs a formatted message at error level.
func Errorf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
ErrorfContext logs a formatted message at error level with context.
func (*Logger) ErrorfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
F returns a builder with fields added using key-value pairs. Keys must be strings, values are auto-detected. Example: log.F("user", "john", "age", 30).Info("created")
func (*Logger) F(keyvals ...any) *BuilderParameters:
keyvals (...any)Returns:
Fatal logs at fatal level and exits.
func (*Builder) Fatal(msg string)Parameters:
msg (string)Returns: None
Fatalf logs a formatted message at fatal level and exits.
func Fatalf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
FullName returns the complete hierarchical name of the logger.
func (*Logger) FullName() stringParameters: None
Returns:
GetLevel returns the current log level.
func (*Logger) GetLevel() LevelParameters: None
Returns:
GetName returns the logger's name, or empty string if not named.
func (*Logger) GetName() stringParameters: None
Returns:
IfErr returns an ErrorBuilder if err is not nil, otherwise returns a no-op builder. This allows for one-liner error logging: log.IfErr(err).With("user", id).Error("failed to create user")
func (*Logger) IfErr(err error) *ErrorBuilderParameters:
err (error)Returns:
Info logs at info level.
func Info(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
InfoContext logs at info level with context.
func (*Logger) InfoContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Infof logs a formatted message at info level.
func Infof(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
InfofContext logs a formatted message at info level with context.
func (*Logger) InfofContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
IsEnabled returns true if the given level is enabled.
func (*Logger) IsEnabled(level Level) boolParameters:
level (Level)Returns:
Log logs at a specific level.
func (*Logger) Log(level Level, msg string, fields ...Field)Parameters:
level (Level)msg (string)fields (...Field)Returns: None
LogContext logs at a specific level with context.
func (*Logger) LogContext(ctx context.Context, level Level, msg string, fields ...Field)Parameters:
ctx (context.Context)level (Level)msg (string)fields (...Field)Returns: None
LogErr logs an error at error level if not nil. This is a simple one-liner for common error logging. log.LogErr(err, "operation failed")
func (*Logger) LogErr(err error, msg string, fields ...Field)Parameters:
err (error)msg (string)fields (...Field)Returns: None
Module creates a named logger for a module. This is an alias for Named with a more semantic name.
func (*Logger) Module(name string) *LoggerParameters:
name (string)Returns:
MustErr panics if error is not nil, logging the error first.
func (*Logger) MustErr(err error, msg string, fields ...Field)Parameters:
err (error)msg (string)fields (...Field)Returns: None
NameParts returns the name split into parts.
func (*Logger) NameParts() []stringParameters: None
Returns:
Named creates a child logger with a name prefix. Names are joined with dots to create a hierarchy. userLog := log.Named("users") // [users] authLog := userLog.Named("auth") // [users.auth] log.Info("action") // [users.auth] action
func Named(name string) *LoggerParameters:
name (string)Returns:
Panic logs at panic level and panics.
func (*Builder) Panic(msg string)Parameters:
msg (string)Returns: None
Panicf logs a formatted message at panic level and panics.
func Panicf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
Print logs a message at info level (stdlib log compatibility).
func Print(args ...any)Parameters:
args (...any)Returns: None
Printf logs a formatted message at info level (stdlib log compatibility).
func Printf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
Println logs a message at info level (stdlib log compatibility).
func Println(args ...any)Parameters:
args (...any)Returns: None
Service creates a named logger for a service. This is an alias for Named with a more semantic name.
func (*Logger) Service(name string) *LoggerParameters:
name (string)Returns:
SetFormatter sets the formatter.
func (*Logger) SetFormatter(f Formatter)Parameters:
f (Formatter)Returns: None
SetLevel sets the minimum log level.
func (*Logger) SetLevel(level Level)Parameters:
level (Level)Returns: None
SetOutput sets the output writer.
func (*Logger) SetOutput(w io.Writer)Parameters:
w (io.Writer)Returns: None
Trace logs at trace level.
func Trace(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
TraceContext logs at trace level with context.
func (*Logger) TraceContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Tracef logs a formatted message at trace level.
func Tracef(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
TracefContext logs a formatted message at trace level with context.
func (*Logger) TracefContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
Warn logs at warn level.
func Warn(msg string, fields ...Field)Parameters:
msg (string)fields (...Field)Returns: None
WarnContext logs at warn level with context.
func (*Logger) WarnContext(ctx context.Context, msg string, fields ...Field)Parameters:
ctx (context.Context)msg (string)fields (...Field)Returns: None
Warnf logs a formatted message at warn level.
func Warnf(format string, args ...any)Parameters:
format (string)args (...any)Returns: None
WarnfContext logs a formatted message at warn level with context.
func (*Logger) WarnfContext(ctx context.Context, format string, args ...any)Parameters:
ctx (context.Context)format (string)args (...any)Returns: None
With creates a child logger with additional fields.
func (*Builder) With(key string, value any) *BuilderParameters:
key (string)value (any)Returns:
WrapErr wraps an error with additional context and logs it. Returns the wrapped error for returning from functions. return log.WrapErr(err, "failed to connect", logs.String("host", host))
func (*Logger) WrapErr(err error, msg string, fields ...Field) errorParameters:
err (error)msg (string)fields (...Field)Returns:
WrapErrLevel wraps an error and logs at a specific level.
func (*Logger) WrapErrLevel(level Level, err error, msg string, fields ...Field) errorParameters:
level (Level)err (error)msg (string)fields (...Field)Returns:
MetricsHook tracks log counts by level.
// Create a new MetricsHook
metricshook := MetricsHook{
}type MetricsHook struct {
}NewMetricsHook creates a hook that tracks log counts.
func NewMetricsHook() *MetricsHookParameters: None
Returns:
Count returns the count for a level.
func (*MetricsHook) Count(level Level) uint64Parameters:
level (Level)Returns:
Counts returns all counts.
func (*MetricsHook) Counts() map[Level]uint64Parameters: None
Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
Reset resets all counts.
func (*MetricsHook) Reset()Parameters: None
Returns: None
NamedFormatter is a formatter that includes the logger name in output.
// Create a new NamedFormatter
namedformatter := NamedFormatter{
Inner: Formatter{},
Separator: "example",
Brackets: "example",
}type NamedFormatter struct {
Inner Formatter
Separator string
Brackets string
}| Field | Type | Description |
|---|---|---|
| Inner | Formatter | Inner is the formatter to wrap. |
| Separator | string | Separator is placed between the name and message. Default: " " |
| Brackets | string | Brackets wraps the name. Default: "[]" |
Format formats an entry, prefixing with the logger name if present.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
NeverSampler never allows logging.
// Create a new NeverSampler
neversampler := NeverSampler{
}type NeverSampler struct {
}Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
NoopFormatter discards all output.
// Create a new NoopFormatter
noopformatter := NoopFormatter{
}type NoopFormatter struct {
}Format returns nil.
func (*NamedFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
OncePerSampler logs a message only once per duration.
// Create a new OncePerSampler
oncepersampler := OncePerSampler{
}type OncePerSampler struct {
}NewOncePerSampler creates a sampler that logs each message at most once per period.
func NewOncePerSampler(period time.Duration) *OncePerSamplerParameters:
period (time.Duration)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
Option configures a Logger.
// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Logger)WithAsync enables asynchronous logging.
func WithAsync(bufferSize int) OptionParameters:
bufferSize (int)Returns:
WithCaller enables caller information in logs.
func WithCaller() OptionParameters: None
Returns:
WithCallerDepth sets the caller stack depth.
func WithCallerDepth(depth int) OptionParameters:
depth (int)Returns:
WithFields adds default fields to all log entries.
func (*Builder) WithFields(fields ...Field) *BuilderParameters:
fields (...Field)Returns:
WithFormatter sets the log formatter.
func WithFormatter(f Formatter) OptionParameters:
f (Formatter)Returns:
WithHooks adds hooks to the logger.
func WithHooks(hooks ...Hook) OptionParameters:
hooks (...Hook)Returns:
WithLevel sets the minimum log level.
func WithLevel(level Level) OptionParameters:
level (Level)Returns:
WithNamedFormat wraps the current formatter to include logger names.
func WithNamedFormat() OptionParameters: None
Returns:
WithOutput sets the output writer.
func WithOutput(w io.Writer) OptionParameters:
w (io.Writer)Returns:
WithSampler sets a sampler for rate limiting logs.
func WithSampler(s Sampler) OptionParameters:
s (Sampler)Returns:
WithStackTrace enables stack traces for error and above.
func WithStackTrace() OptionParameters: None
Returns:
PrettyFormatter formats logs with colors and alignment for development.
// Create a new PrettyFormatter
prettyformatter := PrettyFormatter{
TimestampFormat: "example",
ShowCaller: true,
ShowTimestamp: true,
}type PrettyFormatter struct {
TimestampFormat string
ShowCaller bool
ShowTimestamp bool
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: "15:04:05.000" |
| ShowCaller | bool | ShowCaller shows caller information. |
| ShowTimestamp | bool | ShowTimestamp shows timestamps. |
Format formats an entry in a pretty, colorful format.
func (*NamedFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
RandomSampler samples a percentage of logs.
// Create a new RandomSampler
randomsampler := RandomSampler{
}type RandomSampler struct {
}NewRandomSampler creates a sampler that logs a percentage of entries. percentage should be between 0 and 100.
func NewRandomSampler(percentage int) *RandomSamplerParameters:
percentage (int)Returns:
Sample implements Sampler using a simple modulo for deterministic "random" sampling.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
RateSampler limits logs to a certain rate per message.
// Create a new RateSampler
ratesampler := RateSampler{
}type RateSampler struct {
}NewRateSampler creates a sampler that limits log rate per message. rate is the number of logs allowed per window. burst is the initial burst allowance.
func NewRateSampler(rate int, window time.Duration) *RateSamplerParameters:
rate (int)window (time.Duration)Returns:
Sample implements Sampler.
func (*NeverSampler) Sample(level Level, msg string) boolParameters:
level (Level)msg (string)Returns:
WithBurst sets the burst allowance.
func (*RateSampler) WithBurst(burst int) *RateSamplerParameters:
burst (int)Returns:
Sampler determines if a log entry should be emitted.
// Example implementation of Sampler
type MySampler struct {
// Add your fields here
}
func (m MySampler) Sample(param1 Level, param2 string) bool {
// Implement your logic here
return
}
type Sampler interface {
Sample(level Level, msg string) bool
}| Method | Description |
|---|
TextFormatter formats logs as text.
// Create a new TextFormatter
textformatter := TextFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
DisableColors: true,
DisableQuoting: true,
QuoteEmptyFields: true,
FullTimestamp: true,
PadLevelText: true,
FieldSeparator: "example",
KeyValueSeparator: "example",
}type TextFormatter struct {
TimestampFormat string
DisableTimestamp bool
DisableColors bool
DisableQuoting bool
QuoteEmptyFields bool
FullTimestamp bool
PadLevelText bool
FieldSeparator string
KeyValueSeparator string
}| Field | Type | Description |
|---|---|---|
| TimestampFormat | string | TimestampFormat is the format for timestamps. Default: "2006-01-02T15:04:05.000Z07:00" |
| DisableTimestamp | bool | DisableTimestamp disables timestamp output. |
| DisableColors | bool | DisableColors disables ANSI colors. |
| DisableQuoting | bool | DisableQuoting disables quoting of string values. |
| QuoteEmptyFields | bool | QuoteEmptyFields quotes empty field values. |
| FullTimestamp | bool | FullTimestamp shows full timestamp instead of relative time. |
| PadLevelText | bool | PadLevelText pads level text for alignment. |
| FieldSeparator | string | FieldSeparator is the separator between fields. Default: " " |
| KeyValueSeparator | string | KeyValueSeparator is the separator between key and value. Default: "=" |
Format formats an entry as text.
func (*NoopFormatter) Format(entry *Entry) ([]byte, error)Parameters:
entry (*Entry)Returns:
WriterHook writes entries to an io.Writer.
// Create a new WriterHook
writerhook := WriterHook{
}type WriterHook struct {
}NewWriterHook creates a hook that writes to an io.Writer.
func NewWriterHook(w io.Writer, formatter Formatter, levels ...Level) *WriterHookParameters:
w (io.Writer)formatter (Formatter)levels (...Level)Returns:
Fire implements Hook.
func (*FuncHook) Fire(entry *Entry)Parameters:
entry (*Entry)Returns: None
Levels implements Hook.
func (*FuncHook) Levels() []LevelParameters: None
Returns:
CtxDebug logs at debug level using the logger from context.
func CtxDebug(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxDebug
result := CtxDebug(/* parameters */)CtxError logs at error level using the logger from context.
func CtxError(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxError
result := CtxError(/* parameters */)CtxInfo logs at info level using the logger from context.
func CtxInfo(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxInfo
result := CtxInfo(/* parameters */)CtxTrace logs at trace level using the logger from context.
func CtxTrace(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxTrace
result := CtxTrace(/* parameters */)CtxWarn logs at warn level using the logger from context.
func CtxWarn(ctx context.Context, msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of CtxWarn
result := CtxWarn(/* parameters */)Debug logs at debug level using the default logger.
func (*Builder) Debug(msg string)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string |
Returns: None
Example:
// Example usage of Debug
result := Debug(/* parameters */)Debugf logs a formatted message at debug level.
func Debugf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Debugf
result := Debugf(/* parameters */)Error logs at error level using the default logger.
func Error(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Error
result := Error(/* parameters */)Errorf logs a formatted message at error level.
func Errorf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Errorf
result := Errorf(/* parameters */)Fatal logs at fatal level using the default logger and exits.
func (*Builder) Fatal(msg string)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string |
Returns: None
Example:
// Example usage of Fatal
result := Fatal(/* parameters */)Fatalf logs a formatted message at fatal level and exits.
func Fatalf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Fatalf
result := Fatalf(/* parameters */)Info logs at info level using the default logger.
func Info(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Info
result := Info(/* parameters */)Infof logs a formatted message at info level.
func Infof(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Infof
result := Infof(/* parameters */)Must logs and panics if error is not nil. Useful for initialization code. db := log.Must(sql.Open("postgres", dsn))
func Must(l *Logger, val T, err error) TParameters:
| Parameter | Type | Description |
|---|---|---|
l | *Logger | |
val | T | |
err | error |
Returns:
| Type | Description |
|---|---|
T |
Example:
// Example usage of Must
result := Must(/* parameters */)Panic logs at panic level using the default logger and panics.
func Panic(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Panic
result := Panic(/* parameters */)Panicf logs a formatted message at panic level and panics.
func Panicf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Panicf
result := Panicf(/* parameters */)Print logs a message at info level.
func Print(args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
args | ...any |
Returns: None
Example:
// Example usage of Print
result := Print(/* parameters */)Printf logs a formatted message at info level.
func Printf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Printf
result := Printf(/* parameters */)Println logs a message at info level.
func Println(args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
args | ...any |
Returns: None
Example:
// Example usage of Println
result := Println(/* parameters */)SetDefault sets the default logger.
func SetDefault(l *Logger)Parameters:
| Parameter | Type | Description |
|---|---|---|
l | *Logger |
Returns: None
Example:
// Example usage of SetDefault
result := SetDefault(/* parameters */)SetDefaultFormatter sets the default formatter.
func SetDefaultFormatter(f Formatter)Parameters:
| Parameter | Type | Description |
|---|---|---|
f | Formatter |
Returns: None
Example:
// Example usage of SetDefaultFormatter
result := SetDefaultFormatter(/* parameters */)SetDefaultLevel sets the default level.
func SetDefaultLevel(level Level)Parameters:
| Parameter | Type | Description |
|---|---|---|
level | Level |
Returns: None
Example:
// Example usage of SetDefaultLevel
result := SetDefaultLevel(/* parameters */)Trace logs at trace level using the default logger.
func Trace(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Trace
result := Trace(/* parameters */)Tracef logs a formatted message at trace level.
func Tracef(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Tracef
result := Tracef(/* parameters */)Warn logs at warn level using the default logger.
func Warn(msg string, fields ...Field)Parameters:
| Parameter | Type | Description |
|---|---|---|
msg | string | |
fields | ...Field |
Returns: None
Example:
// Example usage of Warn
result := Warn(/* parameters */)Warnf logs a formatted message at warn level.
func Warnf(format string, args ...any)Parameters:
| Parameter | Type | Description |
|---|---|---|
format | string | |
args | ...any |
Returns: None
Example:
// Example usage of Warnf
result := Warnf(/* parameters */)WithFields adds fields to the context that will be included in all logs.
func WithContextFields(ctx context.Context, fields ...Field) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
fields | ...Field |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithContextFields
result := WithContextFields(/* parameters */)WithLogger attaches a logger to the context.
func WithLogger(ctx context.Context, logger *Logger) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
logger | *Logger |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithLogger
result := WithLogger(/* parameters */)WithRequestID adds a request ID to the context.
func WithRequestID(ctx context.Context, requestID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
requestID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithRequestID
result := WithRequestID(/* parameters */)WithTraceID adds a trace ID to the context.
func WithTraceID(ctx context.Context, traceID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
traceID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithTraceID
result := WithTraceID(/* parameters */)WithUserID adds a user ID to the context.
func WithUserID(ctx context.Context, userID string) context.ContextParameters:
| Parameter | Type | Description |
|---|---|---|
ctx | context.Context | |
userID | string |
Returns:
| Type | Description |
|---|---|
context.Context |
Example:
// Example usage of WithUserID
result := WithUserID(/* parameters */)log := logs.New()
log.Info("server started", logs.Int("port", 8080))const RequestIDKey = "request_id"const TraceIDKey = "trace_id"const UserIDKey = "user_id"// Create a new AlwaysSampler
alwayssampler := AlwaysSampler{
}type AlwaysSampler struct {
}func (*NeverSampler) Sample(level Level, msg string) bool// Create a new Builder
builder := Builder{
}type Builder struct {
}func Bool(key string, value bool) Fieldfunc (*Builder) Debug(msg string)func (*Builder) Err(err error) *Builderfunc (*Builder) Error(msg string)func Fatal(msg string, fields ...Field)func Float64(key string, value float64) Fieldfunc Info(msg string, fields ...Field)func (*Builder) Int(key string, value int) *Builderfunc Int64(key string, value int64) Fieldfunc (*Builder) Log(level Level, msg string)func (*Builder) Msg(msg string)func (*Builder) Panic(msg string)func (*Builder) Send()func (*Builder) Str(key, value string) *Builderfunc (*Builder) Trace(msg string)func (*Builder) Uint(key string, value uint) *Builderfunc Uint64(key string, value uint64) Fieldfunc Warn(msg string, fields ...Field)func With(fields ...Field) *Loggerfunc (*Builder) WithContext(ctx context.Context) *Builderfunc (*Builder) WithError(err error) *Builderfunc (*Builder) WithField(f Field) *Builderfunc WithFields(fields ...Field) Option// Create a new CompositeSampler
compositesampler := CompositeSampler{
}type CompositeSampler struct {
}func NewCompositeSampler(samplers ...Sampler) *CompositeSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new CountSampler
countsampler := CountSampler{
}type CountSampler struct {
}func NewCountSampler(n int) *CountSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new Entry
entry := Entry{
Level: Level{},
Time: /* value */,
Message: "example",
Fields: [],
Caller: "example",
Stack: "example",
}type Entry struct {
Level Level
Time time.Time
Message string
Fields []Field
Caller string
Stack string
}func (*Entry) GetField(key string) (Field, bool)func (*Entry) GetString(key string) stringfunc (*Entry) HasField(key string) bool// Create a new ErrorBuilder
errorbuilder := ErrorBuilder{
}type ErrorBuilder struct {
}func (*ErrorBuilder) Debug(msg string)func (*ErrorBuilder) Error(msg string)func Fatal(msg string, fields ...Field)func Info(msg string, fields ...Field)func Trace(msg string, fields ...Field)func (*Builder) Warn(msg string)func With(fields ...Field) *Loggerfunc (*Builder) WithField(f Field) *Builderfunc WithFields(fields ...Field) Option// Create a new ErrorHook
errorhook := ErrorHook{
}type ErrorHook struct {
}func NewErrorHook(maxEntries int) *ErrorHookfunc (*ErrorHook) Clear()func (*ErrorHook) Errors() []Entryfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new Field
field := Field{
Key: "example",
Type: FieldType{},
Int: 42,
Uint: 42,
Float: 3.14,
String: "example",
Interface: any{},
}type Field struct {
Key string
Type FieldType
Int int64
Uint uint64
Float float64
String string
Interface any
}func Any(key string, value any) Fieldfunc (*Builder) Bool(key string, value bool) *Builderfunc Bytes(key string, value []byte) Fieldfunc Duration(key string, value time.Duration) Fieldfunc (*Builder) Err(err error) *Builderfunc ErrChain(err error) Fieldfunc ErrWithStack(err error) Fieldfunc FieldsFromContext(ctx context.Context) []Fieldfunc Float32(key string, value float32) Fieldfunc (*Builder) Float64(key string, value float64) *Builderfunc Int(key string, value int) Fieldfunc Int16(key string, value int16) Fieldfunc Int32(key string, value int32) Fieldfunc Int64(key string, value int64) Fieldfunc Int8(key string, value int8) Fieldfunc JSON(key string, value any) Fieldfunc NamedErr(key string, err error) Fieldfunc Namespace(key string) Fieldfunc Object(key string, v any) Fieldfunc Stack(key string) Fieldfunc String(key, value string) Fieldfunc Stringer(key string, value fmt.Stringer) Fieldfunc Strings(key string, values []string) Fieldfunc Struct(key string, v any) Fieldfunc StructFlat(v any) []Fieldfunc Time(key string, value time.Time) Fieldfunc Uint(key string, value uint) Fieldfunc Uint16(key string, value uint16) Fieldfunc Uint32(key string, value uint32) Fieldfunc (*Builder) Uint64(key string, value uint64) *Builderfunc Uint8(key string, value uint8) Fieldfunc V(key string, value any) Fieldfunc (Field) StringValue() stringfunc (Field) Value() any// Example usage of FieldType
var value FieldType
// Initialize with appropriate valuetype FieldType uint8// Create a new FileHook
filehook := FileHook{
}type FileHook struct {
*WriterHook
}func NewFileHook(path string, formatter Formatter, levels ...Level) (*FileHook, error)func (*Logger) Close() error// Create a new FilterHook
filterhook := FilterHook{
}type FilterHook struct {
}func NewFilterHook(hook Hook, filter func(*Entry) bool) *FilterHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new FirstNSampler
firstnsampler := FirstNSampler{
}type FirstNSampler struct {
}func NewFirstNSampler(n int) *FirstNSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Example implementation of Formatter
type MyFormatter struct {
// Add your fields here
}
func (m MyFormatter) Format(param1 *Entry) []byte {
// Implement your logic here
return
}
type Formatter interface {
Format(entry *Entry) ([]byte, error)
}// Create a new FuncHook
funchook := FuncHook{
}type FuncHook struct {
}func NewFuncHook(fn func(*Entry), levels ...Level) *FuncHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Example implementation of Hook
type MyHook struct {
// Add your fields here
}
func (m MyHook) Fire(param1 *Entry) {
// Implement your logic here
return
}
func (m MyHook) Levels() []Level {
// Implement your logic here
return
}
type Hook interface {
Fire(entry *Entry)
Levels() []Level
}// Create a new JSONFormatter
jsonformatter := JSONFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
TimestampKey: "example",
LevelKey: "example",
MessageKey: "example",
CallerKey: "example",
StackKey: "example",
PrettyPrint: true,
EscapeHTML: true,
}type JSONFormatter struct {
TimestampFormat string
DisableTimestamp bool
TimestampKey string
LevelKey string
MessageKey string
CallerKey string
StackKey string
PrettyPrint bool
EscapeHTML bool
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Example usage of Level
var value Level
// Initialize with appropriate valuetype Level intfunc AllLevels() []Levelfunc ParseLevel(s string) Levelfunc (Level) Color() stringfunc (Level) ShortString() stringfunc String(key, value string) Field// Create a new LevelHook
levelhook := LevelHook{
}type LevelHook struct {
}func NewLevelHook(hook Hook, levels ...Level) *LevelHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new LevelSampler
levelsampler := LevelSampler{
}type LevelSampler struct {
}func NewLevelSampler(fallback Sampler) *LevelSamplerfunc (*NeverSampler) Sample(level Level, msg string) boolfunc WithLevel(level Level) Option// Create a new Logger
logger := Logger{
}type Logger struct {
}func Component(name string) *Loggerfunc Default() *Loggerfunc LoggerFromContext(ctx context.Context) *Loggerfunc Named(name string) *Loggerfunc New(opts ...Option) *Loggerfunc With(fields ...Field) *Loggerfunc (*Logger) AddHook(hook Hook)func (*Logger) Build() *Builderfunc (*Logger) CheckErr(err error, msg string, fields ...Field) boolfunc (*Logger) Close() errorfunc Component(name string) *Loggerfunc (*Logger) Ctx(ctx context.Context) *Builderfunc (*ErrorBuilder) Debug(msg string)func (*Logger) DebugContext(ctx context.Context, msg string, fields ...Field)func Debugf(format string, args ...any)func (*Logger) DebugfContext(ctx context.Context, format string, args ...any)func Error(msg string, fields ...Field)func (*Logger) ErrorContext(ctx context.Context, msg string, fields ...Field)func Errorf(format string, args ...any)func (*Logger) ErrorfContext(ctx context.Context, format string, args ...any)func (*Logger) F(keyvals ...any) *Builderfunc (*Builder) Fatal(msg string)func Fatalf(format string, args ...any)func (*Logger) FullName() stringfunc (*Logger) GetLevel() Levelfunc (*Logger) GetName() stringfunc (*Logger) IfErr(err error) *ErrorBuilderfunc Info(msg string, fields ...Field)func (*Logger) InfoContext(ctx context.Context, msg string, fields ...Field)func Infof(format string, args ...any)func (*Logger) InfofContext(ctx context.Context, format string, args ...any)func (*Logger) IsEnabled(level Level) boolfunc (*Logger) Log(level Level, msg string, fields ...Field)func (*Logger) LogContext(ctx context.Context, level Level, msg string, fields ...Field)func (*Logger) LogErr(err error, msg string, fields ...Field)func (*Logger) Module(name string) *Loggerfunc (*Logger) MustErr(err error, msg string, fields ...Field)func (*Logger) NameParts() []stringfunc Named(name string) *Loggerfunc (*Builder) Panic(msg string)func Panicf(format string, args ...any)func Print(args ...any)func Printf(format string, args ...any)func Println(args ...any)func (*Logger) Service(name string) *Loggerfunc (*Logger) SetFormatter(f Formatter)func (*Logger) SetLevel(level Level)func (*Logger) SetOutput(w io.Writer)func Trace(msg string, fields ...Field)func (*Logger) TraceContext(ctx context.Context, msg string, fields ...Field)func Tracef(format string, args ...any)func (*Logger) TracefContext(ctx context.Context, format string, args ...any)func Warn(msg string, fields ...Field)func (*Logger) WarnContext(ctx context.Context, msg string, fields ...Field)func Warnf(format string, args ...any)func (*Logger) WarnfContext(ctx context.Context, format string, args ...any)func (*Builder) With(key string, value any) *Builderfunc (*Logger) WrapErr(err error, msg string, fields ...Field) errorfunc (*Logger) WrapErrLevel(level Level, err error, msg string, fields ...Field) error// Create a new MetricsHook
metricshook := MetricsHook{
}type MetricsHook struct {
}func NewMetricsHook() *MetricsHookfunc (*MetricsHook) Count(level Level) uint64func (*MetricsHook) Counts() map[Level]uint64func (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Levelfunc (*MetricsHook) Reset()// Create a new NamedFormatter
namedformatter := NamedFormatter{
Inner: Formatter{},
Separator: "example",
Brackets: "example",
}type NamedFormatter struct {
Inner Formatter
Separator string
Brackets string
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Create a new NeverSampler
neversampler := NeverSampler{
}type NeverSampler struct {
}func (*NeverSampler) Sample(level Level, msg string) bool// Create a new NoopFormatter
noopformatter := NoopFormatter{
}type NoopFormatter struct {
}func (*NamedFormatter) Format(entry *Entry) ([]byte, error)// Create a new OncePerSampler
oncepersampler := OncePerSampler{
}type OncePerSampler struct {
}func NewOncePerSampler(period time.Duration) *OncePerSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Logger)func WithAsync(bufferSize int) Optionfunc WithCaller() Optionfunc WithCallerDepth(depth int) Optionfunc (*Builder) WithFields(fields ...Field) *Builderfunc WithFormatter(f Formatter) Optionfunc WithHooks(hooks ...Hook) Optionfunc WithLevel(level Level) Optionfunc WithNamedFormat() Optionfunc WithOutput(w io.Writer) Optionfunc WithSampler(s Sampler) Optionfunc WithStackTrace() Option// Create a new PrettyFormatter
prettyformatter := PrettyFormatter{
TimestampFormat: "example",
ShowCaller: true,
ShowTimestamp: true,
}type PrettyFormatter struct {
TimestampFormat string
ShowCaller bool
ShowTimestamp bool
}func (*NamedFormatter) Format(entry *Entry) ([]byte, error)// Create a new RandomSampler
randomsampler := RandomSampler{
}type RandomSampler struct {
}func NewRandomSampler(percentage int) *RandomSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new RateSampler
ratesampler := RateSampler{
}type RateSampler struct {
}func NewRateSampler(rate int, window time.Duration) *RateSamplerfunc (*NeverSampler) Sample(level Level, msg string) boolfunc (*RateSampler) WithBurst(burst int) *RateSampler// Example implementation of Sampler
type MySampler struct {
// Add your fields here
}
func (m MySampler) Sample(param1 Level, param2 string) bool {
// Implement your logic here
return
}
type Sampler interface {
Sample(level Level, msg string) bool
}// Create a new TextFormatter
textformatter := TextFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
DisableColors: true,
DisableQuoting: true,
QuoteEmptyFields: true,
FullTimestamp: true,
PadLevelText: true,
FieldSeparator: "example",
KeyValueSeparator: "example",
}type TextFormatter struct {
TimestampFormat string
DisableTimestamp bool
DisableColors bool
DisableQuoting bool
QuoteEmptyFields bool
FullTimestamp bool
PadLevelText bool
FieldSeparator string
KeyValueSeparator string
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Create a new WriterHook
writerhook := WriterHook{
}type WriterHook struct {
}func NewWriterHook(w io.Writer, formatter Formatter, levels ...Level) *WriterHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Levelfunc CtxDebug(ctx context.Context, msg string, fields ...Field)// Example usage of CtxDebug
result := CtxDebug(/* parameters */)func CtxError(ctx context.Context, msg string, fields ...Field)// Example usage of CtxError
result := CtxError(/* parameters */)func CtxInfo(ctx context.Context, msg string, fields ...Field)// Example usage of CtxInfo
result := CtxInfo(/* parameters */)func CtxTrace(ctx context.Context, msg string, fields ...Field)// Example usage of CtxTrace
result := CtxTrace(/* parameters */)func CtxWarn(ctx context.Context, msg string, fields ...Field)// Example usage of CtxWarn
result := CtxWarn(/* parameters */)func (*Builder) Debug(msg string)// Example usage of Debug
result := Debug(/* parameters */)func Debugf(format string, args ...any)// Example usage of Debugf
result := Debugf(/* parameters */)func Error(msg string, fields ...Field)// Example usage of Error
result := Error(/* parameters */)func Errorf(format string, args ...any)// Example usage of Errorf
result := Errorf(/* parameters */)func (*Builder) Fatal(msg string)// Example usage of Fatal
result := Fatal(/* parameters */)func Fatalf(format string, args ...any)// Example usage of Fatalf
result := Fatalf(/* parameters */)func Info(msg string, fields ...Field)// Example usage of Info
result := Info(/* parameters */)func Infof(format string, args ...any)// Example usage of Infof
result := Infof(/* parameters */)func Must(l *Logger, val T, err error) T// Example usage of Must
result := Must(/* parameters */)func Panic(msg string, fields ...Field)// Example usage of Panic
result := Panic(/* parameters */)func Panicf(format string, args ...any)// Example usage of Panicf
result := Panicf(/* parameters */)func Print(args ...any)// Example usage of Print
result := Print(/* parameters */)func Printf(format string, args ...any)// Example usage of Printf
result := Printf(/* parameters */)func Println(args ...any)// Example usage of Println
result := Println(/* parameters */)func SetDefault(l *Logger)// Example usage of SetDefault
result := SetDefault(/* parameters */)func SetDefaultFormatter(f Formatter)// Example usage of SetDefaultFormatter
result := SetDefaultFormatter(/* parameters */)func SetDefaultLevel(level Level)// Example usage of SetDefaultLevel
result := SetDefaultLevel(/* parameters */)func Trace(msg string, fields ...Field)// Example usage of Trace
result := Trace(/* parameters */)func Tracef(format string, args ...any)// Example usage of Tracef
result := Tracef(/* parameters */)func Warn(msg string, fields ...Field)// Example usage of Warn
result := Warn(/* parameters */)func Warnf(format string, args ...any)// Example usage of Warnf
result := Warnf(/* parameters */)func WithContextFields(ctx context.Context, fields ...Field) context.Context// Example usage of WithContextFields
result := WithContextFields(/* parameters */)func WithLogger(ctx context.Context, logger *Logger) context.Context// Example usage of WithLogger
result := WithLogger(/* parameters */)func WithRequestID(ctx context.Context, requestID string) context.Context// Example usage of WithRequestID
result := WithRequestID(/* parameters */)func WithTraceID(ctx context.Context, traceID string) context.Context// Example usage of WithTraceID
result := WithTraceID(/* parameters */)func WithUserID(ctx context.Context, userID string) context.Context// Example usage of WithUserID
result := WithUserID(/* parameters */)log := logs.New()
log.Info("server started", logs.Int("port", 8080))const RequestIDKey = "request_id"const TraceIDKey = "trace_id"const UserIDKey = "user_id"// Create a new AlwaysSampler
alwayssampler := AlwaysSampler{
}type AlwaysSampler struct {
}func (*NeverSampler) Sample(level Level, msg string) bool// Create a new Builder
builder := Builder{
}type Builder struct {
}func Bool(key string, value bool) Fieldfunc (*Builder) Debug(msg string)func (*Builder) Err(err error) *Builderfunc (*Builder) Error(msg string)func Fatal(msg string, fields ...Field)func Float64(key string, value float64) Fieldfunc Info(msg string, fields ...Field)func (*Builder) Int(key string, value int) *Builderfunc Int64(key string, value int64) Fieldfunc (*Builder) Log(level Level, msg string)func (*Builder) Msg(msg string)func (*Builder) Panic(msg string)func (*Builder) Send()func (*Builder) Str(key, value string) *Builderfunc (*Builder) Trace(msg string)func (*Builder) Uint(key string, value uint) *Builderfunc Uint64(key string, value uint64) Fieldfunc Warn(msg string, fields ...Field)func With(fields ...Field) *Loggerfunc (*Builder) WithContext(ctx context.Context) *Builderfunc (*Builder) WithError(err error) *Builderfunc (*Builder) WithField(f Field) *Builderfunc WithFields(fields ...Field) Option// Create a new CompositeSampler
compositesampler := CompositeSampler{
}type CompositeSampler struct {
}func NewCompositeSampler(samplers ...Sampler) *CompositeSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new CountSampler
countsampler := CountSampler{
}type CountSampler struct {
}func NewCountSampler(n int) *CountSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new Entry
entry := Entry{
Level: Level{},
Time: /* value */,
Message: "example",
Fields: [],
Caller: "example",
Stack: "example",
}type Entry struct {
Level Level
Time time.Time
Message string
Fields []Field
Caller string
Stack string
}func (*Entry) GetField(key string) (Field, bool)func (*Entry) GetString(key string) stringfunc (*Entry) HasField(key string) bool// Create a new ErrorBuilder
errorbuilder := ErrorBuilder{
}type ErrorBuilder struct {
}func (*ErrorBuilder) Debug(msg string)func (*ErrorBuilder) Error(msg string)func Fatal(msg string, fields ...Field)func Info(msg string, fields ...Field)func Trace(msg string, fields ...Field)func (*Builder) Warn(msg string)func With(fields ...Field) *Loggerfunc (*Builder) WithField(f Field) *Builderfunc WithFields(fields ...Field) Option// Create a new ErrorHook
errorhook := ErrorHook{
}type ErrorHook struct {
}func NewErrorHook(maxEntries int) *ErrorHookfunc (*ErrorHook) Clear()func (*ErrorHook) Errors() []Entryfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new Field
field := Field{
Key: "example",
Type: FieldType{},
Int: 42,
Uint: 42,
Float: 3.14,
String: "example",
Interface: any{},
}type Field struct {
Key string
Type FieldType
Int int64
Uint uint64
Float float64
String string
Interface any
}func Any(key string, value any) Fieldfunc (*Builder) Bool(key string, value bool) *Builderfunc Bytes(key string, value []byte) Fieldfunc Duration(key string, value time.Duration) Fieldfunc (*Builder) Err(err error) *Builderfunc ErrChain(err error) Fieldfunc ErrWithStack(err error) Fieldfunc FieldsFromContext(ctx context.Context) []Fieldfunc Float32(key string, value float32) Fieldfunc (*Builder) Float64(key string, value float64) *Builderfunc Int(key string, value int) Fieldfunc Int16(key string, value int16) Fieldfunc Int32(key string, value int32) Fieldfunc Int64(key string, value int64) Fieldfunc Int8(key string, value int8) Fieldfunc JSON(key string, value any) Fieldfunc NamedErr(key string, err error) Fieldfunc Namespace(key string) Fieldfunc Object(key string, v any) Fieldfunc Stack(key string) Fieldfunc String(key, value string) Fieldfunc Stringer(key string, value fmt.Stringer) Fieldfunc Strings(key string, values []string) Fieldfunc Struct(key string, v any) Fieldfunc StructFlat(v any) []Fieldfunc Time(key string, value time.Time) Fieldfunc Uint(key string, value uint) Fieldfunc Uint16(key string, value uint16) Fieldfunc Uint32(key string, value uint32) Fieldfunc (*Builder) Uint64(key string, value uint64) *Builderfunc Uint8(key string, value uint8) Fieldfunc V(key string, value any) Fieldfunc (Field) StringValue() stringfunc (Field) Value() any// Example usage of FieldType
var value FieldType
// Initialize with appropriate valuetype FieldType uint8// Create a new FileHook
filehook := FileHook{
}type FileHook struct {
*WriterHook
}func NewFileHook(path string, formatter Formatter, levels ...Level) (*FileHook, error)func (*Logger) Close() error// Create a new FilterHook
filterhook := FilterHook{
}type FilterHook struct {
}func NewFilterHook(hook Hook, filter func(*Entry) bool) *FilterHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new FirstNSampler
firstnsampler := FirstNSampler{
}type FirstNSampler struct {
}func NewFirstNSampler(n int) *FirstNSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Example implementation of Formatter
type MyFormatter struct {
// Add your fields here
}
func (m MyFormatter) Format(param1 *Entry) []byte {
// Implement your logic here
return
}
type Formatter interface {
Format(entry *Entry) ([]byte, error)
}// Create a new FuncHook
funchook := FuncHook{
}type FuncHook struct {
}func NewFuncHook(fn func(*Entry), levels ...Level) *FuncHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Example implementation of Hook
type MyHook struct {
// Add your fields here
}
func (m MyHook) Fire(param1 *Entry) {
// Implement your logic here
return
}
func (m MyHook) Levels() []Level {
// Implement your logic here
return
}
type Hook interface {
Fire(entry *Entry)
Levels() []Level
}// Create a new JSONFormatter
jsonformatter := JSONFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
TimestampKey: "example",
LevelKey: "example",
MessageKey: "example",
CallerKey: "example",
StackKey: "example",
PrettyPrint: true,
EscapeHTML: true,
}type JSONFormatter struct {
TimestampFormat string
DisableTimestamp bool
TimestampKey string
LevelKey string
MessageKey string
CallerKey string
StackKey string
PrettyPrint bool
EscapeHTML bool
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Example usage of Level
var value Level
// Initialize with appropriate valuetype Level intfunc AllLevels() []Levelfunc ParseLevel(s string) Levelfunc (Level) Color() stringfunc (Level) ShortString() stringfunc String(key, value string) Field// Create a new LevelHook
levelhook := LevelHook{
}type LevelHook struct {
}func NewLevelHook(hook Hook, levels ...Level) *LevelHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Level// Create a new LevelSampler
levelsampler := LevelSampler{
}type LevelSampler struct {
}func NewLevelSampler(fallback Sampler) *LevelSamplerfunc (*NeverSampler) Sample(level Level, msg string) boolfunc WithLevel(level Level) Option// Create a new Logger
logger := Logger{
}type Logger struct {
}func Component(name string) *Loggerfunc Default() *Loggerfunc LoggerFromContext(ctx context.Context) *Loggerfunc Named(name string) *Loggerfunc New(opts ...Option) *Loggerfunc With(fields ...Field) *Loggerfunc (*Logger) AddHook(hook Hook)func (*Logger) Build() *Builderfunc (*Logger) CheckErr(err error, msg string, fields ...Field) boolfunc (*Logger) Close() errorfunc Component(name string) *Loggerfunc (*Logger) Ctx(ctx context.Context) *Builderfunc (*ErrorBuilder) Debug(msg string)func (*Logger) DebugContext(ctx context.Context, msg string, fields ...Field)func Debugf(format string, args ...any)func (*Logger) DebugfContext(ctx context.Context, format string, args ...any)func Error(msg string, fields ...Field)func (*Logger) ErrorContext(ctx context.Context, msg string, fields ...Field)func Errorf(format string, args ...any)func (*Logger) ErrorfContext(ctx context.Context, format string, args ...any)func (*Logger) F(keyvals ...any) *Builderfunc (*Builder) Fatal(msg string)func Fatalf(format string, args ...any)func (*Logger) FullName() stringfunc (*Logger) GetLevel() Levelfunc (*Logger) GetName() stringfunc (*Logger) IfErr(err error) *ErrorBuilderfunc Info(msg string, fields ...Field)func (*Logger) InfoContext(ctx context.Context, msg string, fields ...Field)func Infof(format string, args ...any)func (*Logger) InfofContext(ctx context.Context, format string, args ...any)func (*Logger) IsEnabled(level Level) boolfunc (*Logger) Log(level Level, msg string, fields ...Field)func (*Logger) LogContext(ctx context.Context, level Level, msg string, fields ...Field)func (*Logger) LogErr(err error, msg string, fields ...Field)func (*Logger) Module(name string) *Loggerfunc (*Logger) MustErr(err error, msg string, fields ...Field)func (*Logger) NameParts() []stringfunc Named(name string) *Loggerfunc (*Builder) Panic(msg string)func Panicf(format string, args ...any)func Print(args ...any)func Printf(format string, args ...any)func Println(args ...any)func (*Logger) Service(name string) *Loggerfunc (*Logger) SetFormatter(f Formatter)func (*Logger) SetLevel(level Level)func (*Logger) SetOutput(w io.Writer)func Trace(msg string, fields ...Field)func (*Logger) TraceContext(ctx context.Context, msg string, fields ...Field)func Tracef(format string, args ...any)func (*Logger) TracefContext(ctx context.Context, format string, args ...any)func Warn(msg string, fields ...Field)func (*Logger) WarnContext(ctx context.Context, msg string, fields ...Field)func Warnf(format string, args ...any)func (*Logger) WarnfContext(ctx context.Context, format string, args ...any)func (*Builder) With(key string, value any) *Builderfunc (*Logger) WrapErr(err error, msg string, fields ...Field) errorfunc (*Logger) WrapErrLevel(level Level, err error, msg string, fields ...Field) error// Create a new MetricsHook
metricshook := MetricsHook{
}type MetricsHook struct {
}func NewMetricsHook() *MetricsHookfunc (*MetricsHook) Count(level Level) uint64func (*MetricsHook) Counts() map[Level]uint64func (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Levelfunc (*MetricsHook) Reset()// Create a new NamedFormatter
namedformatter := NamedFormatter{
Inner: Formatter{},
Separator: "example",
Brackets: "example",
}type NamedFormatter struct {
Inner Formatter
Separator string
Brackets string
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Create a new NeverSampler
neversampler := NeverSampler{
}type NeverSampler struct {
}func (*NeverSampler) Sample(level Level, msg string) bool// Create a new NoopFormatter
noopformatter := NoopFormatter{
}type NoopFormatter struct {
}func (*NamedFormatter) Format(entry *Entry) ([]byte, error)// Create a new OncePerSampler
oncepersampler := OncePerSampler{
}type OncePerSampler struct {
}func NewOncePerSampler(period time.Duration) *OncePerSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Example usage of Option
var value Option
// Initialize with appropriate valuetype Option func(*Logger)func WithAsync(bufferSize int) Optionfunc WithCaller() Optionfunc WithCallerDepth(depth int) Optionfunc (*Builder) WithFields(fields ...Field) *Builderfunc WithFormatter(f Formatter) Optionfunc WithHooks(hooks ...Hook) Optionfunc WithLevel(level Level) Optionfunc WithNamedFormat() Optionfunc WithOutput(w io.Writer) Optionfunc WithSampler(s Sampler) Optionfunc WithStackTrace() Option// Create a new PrettyFormatter
prettyformatter := PrettyFormatter{
TimestampFormat: "example",
ShowCaller: true,
ShowTimestamp: true,
}type PrettyFormatter struct {
TimestampFormat string
ShowCaller bool
ShowTimestamp bool
}func (*NamedFormatter) Format(entry *Entry) ([]byte, error)// Create a new RandomSampler
randomsampler := RandomSampler{
}type RandomSampler struct {
}func NewRandomSampler(percentage int) *RandomSamplerfunc (*NeverSampler) Sample(level Level, msg string) bool// Create a new RateSampler
ratesampler := RateSampler{
}type RateSampler struct {
}func NewRateSampler(rate int, window time.Duration) *RateSamplerfunc (*NeverSampler) Sample(level Level, msg string) boolfunc (*RateSampler) WithBurst(burst int) *RateSampler// Example implementation of Sampler
type MySampler struct {
// Add your fields here
}
func (m MySampler) Sample(param1 Level, param2 string) bool {
// Implement your logic here
return
}
type Sampler interface {
Sample(level Level, msg string) bool
}// Create a new TextFormatter
textformatter := TextFormatter{
TimestampFormat: "example",
DisableTimestamp: true,
DisableColors: true,
DisableQuoting: true,
QuoteEmptyFields: true,
FullTimestamp: true,
PadLevelText: true,
FieldSeparator: "example",
KeyValueSeparator: "example",
}type TextFormatter struct {
TimestampFormat string
DisableTimestamp bool
DisableColors bool
DisableQuoting bool
QuoteEmptyFields bool
FullTimestamp bool
PadLevelText bool
FieldSeparator string
KeyValueSeparator string
}func (*NoopFormatter) Format(entry *Entry) ([]byte, error)// Create a new WriterHook
writerhook := WriterHook{
}type WriterHook struct {
}func NewWriterHook(w io.Writer, formatter Formatter, levels ...Level) *WriterHookfunc (*FuncHook) Fire(entry *Entry)func (*FuncHook) Levels() []Levelfunc CtxDebug(ctx context.Context, msg string, fields ...Field)// Example usage of CtxDebug
result := CtxDebug(/* parameters */)func CtxError(ctx context.Context, msg string, fields ...Field)// Example usage of CtxError
result := CtxError(/* parameters */)func CtxInfo(ctx context.Context, msg string, fields ...Field)// Example usage of CtxInfo
result := CtxInfo(/* parameters */)func CtxTrace(ctx context.Context, msg string, fields ...Field)// Example usage of CtxTrace
result := CtxTrace(/* parameters */)func CtxWarn(ctx context.Context, msg string, fields ...Field)// Example usage of CtxWarn
result := CtxWarn(/* parameters */)func (*Builder) Debug(msg string)// Example usage of Debug
result := Debug(/* parameters */)func Debugf(format string, args ...any)// Example usage of Debugf
result := Debugf(/* parameters */)func Error(msg string, fields ...Field)// Example usage of Error
result := Error(/* parameters */)func Errorf(format string, args ...any)// Example usage of Errorf
result := Errorf(/* parameters */)func (*Builder) Fatal(msg string)// Example usage of Fatal
result := Fatal(/* parameters */)func Fatalf(format string, args ...any)// Example usage of Fatalf
result := Fatalf(/* parameters */)func Info(msg string, fields ...Field)// Example usage of Info
result := Info(/* parameters */)func Infof(format string, args ...any)// Example usage of Infof
result := Infof(/* parameters */)func Must(l *Logger, val T, err error) T// Example usage of Must
result := Must(/* parameters */)func Panic(msg string, fields ...Field)// Example usage of Panic
result := Panic(/* parameters */)func Panicf(format string, args ...any)// Example usage of Panicf
result := Panicf(/* parameters */)func Print(args ...any)// Example usage of Print
result := Print(/* parameters */)func Printf(format string, args ...any)// Example usage of Printf
result := Printf(/* parameters */)func Println(args ...any)// Example usage of Println
result := Println(/* parameters */)func SetDefault(l *Logger)// Example usage of SetDefault
result := SetDefault(/* parameters */)func SetDefaultFormatter(f Formatter)// Example usage of SetDefaultFormatter
result := SetDefaultFormatter(/* parameters */)func SetDefaultLevel(level Level)// Example usage of SetDefaultLevel
result := SetDefaultLevel(/* parameters */)func Trace(msg string, fields ...Field)// Example usage of Trace
result := Trace(/* parameters */)func Tracef(format string, args ...any)// Example usage of Tracef
result := Tracef(/* parameters */)func Warn(msg string, fields ...Field)// Example usage of Warn
result := Warn(/* parameters */)func Warnf(format string, args ...any)// Example usage of Warnf
result := Warnf(/* parameters */)func WithContextFields(ctx context.Context, fields ...Field) context.Context// Example usage of WithContextFields
result := WithContextFields(/* parameters */)func WithLogger(ctx context.Context, logger *Logger) context.Context// Example usage of WithLogger
result := WithLogger(/* parameters */)func WithRequestID(ctx context.Context, requestID string) context.Context// Example usage of WithRequestID
result := WithRequestID(/* parameters */)func WithTraceID(ctx context.Context, traceID string) context.Context// Example usage of WithTraceID
result := WithTraceID(/* parameters */)func WithUserID(ctx context.Context, userID string) context.Context// Example usage of WithUserID
result := WithUserID(/* parameters */)