logger

package module
v4.5.4 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Aug 20, 2026 License: MIT Imports: 17 Imported by: 0

README


About SmooAI

SmooAI is an AI-powered platform for helping businesses multiply their customer, employee, and developer experience.

Learn more on smoo.ai

SmooAI Packages

Check out other SmooAI packages at smoo.ai/open-source

About smooai-logger (Go)

The missing piece for AWS & Go logging - A contextual logging system that automatically captures the full execution context you need to debug production issues, without the manual setup.

Go Reference

GitHub License GitHub Actions Workflow Status GitHub Repo stars

Go Package

A Go port of @smooai/logger that mirrors the feature set of the TypeScript, Python, and Rust versions. The package exposes a JSON-first logging API with correlation tracking, HTTP helpers, AWS Lambda integration, optional pretty-printing, and rotating-file output — all idiomatic Go with no global init required.

Why smooai-logger?

Ever spent hours debugging a Go service in production, only to realize you're missing critical context? Traditional loggers give you the message, but not the story.

smooai-logger automatically captures:

For AWS Services:

  • Exact code location - File, line number, and function name for every log
  • Request journey - Correlation IDs that follow requests across services
  • AWS context - Service-specific metadata and execution details
  • HTTP details - Headers, methods, status codes from API Gateway
  • Message context - SQS attributes, EventBridge events, SNS messages
  • Service integration - Lambda, ECS, Fargate, EC2, and more

Install

go get github.com/SmooAI/logger/go/v4

Cross-Language Support

The same structured log format works across all your services:

Language Package Install
TypeScript @smooai/logger pnpm add @smooai/logger
Python smooai-logger pip install smooai-logger
Rust smooai-logger cargo add smooai-logger
Go github.com/SmooAI/logger/go/v4 go get github.com/SmooAI/logger/go/v4

The Power of Automatic Context

See Where Your Logs Come From

Every log entry includes the exact location in your code:

import logger "github.com/SmooAI/logger/go/v4"

log := logger.Default()
log.Info("User created")

// Output includes:
{
  "caller": {
    "file":     "src/services/user_service.go",
    "line":     42,
    "function": "UserService.CreateUser"
  }
}

No more guessing which function logged what - the full call site is right there.

Track Requests Across Services

Correlation IDs automatically flow through your entire system:

// Service A: API Gateway Handler
lambdaLog.AddAPIGatewayContext(request)
lambdaLog.Info("Request received")  // Correlation ID: abc-123

// Service B: SQS Processor (automatically extracts ID from message)
lambdaLog.AddSQSRecordContext(record)
lambdaLog.Info("Processing message")  // Same Correlation ID: abc-123

// Service C: Another Lambda (receives via HTTP header)
lambdaLog.Info("Completing workflow")  // Still Correlation ID: abc-123

Production-Ready Examples

AWS Lambda with API Gateway
package main

import (
    "context"

    "github.com/aws/aws-lambda-go/events"
    "github.com/aws/aws-lambda-go/lambda"
    logger "github.com/SmooAI/logger/go/v4"
)

var log *logger.LambdaLogger

func init() {
    base, _ := logger.New(logger.Options{Name: "UserAPI"})
    log = logger.NewLambdaLogger(base)
}

func handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
    log.AddLambdaContext(ctx)
    log.AddAPIGatewayContext(request)

    user, err := createUser(request.Body)
    if err != nil {
        log.Error("Failed to create user", err, map[string]any{
            "body":    request.Body,
            "headers": request.Headers,
        })
        return events.APIGatewayProxyResponse{StatusCode: 500}, err
    }

    log.Info("User created successfully", map[string]any{"userId": user.ID})
    return events.APIGatewayProxyResponse{StatusCode: 201}, nil
}

func main() {
    lambda.Start(handler)
}
AWS ECS/Fargate Services
import (
    "os"
    logger "github.com/SmooAI/logger/go/v4"
)

log, _ := logger.New(logger.Options{
    Name:  "OrderService",
    Level: logger.LevelInfo,
})

// Add container metadata for ECS/Fargate
log.AddContext(logger.Map{
    "taskArn":       os.Getenv("ECS_TASK_ARN"),
    "containerName": os.Getenv("ECS_CONTAINER_NAME"),
})

