Skip to content

Logger ​

Logger is the core type of DD, providing thread-safe logging functionality. It implements every method of the LogProvider interface, plus a few extension methods beyond the interface.

Creation ​

go
// Via New
logger, _ := dd.New(dd.DefaultConfig())
go
// Create with custom config
logger, _ := dd.New(dd.Config{
    Level: dd.LevelInfo,
    Targets: []dd.OutputTarget{
        dd.ConsoleOutput(),
        dd.FileOutput("logs/app.log"),
    },
})

Logging Methods ​

Basic Logs ​

MethodSignatureDescription
Debug(args ...any)Debug-level log
Info(args ...any)Info-level log
Warn(args ...any)Warn-level log
Error(args ...any)Error-level log
Fatal(args ...any)Fatal-level log (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)
Log(level LogLevel, args ...any)Specified-level log

Formatted Logs ​

MethodSignatureDescription
Debugf(format string, args ...any)Formatted Debug
Infof(format string, args ...any)Formatted Info
Warnf(format string, args ...any)Formatted Warn
Errorf(format string, args ...any)Formatted Error
Fatalf(format string, args ...any)Formatted Fatal (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)
Logf(level LogLevel, format string, args ...any)Formatted, specified level

Structured Logs ​

MethodSignatureDescription
DebugWith(msg string, fields ...Field)Structured Debug
InfoWith(msg string, fields ...Field)Structured Info
WarnWith(msg string, fields ...Field)Structured Warn
ErrorWith(msg string, fields ...Field)Structured Error
FatalWith(msg string, fields ...Field)Structured Fatal (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)
LogWith(level LogLevel, msg string, fields ...Field)Structured, specified level
go
logger.InfoWith("request completed",
    dd.String("method", "GET"),
    dd.Int("status", 200),
    dd.Duration("elapsed", 100*time.Millisecond),
)

Level Management ​

MethodSignatureDescription
GetLevel() LogLevelGet the current log level
SetLevel(level LogLevel) errorSet the log level
IsLevelEnabled(level LogLevel) boolCheck whether the specified level is enabled
IsDebugEnabled() boolCheck whether Debug is enabled
IsInfoEnabled() boolCheck whether Info is enabled
IsWarnEnabled() boolCheck whether Warn is enabled
IsErrorEnabled() boolCheck whether Error is enabled
IsFatalEnabled() boolCheck whether Fatal is enabled
SetLevelResolver(resolver LevelResolver)Set a dynamic level resolver (nil disables it; overrides Level while active)
GetLevelResolver() LevelResolverGet the dynamic level resolver
go
level := logger.GetLevel()                    // Get current level
_ = logger.SetLevel(dd.LevelDebug)            // Set level
enabled := logger.IsLevelEnabled(dd.LevelInfo) // Check level

// Shortcut checks
logger.IsDebugEnabled()
logger.IsInfoEnabled()
logger.IsWarnEnabled()
logger.IsErrorEnabled()
logger.IsFatalEnabled()

// Dynamic level resolver
logger.SetLevelResolver(func(ctx context.Context) dd.LogLevel {
    if isDebug {
        return dd.LevelDebug
    }
    return dd.LevelInfo
})
resolver := logger.GetLevelResolver()

Field Chaining ​

MethodSignatureDescription
WithFields(fields ...Field) *LoggerEntryCreate a LoggerEntry with preset fields
WithField(key string, value any) *LoggerEntryCreate an entry with a single preset field (equivalent to WithFields with one field)
go
// Preset fields, returns a LoggerEntry
entry := logger.WithFields(
    dd.String("service", "api"),
    dd.Int("version", 2),
)

// Single field (equivalent to WithFields with one field)
entry2 := logger.WithField("env", "prod")

Output Target Management ​

MethodSignatureDescription
AddWriter(writer io.Writer) errorAdd an output Writer (more than 100 total returns ErrMaxWritersExceeded)
RemoveWriter(writer io.Writer) errorRemove an output Writer (not found returns ErrWriterNotFound)
WriterCount() intGet the Writer count
SetWriteErrorHandler(handler WriteErrorHandler)Set the write-error callback
go
// Add a Writer
_ = logger.AddWriter(os.Stderr)

// Remove a Writer
_ = logger.RemoveWriter(os.Stderr)

// Get the Writer count
count := logger.WriterCount()

