Skip to content

Package Functions ​

DD provides a rich set of package-level functions callable directly via the dd. prefix. Logging functions execute through the global logger (Default()); the exception is the debug-output functions JSON/JSONF/Text/Textf/Exit/Exitf, which bypass the output targets configured in Config.Targets, write directly to os.Stdout, and do not go through security filtering.

Logger Creation ​

New ​

go
func New(cfg ...Config) (*Logger, error)

Creates a new Logger instance. Uses default settings when no config is provided.

go
// Default config
logger, _ := dd.New()

// Custom config
logger, _ := dd.New(dd.DefaultConfig())

// Note: only 0 or 1 config is accepted; passing multiple returns an error
// logger, _ := dd.New(cfg1, cfg2)  // Error!

Global Logger ​

Get and Set ​

FunctionSignatureDescription
Defaultfunc Default() *LoggerGet the global logger (lazy-initialized)
SetDefaultfunc SetDefault(logger *Logger)Set the global logger
InitDefaultfunc InitDefault(cfg ...Config) errorInitialize the global logger with config
DefaultWithErrfunc DefaultWithErr() (*Logger, error)Get the global logger and its initialization error
DefaultInitErrorfunc DefaultInitError() errorGet the initialization error

Initialize the Global Logger ​

go
// Option 1: auto-initialize (created on first call)
dd.Default().Info("global logger auto-created")

// Option 2: explicit initialization
err := dd.InitDefault(dd.JSONConfig())
if err != nil {
    log.Fatal(err)
}
dd.Default().Info("global logger with JSON config")

// Option 3: replace the global logger
custom, _ := dd.New(dd.Config{
    Level: dd.LevelInfo,
    Targets: []dd.OutputTarget{dd.FileOutput("logs/app.log")},
})
dd.SetDefault(custom)

// Option 4: check initialization errors
logger, err := dd.DefaultWithErr()
if err != nil {
    log.Printf("global logger initialization failed: %v", err)
}

Configuration Presets ​

FunctionSignatureDescription
DefaultConfigfunc DefaultConfig() ConfigDefault config (Info level, text format)
DevelopmentConfigfunc DevelopmentConfig() ConfigDevelopment config (Debug level)
JSONConfigfunc JSONConfig() ConfigJSON output config (Debug level)
ProductionConfigfunc ProductionConfig() ConfigProduction config (Info level, JSON format, RFC3339 timestamps)
go
cfg := dd.DefaultConfig()
cfg.Level = dd.LevelDebug
logger, _ := dd.New(cfg)

Output Target Constructors ​

FunctionSignatureDescription
ConsoleOutputfunc ConsoleOutput() OutputTargetConsole output
FileOutputfunc FileOutput(path string) OutputTargetFile output (supports rotation)
CustomOutputfunc CustomOutput(w io.Writer) OutputTargetCustom Writer output
go
cfg := dd.DefaultConfig()
cfg.Targets = []dd.OutputTarget{
    dd.ConsoleOutput(),
    dd.FileOutput("logs/app.log"),
    dd.CustomOutput(customWriter),
}
logger, _ := dd.New(cfg)

Basic Logging (Package-level) ​

The following functions emit logs through the global logger:

FunctionSignatureDescription
Debugfunc Debug(args ...any)Debug-level log
Infofunc Info(args ...any)Info-level log
Warnfunc Warn(args ...any)Warn-level log
Errorfunc Error(args ...any)Error-level log
Fatalfunc Fatal(args ...any)Fatal-level log (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)
go
dd.Info("application started")
dd.Errorf("user %s login failed", username)
dd.Warn("low disk space")

Formatted Logging (Package-level) ​

FunctionSignatureDescription
Debugffunc Debugf(format string, args ...any)Debug-level formatted log
Infoffunc Infof(format string, args ...any)Info-level formatted log
Warnffunc Warnf(format string, args ...any)Warn-level formatted log
Errorffunc Errorf(format string, args ...any)Error-level formatted log
Fatalffunc Fatalf(format string, args ...any)Fatal-level formatted log (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)