log.Info("Processing order", map[string]any{
    "orderId": orderId,
    "amount":  amount,
})
SQS Message Processing
func sqsHandler(ctx context.Context, event events.SQSEvent) error {
    for _, record := range event.Records {
        lambdaLog.AddSQSRecordContext(record)
        lambdaLog.Info("Processing message", map[string]any{
            "messageId": record.MessageId,
            "attempt":   record.Attributes["ApproximateReceiveCount"],
        })

        // Logger maintains context throughout the operation
        if err := processOrder(record.Body); err != nil {
            lambdaLog.Error("Failed to process order", err)
            return err
        }
    }
    return nil
}
HTTP Request Processing
log.AddHTTPRequest(logger.HTTPRequest{
    Method:  "GET",
    Path:    "/api/orders",
    Headers: map[string]string{"X-Correlation-Id": correlationId},
})

log.Info("Processing request", map[string]any{
    "messageId": messageId,
    "attempt":   attemptCount,
})

// Process the request...
response, err := processRequest()

log.AddHTTPResponse(logger.HTTPResponse{
    StatusCode: 200,
    Headers:    responseHeaders,
})

Advanced Features

Smart Error Handling

Errors are automatically serialized with full context, including the goroutine stack trace and the full error chain:

_, err := riskyOperation()
if err != nil {
    log.Error("Operation failed", err, map[string]any{
        "context": "additional-info",
    })
    // Logged fields include: error message, stack trace, error type, causes, and your context
}

Flexible Context Management

// Add user context that persists across all subsequent logs
log.AddUserContext(logger.User{
    ID:   "user-123",
    Role: "admin",
})

// Add telemetry for performance tracking
log.AddTelemetryFields(logger.TelemetryFields{
    Duration:  150,
    Namespace: "db-query",
})

// Add custom context for a specific log
log.Info("Payment processed", map[string]any{
    "amount":   99.99,
    "currency": "USD",
})

Correlation ID Management

// Set a specific correlation ID (also sets requestId and traceId)
log.SetCorrelationID("abc-123")

// Read the current correlation ID
id := log.CorrelationID()

// Generate a fresh correlation ID
log.ResetCorrelationID()

// Reset all context and generate new IDs
log.ResetContext()

Local Development Features

Pretty Printing

Pretty output is automatically enabled in local or CI environments (SST_DEV, IS_LOCAL, or GITHUB_ACTIONS):

prettyOn := true
log, _ := logger.New(logger.Options{
    PrettyPrint: &prettyOn, // Force enable for readable console output
})
Automatic Log Rotation

File logging is automatically enabled in local environments and can be configured explicitly:

fileOn := true
log, _ := logger.New(logger.Options{
    LogToFile: &fileOn,
    Rotation: &logger.RotationOptions{
        Path:           ".smooai-logs",
        FilenamePrefix: "app",
        Extension:      "log",
        Size:           "10M",  // Rotate at 10 MB
        Interval:       "1d",   // Daily rotation
        MaxFiles:       10,     // Keep 10 files
        MaxTotalSize:   "100M", // Total size limit
    },
})

API Reference

Logger Creation

import logger "github.com/SmooAI/logger/go/v4"

// With options
prettyOn := true
log, err := logger.New(logger.Options{
    Name:        "MyService",
    Level:       logger.LevelInfo,
    PrettyPrint: &prettyOn,
})

// With defaults
log := logger.Default()

Context Helpers

// HTTP context (also extracts X-Correlation-Id header automatically)
log.AddHTTPRequest(logger.HTTPRequest{
    Method:  "GET",
    Path:    "/api/users",
    Headers: map[string]string{"X-Correlation-Id": "abc-123"},
})

log.AddHTTPResponse(logger.HTTPResponse{
    StatusCode: 200,
    Headers:    responseHeaders,
})

// User context
log.AddUserContext(logger.User{
    ID:    "user-123",
    Email: "user@example.com",
    Role:  "admin",
})

// Telemetry and tracing
log.AddTelemetryFields(logger.TelemetryFields{
    RequestID: "req-456",
    TraceID:   "trace-789",
    Duration:  250,
    Namespace: "user-service",
    Service:   "api-gateway",
})

// Arbitrary custom context (merged into the "context" field)
log.AddContext(logger.Map{
    "customField": "value",
    "nested": logger.Map{
        "key": "value",
    },
})

