Documentation
¶
Overview ¶
Package logger provides a structured JSON logging library for Go, matching the log format and feature set of the TypeScript (@smooai/logger), Python (smooai-logger), and Rust (smooai-logger) SDKs.
It supports multiple log levels, structured context, correlation tracking, ANSI-formatted file output, and automatic log rotation.
Index ¶
- Constants
- Variables
- func DefaultRedactKeys() []string
- func IsBuild() bool
- func IsLocal() bool
- func MarshalJSON(m Map) ([]byte, error)
- func SetSlogHandler(h slog.Handler)
- type CallerInfo
- type ContextConfig
- type ContextConfigType
- type ErrorDetail
- type HTTPRequest
- type HTTPResponse
- type LambdaLogger
- func (l *LambdaLogger) AddAPIGatewayContext(request events.APIGatewayProxyRequest)
- func (l *LambdaLogger) AddECSContext()
- func (l *LambdaLogger) AddLambdaContext(ctx context.Context)
- func (l *LambdaLogger) AddLambdaEnvironmentContext()
- func (l *LambdaLogger) AddSQSRecordContext(record events.SQSMessage)
- func (l *LambdaLogger) SlimDownLocally()
- type Level
- type Logger
- func (l *Logger) AddBaseContext(ctx Map)
- func (l *Logger) AddBaseContextKey(key string, value any)
- func (l *Logger) AddContext(ctx Map)
- func (l *Logger) AddHTTPRequest(req HTTPRequest)
- func (l *Logger) AddHTTPResponse(resp HTTPResponse)
- func (l *Logger) AddRedactKeys(keys ...string)
- func (l *Logger) AddTelemetryFields(fields TelemetryFields)
- func (l *Logger) AddUserContext(user User)
- func (l *Logger) Close() error
- func (l *Logger) Context() Map
- func (l *Logger) ContextConfigValue() *ContextConfig
- func (l *Logger) CorrelationID() string
- func (l *Logger) Debug(msg string, args ...any) error
- func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) error
- func (l *Logger) Error(msg string, args ...any) error
- func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) error
- func (l *Logger) Fatal(msg string, args ...any) error
- func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any) error
- func (l *Logger) GetLevel() Level
- func (l *Logger) Info(msg string, args ...any) error
- func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) error
- func (l *Logger) Name() string
- func (l *Logger) RedactKeys() []string
- func (l *Logger) ResetContext()
- func (l *Logger) ResetCorrelationID()
- func (l *Logger) SetContext(ctx Map)
- func (l *Logger) SetContextConfig(config *ContextConfig)
- func (l *Logger) SetCorrelationID(id string)
- func (l *Logger) SetLevel(level Level)
- func (l *Logger) SetName(name string)
- func (l *Logger) SetNamespace(namespace string)
- func (l *Logger) SetRedactKeys(keys []string)
- func (l *Logger) Silent(_ string, _ ...any) error
- func (l *Logger) Trace(msg string, args ...any) error
- func (l *Logger) TraceContext(ctx context.Context, msg string, args ...any) error
- func (l *Logger) Warn(msg string, args ...any) error
- func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) error
- type Map
- type Options
- type RotationOptions
- type TelemetryFields
- type User
Constants ¶
const ( KeyLevel = "level" KeyLogLevel = "LogLevel" KeyTime = "time" KeyMessage = "msg" KeyName = "name" KeyCorrelationID = "correlationId" KeyRequestID = "requestId" KeyTraceID = "traceId" KeySpanID = "spanId" KeyNamespace = "namespace" KeyService = "service" KeyDuration = "duration" KeyError = "error" KeyErrorDetails = "errorDetails" KeyContext = "context" KeyUser = "user" KeyHTTP = "http" )
Context key constants matching the TypeScript/Python/Rust implementations.
const RedactedValue = "[REDACTED]"
RedactedValue is the placeholder string substituted in place of any redacted value.
const Version = "3.2.3"
Version is the current version of the smooai-logger Go package.
Variables ¶
var PresetConfigFull = AllowAll()
PresetConfigFull allows all context through unfiltered.
var PresetConfigMinimal = Nested(map[string]*ContextConfig{ "http": Nested(map[string]*ContextConfig{ "request": OnlyKeys("method", "hostname", "path", "queryString", "headers", "sourceIp", "userAgent"), "response": OnlyKeys("statusCode", "headers"), }), })
PresetConfigMinimal filters HTTP context to essential fields only, matching the Rust CONFIG_MINIMAL / TypeScript configMinimal behavior.
Functions ¶
func DefaultRedactKeys ¶
func DefaultRedactKeys() []string
DefaultRedactKeys returns the default list of context keys whose values will be replaced with RedactedValue before logging. Matching is case-insensitive.
func IsLocal ¶
func IsLocal() bool
IsLocal returns true when running in a local development environment, matching the TypeScript/Python/Rust detection logic.
func MarshalJSON ¶
MarshalJSON is a helper that marshals a Map to JSON bytes.
func SetSlogHandler ¶
SetSlogHandler installs an slog.Handler that every subsequent log line is additionally forwarded to, carrying the call's context.Context. A handler that reads the active span from ctx — e.g. the @smooai/observability otelslog bridge (observability.SlogHandler(...)) — turns each line into an OTLP log record correlated to the enclosing trace and ships it to /v1/logs.
The logger's own stdout/file JSON output is unaffected. Pass nil to detach. Wiring is done by the application (not this package) to keep the dependency on @smooai/observability out of the logger and avoid a cycle.
Types ¶
type CallerInfo ¶
type CallerInfo struct {
File string `json:"file"`
Line int `json:"line"`
Function string `json:"function"`
}
CallerInfo holds information about the calling function.
type ContextConfig ¶
type ContextConfig struct {
Type ContextConfigType
Keys []string // For ConfigOnlyKeys
Children map[string]*ContextConfig // For ConfigNested
}
ContextConfig defines how to filter context data in log output. It forms a tree structure that can recursively filter nested maps.
func Nested ¶
func Nested(children map[string]*ContextConfig) *ContextConfig
Nested returns a config that applies child configs per key. Keys not listed in children are kept as-is (AllowAll by default).
func OnlyKeys ¶
func OnlyKeys(keys ...string) *ContextConfig
OnlyKeys returns a config that keeps only the specified keys.
type ContextConfigType ¶
type ContextConfigType int
ContextConfigType represents the type of context config filter.
const ( // ConfigAllowAll includes everything in the target branch. ConfigAllowAll ContextConfigType = iota // ConfigDeny removes the target branch entirely. ConfigDeny // ConfigOnlyKeys keeps only the listed keys at this level. ConfigOnlyKeys // ConfigNested applies nested configuration rules to object children. ConfigNested )
type ErrorDetail ¶
type ErrorDetail struct {
Message string `json:"message"`
Name string `json:"name"`
Stack string `json:"stack,omitempty"`
Causes []string `json:"causes,omitempty"`
}
ErrorDetail represents a serialized error for structured logging.
type HTTPRequest ¶
type HTTPRequest struct {
Protocol string `json:"protocol,omitempty"`
Hostname string `json:"hostname,omitempty"`
Path string `json:"path,omitempty"`
Method string `json:"method,omitempty"`
QueryString string `json:"queryString,omitempty"`
SourceIP string `json:"sourceIp,omitempty"`
UserAgent string `json:"userAgent,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
Body any `json:"body,omitempty"`
}
HTTPRequest holds HTTP request context.
type HTTPResponse ¶
type HTTPResponse struct {
StatusCode int `json:"statusCode,omitempty"`
Body any `json:"body,omitempty"`
Headers map[string]string `json:"headers,omitempty"`
}
HTTPResponse holds HTTP response context.
type LambdaLogger ¶
type LambdaLogger struct {
*Logger
}
LambdaLogger wraps Logger with Lambda-specific context helpers.
func NewLambdaLogger ¶
func NewLambdaLogger(logger *Logger) *LambdaLogger
NewLambdaLogger creates a LambdaLogger from an existing Logger.
func (*LambdaLogger) AddAPIGatewayContext ¶
func (l *LambdaLogger) AddAPIGatewayContext(request events.APIGatewayProxyRequest)
AddAPIGatewayContext adds API Gateway request context to the logger.
func (*LambdaLogger) AddECSContext ¶
func (l *LambdaLogger) AddECSContext()
AddECSContext adds ECS task/container metadata to the logger context under the "ecs" key, mirroring Python's aws_logger.add_ecs_context. Reads the standard ECS-on-Fargate / Amazon-ECS-Agent env vars.
func (*LambdaLogger) AddLambdaContext ¶
func (l *LambdaLogger) AddLambdaContext(ctx context.Context)
AddLambdaContext extracts Lambda invocation context from the context.Context and adds it to the logger's base context. This includes the request ID, function name, function ARN, and memory limit.
func (*LambdaLogger) AddLambdaEnvironmentContext ¶
func (l *LambdaLogger) AddLambdaEnvironmentContext()
AddLambdaEnvironmentContext adds Lambda environment variables to the logger context.
func (*LambdaLogger) AddSQSRecordContext ¶
func (l *LambdaLogger) AddSQSRecordContext(record events.SQSMessage)
AddSQSRecordContext adds SQS message context to the logger, including message ID, event source, event source ARN, and receipt handle.
func (*LambdaLogger) SlimDownLocally ¶
func (l *LambdaLogger) SlimDownLocally()
SlimDownLocally removes verbose context when running locally (IS_LOCAL env). This keeps log output readable during local development by stripping Lambda environment details, API Gateway metadata, and SQS receipt handles.
type Level ¶
type Level int
Level represents the severity of a log entry.
func ParseLevel ¶
ParseLevel converts a string to a Level. Returns LevelInfo if unrecognized.
type Logger ¶
type Logger struct {
// contains filtered or unexported fields
}
Logger is a structured JSON logger that writes to stdout and optionally to rotating log files, matching the smooai logging format.
func (*Logger) AddBaseContext ¶
AddBaseContext merges the given map into the base context.
func (*Logger) AddBaseContextKey ¶
AddBaseContextKey adds a single key-value pair to the base context.
func (*Logger) AddContext ¶
AddContext merges the given map into the nested "context" field.
func (*Logger) AddHTTPRequest ¶
func (l *Logger) AddHTTPRequest(req HTTPRequest)
AddHTTPRequest adds HTTP request context and sets the namespace.
func (*Logger) AddHTTPResponse ¶
func (l *Logger) AddHTTPResponse(resp HTTPResponse)
AddHTTPResponse adds HTTP response context.
func (*Logger) AddRedactKeys ¶
AddRedactKeys adds keys to the redact-keys list. Existing entries are preserved.
func (*Logger) AddTelemetryFields ¶
func (l *Logger) AddTelemetryFields(fields TelemetryFields)
AddTelemetryFields adds telemetry context to the base context.
func (*Logger) AddUserContext ¶
AddUserContext adds user identity context.
func (*Logger) ContextConfigValue ¶
func (l *Logger) ContextConfigValue() *ContextConfig
ContextConfigValue returns the current context config, if any.
func (*Logger) CorrelationID ¶
CorrelationID returns the current correlation ID.
func (*Logger) DebugContext ¶
DebugContext logs at DEBUG level, correlating to the active span in ctx.
func (*Logger) ErrorContext ¶
ErrorContext logs at ERROR level, correlating to the active span in ctx.
func (*Logger) FatalContext ¶
FatalContext logs at FATAL level, correlating to the active span in ctx.
func (*Logger) InfoContext ¶
InfoContext logs at INFO level, correlating to the active span in ctx.
func (*Logger) RedactKeys ¶
RedactKeys returns the current redact-keys list (lowercased, sorted).
func (*Logger) ResetContext ¶
func (l *Logger) ResetContext()
ResetContext clears the global context and generates new correlation IDs.
func (*Logger) ResetCorrelationID ¶
func (l *Logger) ResetCorrelationID()
ResetCorrelationID generates a new correlation ID.
func (*Logger) SetContext ¶
SetContext replaces the global context.
func (*Logger) SetContextConfig ¶
func (l *Logger) SetContextConfig(config *ContextConfig)
SetContextConfig sets the context config filter on the logger.
func (*Logger) SetCorrelationID ¶
SetCorrelationID sets the correlation ID (also sets requestId and traceId).
func (*Logger) SetNamespace ¶
SetNamespace sets the namespace in the base context.
func (*Logger) SetRedactKeys ¶
SetRedactKeys replaces the redact-keys list. Keys are stored lowercased.
func (*Logger) TraceContext ¶
TraceContext logs at TRACE level, correlating to the active span in ctx.
type Map ¶
Map is the type used for structured context data.
func ApplyContextConfig ¶
func ApplyContextConfig(data Map, config *ContextConfig) Map
ApplyContextConfig recursively filters a map based on the config. It returns a new map with the filtered result, leaving the original untouched.
func GetLambdaEnvironmentContext ¶
func GetLambdaEnvironmentContext() Map
GetLambdaEnvironmentContext returns Lambda environment variables as a context map. This captures function name, version, region, memory size, and log group.
type Options ¶
type Options struct {
Name string
Level Level
PrettyPrint *bool
LogToFile *bool
Rotation *RotationOptions
Context Map
ContextConfig *ContextConfig
// RedactKeys overrides the default redact-keys list. If nil, [DefaultRedactKeys]
// is used. Matching is case-insensitive. Set to a non-nil empty slice to disable
// redaction entirely.
RedactKeys []string
}
Options configures a new Logger.
type RotationOptions ¶
type RotationOptions struct {
Path string // Directory for log files (default: ".smooai-logs")
FilenamePrefix string // Prefix for log filenames (default: "output")
Extension string // File extension (default: "ansi")
Size string // Max file size before rotation (e.g., "1M", "10K")
Interval string // Rotation interval (e.g., "1d", "2h")
MaxFiles int // Max rotated files to keep (default: 30)
MaxTotalSize string // Max total size of all log files (e.g., "100M")
}
RotationOptions configures log file rotation.
func DefaultRotationOptions ¶
func DefaultRotationOptions() RotationOptions
DefaultRotationOptions returns the default rotation configuration.
type TelemetryFields ¶
type TelemetryFields struct {
RequestID string `json:"requestId,omitempty"`
Duration float64 `json:"duration,omitempty"`
TraceID string `json:"traceId,omitempty"`
Namespace string `json:"namespace,omitempty"`
Service string `json:"service,omitempty"`
Error string `json:"error,omitempty"`
}
TelemetryFields holds telemetry context.
type User ¶
type User struct {
ID string `json:"id,omitempty"`
Email string `json:"email,omitempty"`
Phone string `json:"phone,omitempty"`
Role string `json:"role,omitempty"`
FullName string `json:"fullName,omitempty"`
FirstName string `json:"firstName,omitempty"`
LastName string `json:"lastName,omitempty"`
Context Map `json:"context,omitempty"`
}
User holds user identity context.