Generic-Level Logging (Package-level) ​

FunctionSignatureDescription
Logfunc Log(level LogLevel, args ...any)Specified-level log
Logffunc Logf(level LogLevel, format string, args ...any)Specified-level formatted log
LogWithfunc LogWith(level LogLevel, msg string, fields ...Field)Specified-level structured log
go
dd.Log(dd.LevelDebug, "debug message")
dd.Logf(dd.LevelWarn, "warning: %s", reason)
dd.LogWith(dd.LevelError, "request failed",
    dd.String("path", "/api/users"),
    dd.Int("status", 500),
)

Structured Logging (Package-level) ​

The following functions emit structured logs through the global logger:

FunctionSignatureDescription
DebugWithfunc DebugWith(msg string, fields ...Field)Debug-level structured log
InfoWithfunc InfoWith(msg string, fields ...Field)Info-level structured log
WarnWithfunc WarnWith(msg string, fields ...Field)Warn-level structured log
ErrorWithfunc ErrorWith(msg string, fields ...Field)Error-level structured log
FatalWithfunc FatalWith(msg string, fields ...Field)Fatal-level structured log (by default calls os.Exit(1), deferred functions will not run; customizable via FatalHandler)
go
dd.InfoWith("request completed",
    dd.String("method", "GET"),
    dd.Int("status", 200),
)

dd.ErrorWith("database error",
    dd.Err(err),
    dd.String("query", sql),
)

Level Management (Package-level) ​

FunctionSignatureDescription
SetLevelfunc SetLevel(level LogLevel) errorSet the global log level
GetLevelfunc GetLevel() LogLevelGet the global log level
IsLevelEnabledfunc IsLevelEnabled(level LogLevel) boolCheck whether a level is enabled
IsDebugEnabledfunc IsDebugEnabled() boolCheck whether Debug level is enabled
IsInfoEnabledfunc IsInfoEnabled() boolCheck whether Info level is enabled
IsWarnEnabledfunc IsWarnEnabled() boolCheck whether Warn level is enabled
IsErrorEnabledfunc IsErrorEnabled() boolCheck whether Error level is enabled
IsFatalEnabledfunc IsFatalEnabled() boolCheck whether Fatal level is enabled
go
// Dynamically adjust the log level
dd.SetLevel(dd.LevelDebug)

// Conditional logging (avoid unnecessary computation)
if dd.IsDebugEnabled() {
    dd.Debug(computeExpensiveDebugInfo())
}

Field Chaining (Package-level) ​

FunctionSignatureDescription
WithFieldsfunc WithFields(fields ...Field) *LoggerEntryCreate an Entry with preset fields
WithFieldfunc WithField(key string, value any) *LoggerEntryCreate an Entry with a single preset field
go
dd.WithFields(dd.String("service", "api"), dd.String("version", "1.0")).
    Info("request completed")

dd.WithField("request_id", "abc123").Info("processing request")

Lifecycle (Package-level) ​

FunctionSignatureDescription
Flushfunc Flush() errorFlush the global logger buffers
Closefunc Close() errorClose the global logger (after Close, package-level log functions become no-ops; prefer Shutdown in production code)
Shutdownfunc Shutdown(ctx context.Context) errorGraceful shutdown with timeout

Writer Management (Package-level) ​

FunctionSignatureDescription
AddWriterfunc AddWriter(writer io.Writer) errorAdd an output writer
RemoveWriterfunc RemoveWriter(writer io.Writer) errorRemove an output writer
WriterCountfunc WriterCount() intGet the writer count

Sampling Control (Package-level) ​

FunctionSignatureDescription
SetSamplingfunc SetSampling(config *SamplingConfig)Set sampling config
GetSamplingfunc GetSampling() *SamplingConfigGet sampling config