// Set a single base-level key
log.AddBaseContextKey("region", "us-east-1")

// Set namespace
log.SetNamespace("custom-namespace")

// Reset all context and regenerate correlation IDs
log.ResetContext()

Lambda Helpers

lambdaLog := logger.NewLambdaLogger(log)

// Add Lambda invocation context (request ID, function ARN, Cognito identity)
lambdaLog.AddLambdaContext(ctx)

// Add Lambda environment variables (function name, version, region, memory)
lambdaLog.AddLambdaEnvironmentContext()

// Add API Gateway request context
lambdaLog.AddAPIGatewayContext(request)

// Add SQS record context (also sets correlation ID from message ID)
lambdaLog.AddSQSRecordContext(record)

// Strip verbose context when running locally
lambdaLog.SlimDownLocally()

Logging Methods

// Simple message
log.Info("User created successfully")

// With structured data (map[string]any args are merged into the "context" field)
log.Info("Processing request", map[string]any{
    "userId": "123",
    "action": "create",
})

// With error (stack trace and error chain captured automatically)
log.Error("Database connection failed", err)

// Combining message, error, and data
log.Error("Failed to create user", err, map[string]any{
    "userId":  "123",
    "attempt": 3,
})

// All log levels
log.Trace("Verbose detail")
log.Debug("Diagnostic info")
log.Info("Operational message")
log.Warn("Warning condition")
log.Error("Error condition", err)
log.Fatal("Critical failure", err)

Lifecycle

// Close flushes and closes the file writer (call on shutdown)
defer log.Close()

Configuration

Log Levels

  • LevelTrace (10) - Detailed debugging information
  • LevelDebug (20) - Diagnostic information
  • LevelInfo (30) - General operational information
  • LevelWarn (40) - Warning conditions
  • LevelError (50) - Error conditions
  • LevelFatal (60) - Critical failures

Log level can also be set via the LOG_LEVEL environment variable (trace, debug, info, warn, error, fatal).

Environment Variables

The logger respects these environment variables for automatic configuration:

  • SST_DEV - Enables pretty printing and file logging in SST development
  • IS_LOCAL - Enables pretty printing and file logging for local development
  • IS_DEPLOYED_STAGE - When set to true, disables local-mode behaviour
  • GITHUB_ACTIONS - Enables pretty printing in CI/CD
  • LOG_LEVEL - Sets the minimum log level (default: info)

Built With

  • Go 1.22+ - Static typing and first-class concurrency
  • encoding/json - Standard library JSON serialization
  • github.com/aws/aws-lambda-go - AWS Lambda context and event types
  • github.com/google/uuid - Correlation ID generation
  • Automatic log rotation with configurable size, interval, and retention

Development

Running tests

go test ./...

Building

go build ./...

Linting and Formatting

go vet ./...
gofmt -w .

(back to top)

Contact

Brent Rager

Smoo Github: https://github.com/SmooAI

(back to top)

License

MIT © SmooAI

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

View Source
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.

View Source
const RedactedValue = "[REDACTED]"

RedactedValue is the placeholder string substituted in place of any redacted value.

View Source
const Version = "4.5.4"

Version is the current version of the smooai-logger Go package.

Variables

View Source
var PresetConfigFull = AllowAll()

PresetConfigFull allows all context through unfiltered.

View Source
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 IsBuild

func IsBuild() bool

IsBuild returns true when running inside GitHub Actions.

func IsLocal

func IsLocal() bool

IsLocal returns true when running in a local development environment, matching the TypeScript/Python/Rust detection logic.

func MarshalJSON

func MarshalJSON(m Map) ([]byte, error)

MarshalJSON is a helper that marshals a Map to JSON bytes.

func SetSlogHandler

func SetSlogHandler(h slog.Handler)

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 AllowAll

func AllowAll() *ContextConfig

AllowAll returns a config that includes everything.

func Deny

func Deny() *ContextConfig

Deny returns a config that removes the entire branch.

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.

const (
	LevelTrace Level = 10
	LevelDebug Level = 20
	LevelInfo  Level = 30
	LevelWarn  Level = 40
	LevelError Level = 50
	LevelFatal Level = 60
)

func ParseLevel

func ParseLevel(s string) Level