// Set the write-error handler
logger.SetWriteErrorHandler(func(w io.Writer, err error) {
    fmt.Fprintf(os.Stderr, "write failed: %v\n", err)
})

Context Integration ​

MethodSignatureDescription
AddContextExtractor(extractor ContextExtractor) errorAppend a context extractor
SetContextExtractors(extractors ...ContextExtractor) errorReplace all context extractors
GetContextExtractors() []ContextExtractorGet the current context extractors
go
// Add a context extractor
_ = logger.AddContextExtractor(func(ctx context.Context) []dd.Field {
    return []dd.Field{
        dd.String("trace_id", dd.GetTraceID(ctx)),
    }
})

// Replace all extractors
_ = logger.SetContextExtractors(extractor1, extractor2)

// Get the current extractors
extractors := logger.GetContextExtractors()

Hook Management ​

MethodSignatureDescription
AddHook(event HookEvent, hook Hook) errorRegister a single hook (see Hooks)
SetHooks(registry *HookRegistry) errorReplace the entire hook registry
GetHooks() *HookRegistryGet the current hook registry
go
// Register a hook
_ = logger.AddHook(dd.HookBeforeLog, func(ctx context.Context, hc *dd.HookContext) error {
    // Pre-log processing
    return nil
})

// Replace the hook registry
_ = logger.SetHooks(registry)

// Get the hook registry
hooks := logger.GetHooks()

Sampling Control ​

MethodSignatureDescription
SetSampling(config *SamplingConfig)Enable/disable sampling at runtime (pass nil to disable; the config is copied, so mutating the argument does not affect the logger)
GetSampling() *SamplingConfigGet a copy of the sampling config (nil when sampling is not enabled)
go
// Set sampling config
logger.SetSampling(&dd.SamplingConfig{
    // Sampling parameters
})

// Get sampling config
cfg := logger.GetSampling()

Security Configuration ​

MethodSignatureDescription
SetSecurityConfig(config *SecurityConfig)Atomically replace the security config at runtime (cloned internally; see Security Filtering)
GetSecurityConfig() *SecurityConfigGet the current security config
go
// Set security config
logger.SetSecurityConfig(dd.DefaultSecurityConfig())

// Get security config
sec := logger.GetSecurityConfig()

Field Validation ​

MethodSignatureDescription
SetFieldValidation(config *FieldValidationConfig)Set the field-validation config
GetFieldValidation() *FieldValidationConfigGet the field-validation config
go
// Set field validation
logger.SetFieldValidation(dd.StrictSnakeCaseConfig())

// Get validation config
validation := logger.GetFieldValidation()

Lifecycle ​

MethodSignatureDescription
Flush() errorFlush Writers that implement Flusher
Close() errorClose the logger: triggers OnClose hooks, waits for filter goroutines, flushes then closes all Writers (CAS-guarded; safe to call repeatedly)
Shutdown(ctx context.Context) errorGraceful close with timeout (recommended in production): marks closed → triggers OnClose hooks → waits for in-flight operations → flushes and closes all Writers within the timeout; on timeout returns context.DeadlineExceeded while teardown continues in the background without leaking Writers
IsClosed() boolCheck whether the logger is closed
WaitForFilterGoroutines(timeout time.Duration) boolWait for in-flight security-filter goroutines (returns false on timeout)
ActiveFilterGoroutines() int32Number of currently active filter goroutines
go
// Flush buffers
_ = logger.Flush()

// Close the logger
_ = logger.Close()

// Graceful shutdown (with timeout)
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
_ = logger.Shutdown(ctx)

// Check whether closed
closed := logger.IsClosed()

// Wait for filter goroutines to finish
ok := logger.WaitForFilterGoroutines(3 * time.Second)
active := logger.ActiveFilterGoroutines()

Debug Output ​

MethodSignatureDescription
Print(args ...any)Output to the configured Writer (LevelInfo, subject to security filtering)
Println(args ...any)Same behavior as Print (the underlying Log() already appends a newline)
Printf(format string, args ...any)Formatted output (LevelInfo, subject to security filtering)
JSON(data ...any)Compact-JSON output to stdout (includes caller info; does not go through security filtering)
JSONF(format string, args ...any)Formatted compact-JSON output to stdout (includes caller info; does not go through security filtering)
Text(data ...any)Pretty-printed output to stdout (no caller info; does not go through security filtering)
Textf(format string, args ...any)Formatted text output to stdout (no caller info; does not go through security filtering)

Next Steps ​