Writer Constructors ​

FunctionSignatureDescription
NewFileWriterfunc NewFileWriter(path string, cfg FileWriterConfig) (*FileWriter, error)Create a file writer
DefaultFileWriterConfigfunc DefaultFileWriterConfig() FileWriterConfigDefault file writer config
NewBufferedWriterfunc NewBufferedWriter(w io.Writer, cfg BufferedWriterConfig) (*BufferedWriter, error)Create a buffered writer
DefaultBufferedWriterConfigfunc DefaultBufferedWriterConfig() BufferedWriterConfigDefault buffered writer config
NewMultiWriterfunc NewMultiWriter(writers ...io.Writer) *MultiWriterCreate a multi-output writer

Security Config Constructors ​

FunctionSignatureDescription
DefaultSecurityConfigfunc DefaultSecurityConfig() *SecurityConfigDefault security config (basic filtering)
DefaultSecureConfig Deprecatedfunc DefaultSecureConfig() *SecurityConfigComplete security config (a near-homonym of DefaultSecurityConfig with a different filtering strength, easy to confuse; use SecurityConfigForLevel(dd.SecurityLevelStandard) instead)
HealthcareConfigfunc HealthcareConfig() *SecurityConfigHIPAA-compliant config
FinancialConfigfunc FinancialConfig() *SecurityConfigPCI-DSS-compliant config
GovernmentConfigfunc GovernmentConfig() *SecurityConfigGovernment-standard config
SecurityConfigForLevelfunc SecurityConfigForLevel(level SecurityLevel) *SecurityConfigGet security config by level
DefaultRateLimitConfigfunc DefaultRateLimitConfig() *RateLimitConfigDefault rate-limit config (10,000 messages/s, 10MB/s, burst of 1,000 messages, drop strategy, 1-in-100 sampling rate; see Security Filtering)

Sensitive-Data Filter Constructors ​

FunctionSignatureDescription
NewSensitiveDataFilterfunc NewSensitiveDataFilter() *SensitiveDataFilterFull pattern set filter
NewEmptySensitiveDataFilterfunc NewEmptySensitiveDataFilter() *SensitiveDataFilterEmpty filter
NewCustomSensitiveDataFilterfunc NewCustomSensitiveDataFilter(patterns ...string) (*SensitiveDataFilter, error)Custom-pattern filter

Hook Constructors ​

FunctionSignatureDescription
NewHookRegistryfunc NewHookRegistry() *HookRegistryCreate a hook registry
NewHooksFromConfigfunc NewHooksFromConfig(cfg HooksConfig) *HookRegistryCreate a hook registry from config

Audit Logger Constructors ​

FunctionSignatureDescription
NewAuditLoggerfunc NewAuditLogger(cfg AuditConfig) (*AuditLogger, error)Create an audit logger
DefaultAuditConfigfunc DefaultAuditConfig() AuditConfigDefault audit config
VerifyAuditEventfunc VerifyAuditEvent(entry string, signer *IntegritySigner) *AuditVerificationResultVerify the integrity of an audit event

Integrity Signing Constructors ​

FunctionSignatureDescription
NewIntegritySignerfunc NewIntegritySigner(cfg IntegrityConfig) (*IntegritySigner, error)Create an integrity signer
DefaultIntegrityConfigSafefunc DefaultIntegrityConfigSafe() (IntegrityConfig, error)Safe random-key config

Test Helper Constructor ​

FunctionSignatureDescription
NewLoggerRecorderfunc NewLoggerRecorder() *LoggerRecorderCreate a log recorder (for testing)

Context Functions ​

FunctionSignatureDescription
WithTraceIDfunc WithTraceID(ctx context.Context, traceID string) context.ContextSet Trace ID
WithSpanIDfunc WithSpanID(ctx context.Context, spanID string) context.ContextSet Span ID
WithRequestIDfunc WithRequestID(ctx context.Context, requestID string) context.ContextSet Request ID
GetTraceIDfunc GetTraceID(ctx context.Context) stringGet Trace ID
GetSpanIDfunc GetSpanID(ctx context.Context) stringGet Span ID
GetRequestIDfunc GetRequestID(ctx context.Context) stringGet Request ID

JSON Configuration ​

FunctionSignatureDescription
DefaultJSONOptionsfunc DefaultJSONOptions() *JSONOptionsDefault JSON output options

Field Constructors ​

Used to create structured log fields (Field); used with the *With family of methods or WithFields.

FunctionSignatureDescription
Anyfunc Any(key string, value any) FieldAny-type field
Stringfunc String(key, value string) FieldString field
Boolfunc Bool(key string, value bool) FieldBool field
Intfunc Int(key string, value int) Fieldint field
Int8func Int8(key string, value int8) Fieldint8 field
Int16func Int16(key string, value int16) Fieldint16 field
Int32func Int32(key string, value int32) Fieldint32 field
Int64func Int64(key string, value int64) Fieldint64 field
Uintfunc Uint(key string, value uint) Fielduint field
Uint8func Uint8(key string, value uint8) Fielduint8 field
Uint16func Uint16(key string, value uint16) Fielduint16 field
Uint32func Uint32(key string, value uint32) Fielduint32 field
Uint64func Uint64(key string, value uint64) Fielduint64 field
Float32func Float32(key string, value float32) Fieldfloat32 field
Float64func Float64(key string, value float64) Fieldfloat64 field
Durationfunc Duration(key string, value time.Duration) FieldDuration field
Timefunc Time(key string, value time.Time) FieldTime field
Errfunc Err(err error) FieldError field (key is "error")
ErrWithKeyfunc ErrWithKey(key string, err error) FieldError field with custom key
ErrWithStackfunc ErrWithStack(err error) FieldError field with stack trace
go
dd.InfoWith("request completed",
    dd.String("method", "GET"),
    dd.Int("status", 200),
    dd.Duration("elapsed", 100*time.Millisecond),
    dd.Err(err),
)

Type-safety recommendation

Prefer type-specific constructors (e.g. Int, String) over Any to catch type errors at compile time and avoid runtime issues from type mismatches.

Field Validation Configuration ​

FunctionSignatureDescription
DefaultFieldValidationConfigfunc DefaultFieldValidationConfig() *FieldValidationConfigDefault field validation (none)
StrictSnakeCaseConfigfunc StrictSnakeCaseConfig() *FieldValidationConfigStrict snake_case validation
StrictCamelCaseConfigfunc StrictCamelCaseConfig() *FieldValidationConfigStrict camelCase validation

Debug Output Functions ​

FunctionSignatureDescription
Printfunc Print(args ...any)Output to the global logger's Writer (LevelInfo, subject to security filtering)
Printlnfunc Println(args ...any)Same as Print (the underlying Log() already appends a newline; subject to security filtering)
Printffunc Printf(format string, args ...any)Formatted output (LevelInfo, subject to security filtering)
JSONfunc JSON(data ...any)Compact-JSON output to stdout (includes caller info; does not go through security filtering)
JSONFfunc JSONF(format string, args ...any)Formatted string output as compact JSON to stdout (includes caller info; does not go through security filtering)
Textfunc Text(data ...any)Pretty-printed output to stdout (does not go through security filtering)
Textffunc Textf(format string, args ...any)Formatted text output to stdout (does not go through security filtering)
Exitfunc Exit(data ...any)Text output with caller info followed by exit (exit code 0); complex types are pretty-printed automatically; does not go through security filtering
Exitffunc Exitf(format string, args ...any)Formatted output with caller info followed by exit (exit code 0; does not go through security filtering)

Debug-function security note

Print/Println/Printf go through security filtering, but JSON/JSONF/Text/Textf/Exit/Exitf emit raw data directly and do not go through security filtering.

Next Steps ​