ParseLevel converts a string to a Level. Returns LevelInfo if unrecognized.

func (Level) String

func (l Level) String() string

String returns the lowercase string representation of the level.

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 Default

func Default() *Logger

Default creates a Logger with default settings.

func New

func New(opts Options) (*Logger, error)

New creates a new Logger with the given options.

func (*Logger) AddBaseContext

func (l *Logger) AddBaseContext(ctx Map)

AddBaseContext merges the given map into the base context.

func (*Logger) AddBaseContextKey

func (l *Logger) AddBaseContextKey(key string, value any)

AddBaseContextKey adds a single key-value pair to the base context.

func (*Logger) AddContext

func (l *Logger) AddContext(ctx Map)

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

func (l *Logger) AddRedactKeys(keys ...string)

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

func (l *Logger) AddUserContext(user User)

AddUserContext adds user identity context.

func (*Logger) Close

func (l *Logger) Close() error

Close flushes and closes the file writer, if any.

func (*Logger) Context

func (l *Logger) Context() Map

Context returns a copy of the global context.

func (*Logger) ContextConfigValue

func (l *Logger) ContextConfigValue() *ContextConfig

ContextConfigValue returns the current context config, if any.

func (*Logger) CorrelationID

func (l *Logger) CorrelationID() string

CorrelationID returns the current correlation ID.

func (*Logger) Debug

func (l *Logger) Debug(msg string, args ...any) error

Debug logs at DEBUG level.

func (*Logger) DebugContext

func (l *Logger) DebugContext(ctx context.Context, msg string, args ...any) error

DebugContext logs at DEBUG level, correlating to the active span in ctx.

func (*Logger) Error

func (l *Logger) Error(msg string, args ...any) error

Error logs at ERROR level.

func (*Logger) ErrorContext

func (l *Logger) ErrorContext(ctx context.Context, msg string, args ...any) error

ErrorContext logs at ERROR level, correlating to the active span in ctx.

func (*Logger) Fatal

func (l *Logger) Fatal(msg string, args ...any) error

Fatal logs at FATAL level.

func (*Logger) FatalContext

func (l *Logger) FatalContext(ctx context.Context, msg string, args ...any) error

FatalContext logs at FATAL level, correlating to the active span in ctx.

func (*Logger) GetLevel

func (l *Logger) GetLevel() Level

GetLevel returns the current log level.

func (*Logger) Info

func (l *Logger) Info(msg string, args ...any) error

Info logs at INFO level.

func (*Logger) InfoContext

func (l *Logger) InfoContext(ctx context.Context, msg string, args ...any) error

InfoContext logs at INFO level, correlating to the active span in ctx.

func (*Logger) Name

func (l *Logger) Name() string

Name returns the logger's name.

func (*Logger) RedactKeys

func (l *Logger) RedactKeys() []string

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

func (l *Logger) SetContext(ctx Map)

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

func (l *Logger) SetCorrelationID(id string)

SetCorrelationID sets the correlation ID (also sets requestId and traceId).

func (*Logger) SetLevel

func (l *Logger) SetLevel(level Level)

SetLevel sets the minimum log level.

func (*Logger) SetName

func (l *Logger) SetName(name string)

SetName sets the logger's name.

func (*Logger) SetNamespace

func (l *Logger) SetNamespace(namespace string)

SetNamespace sets the namespace in the base context.

func (*Logger) SetRedactKeys

func (l *Logger) SetRedactKeys(keys []string)

SetRedactKeys replaces the redact-keys list. Keys are stored lowercased.

func (*Logger) Silent

func (l *Logger) Silent(_ string, _ ...any) error

Silent is a no-op log method.

func (*Logger) Trace

func (l *Logger) Trace(msg string, args ...any) error

Trace logs at TRACE level.

func (*Logger) TraceContext

func (l *Logger) TraceContext(ctx context.Context, msg string, args ...any) error

TraceContext logs at TRACE level, correlating to the active span in ctx.

func (*Logger) Warn

func (l *Logger) Warn(msg string, args ...any) error

Warn logs at WARN level.

func (*Logger) WarnContext

func (l *Logger) WarnContext(ctx context.Context, msg string, args ...any) error

WarnContext logs at WARN level, correlating to the active span in ctx.

type Map

type Map = map[string]any

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.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL