logging

package
v0.2.11-alpha Latest Latest
Warning

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

Go to latest
Published: Jan 27, 2026 License: Apache-2.0 Imports: 17 Imported by: 5

README

zen-sdk/pkg/logging

Unified, professional logging package for all zen components with context-aware structured logging, OpenTelemetry integration, and production-ready features.

Features

  • Context-aware logging - Automatic extraction of request_id, tenant_id, user_id, trace_id, span_id
  • Structured logging - JSON output in production, pretty console in development
  • OpenTelemetry integration - Automatic trace/span ID extraction from context
  • Enhanced error handling - Automatic categorization, stack traces in debug mode
  • Security features - UUID masking, token masking, password redaction, PII protection
  • Performance logging - Standardized helpers for requests, DB, cache, external APIs
  • Audit logging - Security-compliant audit helpers for compliance
  • Sampling & rate limiting - Prevent log flooding in production
  • Dev vs Production optimizations - Pretty logs in dev, optimized JSON in production

Quick Start

import "github.com/kube-zen/zen-sdk/pkg/logging"

// Create a logger
logger := logging.NewLogger("my-component")

// Log with context (extracts request_id, tenant_id, trace_id automatically)
ctx := context.WithValue(context.Background(), "request_id", "req-123")
logger.WithContext(ctx).Info("Processing request",
    logging.Operation("handle_request"),
    logging.String("status", "success"),
)

Basic Usage

Creating a Logger
// Simple logger with defaults
logger := logging.NewLogger("zen-back")

// Logger with custom configuration
config := logging.LoggerConfig{
    ComponentName:     "zen-back",
    Development:       false,
    LogLevel:          "info",
    EnableStackTraces: false,
}
logger := logging.NewLoggerWithConfig(config)
Logging Levels
logger.WithContext(ctx).Debug("Debug message", logging.Operation("debug_op"))
logger.WithContext(ctx).Info("Info message", logging.Operation("info_op"))
logger.WithContext(ctx).Warn("Warning message", logging.Operation("warn_op"))
logger.WithContext(ctx).Error(err, "Error message", logging.Operation("error_op"))
Context-Aware Logging

The logger automatically extracts context values:

ctx := context.Background()
ctx = logging.WithRequestID(ctx, "req-123")
ctx = logging.WithTenantID(ctx, "tenant-456")
ctx = logging.WithUserID(ctx, "user-789")
ctx = logging.WithClusterID(ctx, "cluster-abc")
ctx = logging.WithTraceID(ctx, "trace-789")
ctx = logging.WithResourceID(ctx, "resource-xyz")

// Kubernetes context helpers
ctx = logging.WithNamespace(ctx, "default")
ctx = logging.WithName(ctx, "my-resource")
ctx = logging.WithKind(ctx, "Pod")

logger.WithContext(ctx).Info("Request processed")
// Logs include: request_id, tenant_id, user_id, cluster_id, trace_id, resource_id automatically

Available context helpers:

  • WithRequestID(ctx, id) - Add request ID
  • WithTenantID(ctx, id) - Add tenant ID
  • WithUserID(ctx, id) - Add user ID
  • WithClusterID(ctx, id) - Add cluster ID
  • WithResourceID(ctx, id) - Add generic resource ID
  • WithNamespace(ctx, ns) - Add Kubernetes namespace
  • WithName(ctx, name) - Add Kubernetes resource name
  • WithKind(ctx, kind) - Add Kubernetes resource kind

Error Logging

Automatic Error Enhancement

Errors are automatically categorized and include stack traces in debug mode:

err := fmt.Errorf("user not found")
logger.WithContext(ctx).Error(err, "Operation failed",
    logging.Operation("fetch_user"),
    logging.ErrorCode("USER_NOT_FOUND"),
)
// Automatically adds: error_category, error_stack (if debug mode)
Error Categories

13 predefined categories:

  • validation, authentication, authorization
  • not_found, conflict, rate_limit
  • timeout, network, database
  • external, internal, config, temporary
Error Helpers
// Check if error is retryable
if logging.IsRetryableError(err) {
    // Retry logic
}

// Check error type
if logging.IsClientError(err) {
    // 4xx error handling
}
if logging.IsServerError(err) {
    // 5xx error handling
}

// Create error with code
err := logging.NewErrorWithCode("USER_NOT_FOUND", "User not found")
code := logging.ExtractErrorCode(err)

Performance Logging

Performance Logger
perfLogger := logging.NewPerformanceLogger(logger)

// HTTP request
perfLogger.LogRequestProcessed(ctx, "user_list",
    duration,
    200,
    requestSize,
    responseSize,
    logging.RequestID(requestID),
)

// Database operation
perfLogger.LogDBCall(ctx, "select_users", query, duration, rowsAffected, err)

// Cache operation
perfLogger.LogCacheOperation(ctx, "get", cacheKey, hit, duration, err)

// External API call
perfLogger.LogExternalAPICall(ctx, "payment-service", "/process", "POST",
    statusCode, duration, requestSize, responseSize, err,
)

// Message queue operation
perfLogger.LogMessageQueueOperation(ctx, "publish", "event-queue",
    messageCount, duration, err,
)

// File operation
perfLogger.LogFileOperation(ctx, "read", "/path/to/file", fileSize, duration, err)

// Measure duration
err := perfLogger.MeasureDuration(ctx, "complex_operation", func() error {
    // Do work
    return nil
})

// Measure duration with custom fields
err := perfLogger.MeasureDurationWithFields(ctx, "operation", []zap.Field{
    logging.String("custom_field", "value"),
}, func() error {
    // Do work
    return nil
})

Audit Logging

Audit Logger
auditLogger := logging.NewAuditLogger(logger)

// User actions
auditLogger.LogUserAction(ctx, logging.AuditActionCreate, "user", userID,
    logging.AuditResultSuccess,
    logging.UserID(userID, true),
)

// Authentication
auditLogger.LogLogin(ctx, logging.AuditResultSuccess, ipAddress, userAgent)

// Authorization decisions
auditLogger.LogAuthorization(ctx, "resource", resourceID, "read",
    logging.AuditResultDenied,
)

// Configuration changes
auditLogger.LogConfigChange(ctx, "max_connections", oldValue, newValue)

// Data access (PII)
auditLogger.LogDataAccess(ctx, "user_profile", userID)

Sampling and Rate Limiting

For high-volume operations, use sampled logging:

samplerConfig := logging.DefaultSamplerConfig()
rateLimiterConfig := logging.DefaultRateLimiterConfig()

sampledLogger := logging.NewSampledLogger(logger, samplerConfig, rateLimiterConfig)

// Info logs are sampled (10% by default)
sampledLogger.Info("Request processed", true, "http_request",
    logging.HTTPStatus(200),
)

// Errors are always logged (not sampled)
sampledLogger.Error(err, "Request failed", "http_error",
    logging.HTTPStatus(500),
)

Security Features

Data Masking
// UUID masking
masked := logging.MaskUUID("123e4567-e89b-12d3-a456-426614174000")
// Result: "123e4567-e89b-****-a456-426614174000"

// Token masking
masked := logging.MaskToken("eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...")
// Result: "eyJh****...J9"

// Email masking
masked := logging.MaskEmail("user@example.com")
// Result: "u***@example.com"

// IP masking
masked := logging.MaskIP("192.168.1.100")
// Result: "192.168.1.***"
Field Helpers with Masking
// Automatically masks UUIDs
logging.TenantID(tenantID, true)  // maskUUID=true
logging.UserID(userID, true)      // maskUUID=true

// Automatically sanitizes SQL
logging.DBQuery("SELECT * FROM users WHERE password = 'secret'")
// Result: sanitized query with masked sensitive values

Structured Fields

Standard field helpers following Kubernetes logging conventions:

// Request/Correlation
logging.RequestID(id)
logging.TraceID(id)
logging.SpanID(id)

// Resource identification
logging.TenantID(id, maskUUID)
logging.UserID(id, maskUUID)
logging.ClusterID(id)
logging.ResourceID(id)
logging.ResourceType(type)

// HTTP
logging.HTTPMethod(method)
logging.HTTPPath(path)
logging.HTTPStatus(status)

// Performance
logging.Latency(duration)
logging.LatencyMs(ms)

// Kubernetes
logging.Namespace(ns)
logging.Pod(pod)
logging.Node(node)
logging.Kind(kind)
logging.Name(name)

// Operations
logging.Operation(op)
logging.ErrorCode(code)
logging.Component(name)

// Additional helpers
logging.RetryCount(count)
logging.CacheHit(hit)
logging.RemoteAddr(addr)
logging.UserAgent(ua)
logging.DBQuery(query)      // Automatically sanitizes SQL
logging.DBDurationMs(ms)
logging.Strings(key, values)
logging.Duration(key, duration)

Environment Configuration

Environment Variables
  • LOG_LEVEL - Log level: debug, info, warn, error (default: info)
  • DEVELOPMENT - Set to "true" for development mode
  • ENV - Set to "development" for development mode
  • DEBUG - Set to "true" for debug mode (enables stack traces)
Development vs Production

Development Mode (pretty console logs):

  • Colored output
  • Human-readable format
  • Stack traces for errors
  • Caller information

Production Mode (JSON logs):

  • Structured JSON output
  • Optimized for log aggregation
  • Minimal verbosity
  • Stack traces only if explicitly enabled

Best Practices

1. Always Use Context
// ✅ Good
logger.WithContext(ctx).Info("Operation completed", logging.Operation("op"))

// ❌ Bad
logger.Info("Operation completed") // Missing context
2. Use Structured Fields
// ✅ Good
logger.WithContext(ctx).Info("User created",
    logging.UserID(userID, true),
    logging.ResourceType("user"),
    logging.Operation("create_user"),
)

// ❌ Bad
logger.WithContext(ctx).Info(fmt.Sprintf("User %s created", userID))
3. Error Logging
// ✅ Good
logger.WithContext(ctx).Error(err, "Failed to create user",
    logging.Operation("create_user"),
    logging.ErrorCode("USER_CREATE_FAILED"),
)

// ❌ Bad
logger.WithContext(ctx).Error(err, fmt.Sprintf("Failed: %v", err))
4. Performance Logging
// ✅ Good - use PerformanceLogger for standard metrics
perfLogger.LogRequestProcessed(ctx, "user_list", duration, statusCode, reqSize, respSize)

// ❌ Bad - manual logging without standardization
logger.Info(fmt.Sprintf("Request took %v", duration))
5. Security
// ✅ Good - masks sensitive data
logger.WithContext(ctx).Info("User logged in",
    logging.UserID(userID, true),      // Masked
    logging.RemoteAddr(logging.MaskIP(ip)), // Masked
)

// ❌ Bad - logs sensitive data
logger.WithContext(ctx).Info("User logged in",
    logging.String("user_id", userID),  // Not masked!
    logging.String("token", token),     // Exposed!
)
6. Audit Logging
// ✅ Good - use AuditLogger for security-sensitive operations
auditLogger.LogUserAction(ctx, logging.AuditActionDelete, "user", userID,
    logging.AuditResultSuccess,
)

// ❌ Bad - regular logging for audit events
logger.Info("User deleted") // Missing audit context

Integration with OpenTelemetry

The logger automatically extracts trace and span IDs from OpenTelemetry context:

// After initializing OpenTelemetry
import "github.com/kube-zen/zen-sdk/pkg/observability"

observability.InitWithDefaults(ctx, "my-service")

// Logger automatically includes trace_id and span_id in logs
logger.WithContext(ctx).Info("Processing request")
// Logs include: trace_id, span_id (extracted from OTEL context)

Examples

See:

  • performance_example.go - Performance logging examples
  • sampling_example.go - Sampling and rate limiting examples
  • PATTERNS.md - Component-specific patterns and examples
  • INTEGRATION.md - Integration with monitoring and log aggregation
  • Component codebases for real-world usage

Migration Guide

From Old Logging

If migrating from older logging implementations:

  1. Replace logger.Info(ctx, msg, fields...) with logger.WithContext(ctx).Info(msg, fields...)
  2. Replace error logging: logger.Error(ctx, msg, err)logger.WithContext(ctx).Error(err, msg)
  3. Update field helpers to use logging.* functions (e.g., logging.Operation())
  4. Use logging.String("key", value) instead of custom field functions

License

Apache 2.0

Documentation

Overview

Package logging provides structured logging configuration for Kubernetes controllers. It standardizes logging across all Zen tools using zap, providing consistent formatting, component context, and development mode detection.

Usage:

logger := logging.NewLogger("my-controller")
logger.Info("Controller started", "namespace", "default")
logger.Error(err, "Reconciliation failed", "resource", "my-resource")

The logger automatically includes component name context and adapts to development or production environments based on the LOG_DEV environment variable.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AlertFlag

func AlertFlag(shouldAlert bool) zap.Field

AlertFlag creates an alert field (marks logs that should trigger alerts)

func AuditActionField

func AuditActionField(action AuditAction) zap.Field

AuditActionField creates an audit_action field

func AuditResultField

func AuditResultField(result AuditResult) zap.Field

AuditResultField creates an audit_result field

func AuditTypeField

func AuditTypeField(auditType string) zap.Field

AuditTypeField creates an audit_type field

func Bool

func Bool(key string, value bool) zap.Field

Bool creates a custom bool field

func CacheHit

func CacheHit(hit bool) zap.Field

CacheHit creates a cache_hit field

func ClusterID

func ClusterID(id string) zap.Field

ClusterID creates a cluster_id field (generic resource identifier)

func Component

func Component(name string) zap.Field

Component creates a component field (standard Kubernetes pattern)

func ConcurrentOperations

func ConcurrentOperations(count int) zap.Field

ConcurrentOperations creates a concurrent_operations field

func ConfigKeyField

func ConfigKeyField(key string) zap.Field

ConfigKeyField creates a config_key field (for config change audits)

func DBDurationMs

func DBDurationMs(ms int64) zap.Field

DBDurationMs creates a db_duration_ms field

func DBQuery

func DBQuery(query string) zap.Field

DBQuery creates a db_query field with SQL sanitization

func DataTypeField

func DataTypeField(dataType string) zap.Field

DataTypeField creates a data_type field (for data access audits)

func Duration

func Duration(key string, value time.Duration) zap.Field

Duration creates a custom duration field (stored as milliseconds)

func Error

func Error(err error) zap.Field

Error creates an error field

func ErrorCategoryField

func ErrorCategoryField(category ErrorCategory) zap.Field

ErrorCategoryField creates a zap field for error category

func ErrorCode

func ErrorCode(code string) zap.Field

ErrorCode creates an error_code field

func ErrorFields

func ErrorFields(err error, errorCode string) []zap.Field

ErrorFields extracts all error-related fields for logging This is a convenience function that extracts category, code, and optionally stack trace

func ErrorStackField

func ErrorStackField(stack string) zap.Field

ErrorStackField creates a zap field for error stack trace (only in debug mode)

func EventType

func EventType(eventType string) zap.Field

EventType creates an event_type field (for log classification)

func ExternalEndpoint

func ExternalEndpoint(endpoint string) zap.Field

ExternalEndpoint creates an external_endpoint field

func ExternalService

func ExternalService(service string) zap.Field

ExternalService creates an external_service field

func ExtractErrorCode

func ExtractErrorCode(err error) string

ExtractErrorCode extracts the error code from an error if it implements ErrorWithCode

func ExtractTraceContext

func ExtractTraceContext(req *http.Request) context.Context

ExtractTraceContext extracts trace context from HTTP request headers Supports W3C TraceContext (via OpenTelemetry) and custom headers

func FilePath

func FilePath(path string) zap.Field

FilePath creates a file_path field (be careful with sensitive paths)

func FileSizeBytes

func FileSizeBytes(size int64) zap.Field

FileSizeBytes creates a file_size_bytes field

func Float64

func Float64(key string, value float64) zap.Field

Float64 creates a custom float64 field

func GetClusterID

func GetClusterID(ctx context.Context) string

GetClusterID retrieves cluster ID from context

func GetRequestID

func GetRequestID(ctx context.Context) string

GetRequestID retrieves request ID from context

func GetResourceID

func GetResourceID(ctx context.Context) string

GetResourceID retrieves a generic resource ID from context

func GetSpanID

func GetSpanID(ctx context.Context) string

GetSpanID retrieves span ID from context (tries OpenTelemetry first, then custom key)

func GetStackTrace

func GetStackTrace(skip int) string

GetStackTrace returns the stack trace for the current goroutine Only includes stack frames up to the caller (skips logging package frames)

func GetTenantID

func GetTenantID(ctx context.Context) string

GetTenantID retrieves tenant ID from context

func GetTraceID

func GetTraceID(ctx context.Context) string

GetTraceID retrieves trace ID from context (tries OpenTelemetry first, then custom key)

func GetUserID

func GetUserID(ctx context.Context) string

GetUserID retrieves user ID from context

func HTTPMethod

func HTTPMethod(method string) zap.Field

HTTPMethod creates an http_method field

func HTTPPath

func HTTPPath(path string) zap.Field

HTTPPath creates an http_path field

func HTTPStatus

func HTTPStatus(status int) zap.Field

HTTPStatus creates an http_status field

func HealthCheckHealthy

func HealthCheckHealthy(healthy bool) zap.Field

HealthCheckHealthy creates a health_check_healthy field

func HealthCheckName

func HealthCheckName(name string) zap.Field

HealthCheckName creates a health_check_name field

func Int

func Int(key string, value int) zap.Field

Int creates a custom int field

func Int64

func Int64(key string, value int64) zap.Field

Int64 creates a custom int64 field

func IsClientError

func IsClientError(err error) bool

IsClientError checks if an error is a client error (4xx)

func IsRetryableError

func IsRetryableError(err error) bool

IsRetryableError checks if an error is likely retryable based on its category

func IsServerError

func IsServerError(err error) bool

IsServerError checks if an error is a server error (5xx)

func Kind

func Kind(kind string) zap.Field

Kind creates a kind field (Kubernetes resource kind)

func Latency

func Latency(d time.Duration) zap.Field

Latency creates a latency_ms field from duration

func LatencyMs

func LatencyMs(ms int64) zap.Field

LatencyMs creates a latency_ms field

func MaskEmail

func MaskEmail(email string) string

MaskEmail masks an email address (shows first 3 chars + domain) Security: Protects PII in logs

func MaskIP

func MaskIP(ip string) string

MaskIP masks IP addresses (shows first octet) Security: Protects client IP addresses

func MaskToken

func MaskToken(token string) string

MaskToken masks a token/API key (shows first 4 chars) Security: Prevents leaking credentials in logs

func MaskUUID

func MaskUUID(uuid string) string

MaskUUID masks a UUID for logging (shows first 8 chars) Security: Prevents leaking full UUIDs in logs

func MessageCount

func MessageCount(count int) zap.Field

MessageCount creates a message_count field

func MetricName

func MetricName(name string) zap.Field

MetricName creates a metric_name field

func MetricUnit

func MetricUnit(unit string) zap.Field

MetricUnit creates a metric_unit field

func MetricValue

func MetricValue(value float64) zap.Field

MetricValue creates a metric_value field

func Name

func Name(name string) zap.Field

Name creates a name field (Kubernetes resource name)

func Namespace

func Namespace(ns string) zap.Field

Namespace creates a namespace field (standard Kubernetes pattern)

func NewErrorWithCode

func NewErrorWithCode(code, message string) error

NewErrorWithCode creates a new error with an associated code

func NewErrorWithCodeAndCause

func NewErrorWithCodeAndCause(code, message string, cause error) error

NewErrorWithCodeAndCause creates a new error with code and underlying cause

func Node

func Node(node string) zap.Field

Node creates a node field (standard Kubernetes pattern)

func Operation

func Operation(op string) zap.Field

Operation creates an operation field (standard Kubernetes pattern)

func PermissionField

func PermissionField(permission string) zap.Field

PermissionField creates a permission field (for authorization audits)

func Pod

func Pod(pod string) zap.Field

Pod creates a pod field (standard Kubernetes pattern)

func PropagateTraceHeaders

func PropagateTraceHeaders(ctx context.Context, req *http.Request)

PropagateTraceHeaders adds trace headers to HTTP requests for unified distributed tracing Supports W3C TraceContext format and custom headers

func QueueName

func QueueName(name string) zap.Field

QueueName creates a queue_name field

func RedactPassword

func RedactPassword(password string) string

RedactPassword ensures passwords are never logged Security: Hard redaction for passwords

func RedactSecret

func RedactSecret(secret string) string

RedactSecret ensures secrets are never logged Security: Hard redaction for secrets

func RemoteAddr

func RemoteAddr(addr string) zap.Field

RemoteAddr creates a remote_addr field (IP address should be masked if sensitive)

func RequestID

func RequestID(id string) zap.Field

RequestID creates a request_id field (standard HTTP correlation)

func RequestSizeBytes

func RequestSizeBytes(size int64) zap.Field

RequestSizeBytes creates a request_size_bytes field

func ResourceID

func ResourceID(id string) zap.Field

ResourceID creates a resource_id field (generic resource identifier)

func ResourceType

func ResourceType(resourceType string) zap.Field

ResourceType creates a resource_type field

func ResponseSizeBytes

func ResponseSizeBytes(size int64) zap.Field

ResponseSizeBytes creates a response_size_bytes field

func RetryCount

func RetryCount(count int) zap.Field

RetryCount creates a retry_count field

func RowsAffected

func RowsAffected(count int64) zap.Field

RowsAffected creates a rows_affected field

func SanitizeSQL

func SanitizeSQL(query string) string

SanitizeSQL sanitizes SQL queries for logging (removes values, keeps structure) Security: Prevents leaking sensitive data from SQL queries

func Severity

func Severity(severity string) zap.Field

Severity creates a severity field (for critical events)

func SpanID

func SpanID(id string) zap.Field

SpanID creates a span_id field (W3C TraceContext)

func String

func String(key, value string) zap.Field

String creates a custom string field

func Strings

func Strings(key string, values []string) zap.Field

Strings creates a custom string slice field

func TenantID

func TenantID(id string, maskUUID bool) zap.Field

TenantID creates a tenant_id field with optional masking maskUUID: if true, applies UUID masking for security

func ThroughputBytesPerSecond

func ThroughputBytesPerSecond(throughput float64) zap.Field

ThroughputBytesPerSecond creates a throughput_bytes_per_second field

func TraceID

func TraceID(id string) zap.Field

TraceID creates a trace_id field (W3C TraceContext)

func UserAgent

func UserAgent(ua string) zap.Field

UserAgent creates a user_agent field

func UserID

func UserID(id string, maskUUID bool) zap.Field

UserID creates a user_id field with optional masking

func WithClusterID

func WithClusterID(ctx context.Context, clusterID string) context.Context

WithClusterID adds cluster ID to context

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds request ID to context

func WithResourceID

func WithResourceID(ctx context.Context, resourceID string) context.Context

WithResourceID adds a generic resource ID to context (for multi-tenant systems)

func WithSpanID

func WithSpanID(ctx context.Context, spanID string) context.Context

WithSpanID adds span ID to context (W3C TraceContext)

func WithTenantID

func WithTenantID(ctx context.Context, tenantID string) context.Context

WithTenantID adds tenant ID to context

func WithTraceID

func WithTraceID(ctx context.Context, traceID string) context.Context

WithTraceID adds trace ID to context (W3C TraceContext)

func WithUserID

func WithUserID(ctx context.Context, userID string) context.Context

WithUserID adds user ID to context

func WrapError

func WrapError(err error, msg string) error

WrapError wraps an error with additional context Returns a new error that includes the original error and context

func WrapErrorf

func WrapErrorf(err error, format string, args ...interface{}) error

WrapErrorf wraps an error with formatted additional context

Types

type AuditAction

type AuditAction string

AuditAction represents the type of action being audited

const (
	// AuditActionCreate represents a create operation
	AuditActionCreate AuditAction = "create"
	// AuditActionRead represents a read/access operation
	AuditActionRead AuditAction = "read"
	// AuditActionUpdate represents an update operation
	AuditActionUpdate AuditAction = "update"
	// AuditActionDelete represents a delete operation
	AuditActionDelete AuditAction = "delete"
	// AuditActionLogin represents a login/authentication operation
	AuditActionLogin AuditAction = "login"
	// AuditActionLogout represents a logout operation
	AuditActionLogout AuditAction = "logout"
	// AuditActionAuthorize represents an authorization decision
	AuditActionAuthorize AuditAction = "authorize"
	// AuditActionConfigChange represents a configuration change
	AuditActionConfigChange AuditAction = "config_change"
	// AuditActionDataAccess represents access to sensitive data
	AuditActionDataAccess AuditAction = "data_access"
)

type AuditLogger

type AuditLogger struct {
	// contains filtered or unexported fields
}

AuditLogger provides standardized audit logging helpers for security-sensitive operations

func NewAuditLogger

func NewAuditLogger(logger *Logger) *AuditLogger

NewAuditLogger creates a new audit logger

func (*AuditLogger) LogAuthorization

func (al *AuditLogger) LogAuthorization(ctx context.Context, resourceType, resourceID, permission string, result AuditResult, fields ...zap.Field)

LogAuthorization logs an authorization decision

func (*AuditLogger) LogConfigChange

func (al *AuditLogger) LogConfigChange(ctx context.Context, configKey string, oldValue, newValue interface{}, fields ...zap.Field)

LogConfigChange logs a configuration change

func (*AuditLogger) LogDataAccess

func (al *AuditLogger) LogDataAccess(ctx context.Context, dataType, resourceID string, fields ...zap.Field)

LogDataAccess logs access to sensitive data (PII, etc.)

func (*AuditLogger) LogLogin

func (al *AuditLogger) LogLogin(ctx context.Context, result AuditResult, ipAddress, userAgent string, fields ...zap.Field)

LogLogin logs a login/authentication event

func (*AuditLogger) LogResourceOperation

func (al *AuditLogger) LogResourceOperation(ctx context.Context, action AuditAction, resourceType, resourceID string, result AuditResult, fields ...zap.Field)

LogResourceOperation logs a create/update/delete operation on a resource

func (*AuditLogger) LogUserAction

func (al *AuditLogger) LogUserAction(ctx context.Context, action AuditAction, resourceType, resourceID string, result AuditResult, fields ...zap.Field)

LogUserAction logs a user action for audit purposes

type AuditResult

type AuditResult string

AuditResult represents the result of an audit action

const (
	// AuditResultSuccess represents a successful operation
	AuditResultSuccess AuditResult = "success"
	// AuditResultFailure represents a failed operation
	AuditResultFailure AuditResult = "failure"
	// AuditResultDenied represents a denied operation
	AuditResultDenied AuditResult = "denied"
)

type EnhancedErrorLogger

type EnhancedErrorLogger struct {
	// contains filtered or unexported fields
}

EnhancedErrorLogger is a helper for logging errors with enhanced context

func NewEnhancedErrorLogger

func NewEnhancedErrorLogger(logger *Logger) *EnhancedErrorLogger

NewEnhancedErrorLogger creates a new enhanced error logger

func (*EnhancedErrorLogger) LogError

func (e *EnhancedErrorLogger) LogError(err error, msg string, errorCode string, fields ...zap.Field)

LogError logs an error with enhanced context

type ErrorCategory

type ErrorCategory string

ErrorCategory represents the category of an error

const (
	// ErrorCategoryUnknown represents an unknown/unclassified error
	ErrorCategoryUnknown ErrorCategory = "unknown"
	// ErrorCategoryValidation represents a validation error (user input)
	ErrorCategoryValidation ErrorCategory = "validation"
	// ErrorCategoryAuthentication represents an authentication error
	ErrorCategoryAuthentication ErrorCategory = "authentication"
	// ErrorCategoryAuthorization represents an authorization error (permissions)
	ErrorCategoryAuthorization ErrorCategory = "authorization"
	// ErrorCategoryNotFound represents a resource not found error
	ErrorCategoryNotFound ErrorCategory = "not_found"
	// ErrorCategoryConflict represents a conflict error (e.g., duplicate resource)
	ErrorCategoryConflict ErrorCategory = "conflict"
	// ErrorCategoryRateLimit represents a rate limiting error
	ErrorCategoryRateLimit ErrorCategory = "rate_limit"
	// ErrorCategoryTimeout represents a timeout error
	ErrorCategoryTimeout ErrorCategory = "timeout"
	// ErrorCategoryNetwork represents a network error
	ErrorCategoryNetwork ErrorCategory = "network"
	// ErrorCategoryDatabase represents a database error
	ErrorCategoryDatabase ErrorCategory = "database"
	// ErrorCategoryExternal represents an external service error
	ErrorCategoryExternal ErrorCategory = "external"
	// ErrorCategoryInternal represents an internal/system error
	ErrorCategoryInternal ErrorCategory = "internal"
	// ErrorCategoryConfig represents a configuration error
	ErrorCategoryConfig ErrorCategory = "config"
	// ErrorCategoryTemporary represents a temporary/transient error
	ErrorCategoryTemporary ErrorCategory = "temporary"
)

func CategorizeError

func CategorizeError(err error) ErrorCategory

CategorizeError attempts to categorize an error based on its message and type

type ErrorContext

type ErrorContext struct {
	Category   ErrorCategory
	Code       string
	Message    string
	Stack      string
	WrappedErr error
	Fields     []zap.Field
}

ErrorContext holds enhanced error context information

func ExtractErrorContext

func ExtractErrorContext(err error, skipStack int) ErrorContext

ExtractErrorContext extracts enhanced context from an error

func (*ErrorContext) WithZapFields

func (ctx *ErrorContext) WithZapFields(fields ...zap.Field) *ErrorContext

WithZapFields adds zap fields to an error context for structured logging

type ErrorWithCode

type ErrorWithCode struct {
	Code    string
	Message string
	Err     error
}

ErrorWithCode creates an error with an associated error code

func (*ErrorWithCode) Error

func (e *ErrorWithCode) Error() string

func (*ErrorWithCode) Unwrap

func (e *ErrorWithCode) Unwrap() error

type Field

type Field = zap.Field

Field is a zap.Field for backward compatibility and convenience

type Logger

type Logger struct {
	*zap.Logger
	// contains filtered or unexported fields
}

Logger wraps zap.Logger with component-specific context

func NewLogger

func NewLogger(componentName string) *Logger

NewLogger creates a new structured logger for a component with default configuration

func NewLoggerWithConfig

func NewLoggerWithConfig(config LoggerConfig) *Logger

NewLoggerWithConfig creates a new structured logger with custom configuration

func (*Logger) Debug

func (l *Logger) Debug(msg string, fields ...zap.Field)

Debug logs a debug message

func (*Logger) DebugC

func (l *Logger) DebugC(ctx context.Context, msg string, fields ...zap.Field)

DebugC logs a debug message with context

func (*Logger) Error

func (l *Logger) Error(err error, msg string, fields ...zap.Field)

Error logs an error message with enhanced context If fields don't already include error_code or error_category, they are automatically added

func (*Logger) ErrorC

func (l *Logger) ErrorC(ctx context.Context, err error, msg string, fields ...zap.Field)

ErrorC logs an error message with context

func (*Logger) Info

func (l *Logger) Info(msg string, fields ...zap.Field)

Info logs an info message

func (*Logger) InfoC

func (l *Logger) InfoC(ctx context.Context, msg string, fields ...zap.Field)

InfoC logs an info message with context (extracts context values automatically)

func (*Logger) Warn

func (l *Logger) Warn(msg string, fields ...zap.Field)

Warn logs a warning message

func (*Logger) WarnC

func (l *Logger) WarnC(ctx context.Context, msg string, fields ...zap.Field)

WarnC logs a warning message with context

func (*Logger) WithComponent

func (l *Logger) WithComponent(component string) *Logger

WithComponent adds component name to log context

func (*Logger) WithContext

func (l *Logger) WithContext(ctx context.Context) *Logger

WithContext creates a logger with context values automatically extracted Extracts standard context values: request_id, tenant_id, user_id, cluster_id, trace_id, span_id This follows Kubernetes logging best practices for context propagation

func (*Logger) WithField

func (l *Logger) WithField(key string, value interface{}) *Logger

WithField adds a field to the log context

func (*Logger) WithFields

func (l *Logger) WithFields(fields map[string]interface{}) *Logger

WithFields adds multiple fields to the log context

type LoggerConfig

type LoggerConfig struct {
	// ComponentName is the name of the component
	ComponentName string
	// Development enables development mode (pretty console logs, stack traces)
	Development bool
	// LogLevel sets the minimum log level (debug, info, warn, error)
	// If empty, uses environment variable LOG_LEVEL or defaults to info
	LogLevel string
	// EnableStackTraces enables stack traces for errors (even in production)
	EnableStackTraces bool
}

LoggerConfig holds configuration for logger creation

type MonitoringLogger

type MonitoringLogger struct {
	// contains filtered or unexported fields
}

MonitoringLogger provides logging helpers that integrate with monitoring systems These helpers ensure logs contain fields that are useful for metrics extraction

func NewMonitoringLogger

func NewMonitoringLogger(logger *Logger) *MonitoringLogger

NewMonitoringLogger creates a new monitoring logger

func (*MonitoringLogger) LogCounter

func (ml *MonitoringLogger) LogCounter(ctx context.Context, counterName string, increment int64, fields ...zap.Field)

LogCounter logs a counter increment event

func (*MonitoringLogger) LogCriticalEvent

func (ml *MonitoringLogger) LogCriticalEvent(ctx context.Context, eventName, severity string, fields ...zap.Field)

LogCriticalEvent logs a critical event that should trigger alerts

func (*MonitoringLogger) LogGauge

func (ml *MonitoringLogger) LogGauge(ctx context.Context, gaugeName string, value float64, fields ...zap.Field)

LogGauge logs a gauge value (current state)

func (*MonitoringLogger) LogHealthCheck

func (ml *MonitoringLogger) LogHealthCheck(ctx context.Context, checkName string, healthy bool, duration time.Duration, err error, fields ...zap.Field)

LogHealthCheck logs a health check result

func (*MonitoringLogger) LogHistogram

func (ml *MonitoringLogger) LogHistogram(ctx context.Context, histogramName string, value float64, bucket string, fields ...zap.Field)

LogHistogram logs a histogram value for latency/request size distribution

func (*MonitoringLogger) LogMetric

func (ml *MonitoringLogger) LogMetric(ctx context.Context, metricName string, value float64, unit string, fields ...zap.Field)

LogMetric logs a metric event that can be extracted for monitoring Use this for custom metrics that aren't covered by standard performance logging

type PerformanceLogger

type PerformanceLogger struct {
	// contains filtered or unexported fields
}

PerformanceLogger provides standardized performance logging helpers

func NewPerformanceLogger

func NewPerformanceLogger(logger *Logger) *PerformanceLogger

NewPerformanceLogger creates a new performance logger

func (*PerformanceLogger) LogCacheOperation

func (pl *PerformanceLogger) LogCacheOperation(ctx context.Context, operation, key string, hit bool, duration time.Duration, err error, fields ...zap.Field)

LogCacheOperation logs a cache operation with standardized fields

func (*PerformanceLogger) LogDBCall

func (pl *PerformanceLogger) LogDBCall(ctx context.Context, operation, query string, duration time.Duration, rowsAffected int64, err error, fields ...zap.Field)

LogDBCall logs a database operation with standardized fields

func (*PerformanceLogger) LogExternalAPICall

func (pl *PerformanceLogger) LogExternalAPICall(ctx context.Context, service, endpoint, method string, statusCode int, duration time.Duration, requestSize, responseSize int64, err error, fields ...zap.Field)

LogExternalAPICall logs an external API call with standardized fields

func (*PerformanceLogger) LogFileOperation

func (pl *PerformanceLogger) LogFileOperation(ctx context.Context, operation, filePath string, fileSize int64, duration time.Duration, err error, fields ...zap.Field)

LogFileOperation logs a file operation with standardized fields

func (*PerformanceLogger) LogMessageQueueOperation

func (pl *PerformanceLogger) LogMessageQueueOperation(ctx context.Context, operation, queueName string, messageCount int, duration time.Duration, err error, fields ...zap.Field)

LogMessageQueueOperation logs a message queue operation with standardized fields

func (*PerformanceLogger) LogRequestProcessed

func (pl *PerformanceLogger) LogRequestProcessed(ctx context.Context, operation string, duration time.Duration, statusCode int, requestSize, responseSize int64, fields ...zap.Field)

LogRequestProcessed logs a processed request with standardized fields

func (*PerformanceLogger) MeasureDuration

func (pl *PerformanceLogger) MeasureDuration(ctx context.Context, operation string, fn func() error) error

MeasureDuration is a helper function that measures duration and logs it

func (*PerformanceLogger) MeasureDurationWithFields

func (pl *PerformanceLogger) MeasureDurationWithFields(ctx context.Context, operation string, fields []zap.Field, fn func() error) error

MeasureDurationWithFields is like MeasureDuration but accepts additional fields

type RateLimiter

type RateLimiter struct {
	// contains filtered or unexported fields
}

RateLimiter provides rate limiting for log entries to prevent log flooding

func NewRateLimiter

func NewRateLimiter(config RateLimiterConfig) *RateLimiter

NewRateLimiter creates a new rate limiter

func (*RateLimiter) Allow

func (rl *RateLimiter) Allow(key string) bool

Allow checks if a log entry with the given key should be allowed (not rate limited) Returns true if the log should be allowed, false if it should be rate limited

type RateLimiterConfig

type RateLimiterConfig struct {
	// MaxLogsPerSecond is the maximum number of logs allowed per second per key
	MaxLogsPerSecond int

	// WindowSize is the time window for rate limiting (default: 1 second)
	WindowSize time.Duration

	// CleanupInterval is how often to clean up old entries (default: 1 minute)
	CleanupInterval time.Duration
}

RateLimiterConfig configures rate limiting behavior

func DefaultRateLimiterConfig

func DefaultRateLimiterConfig() RateLimiterConfig

DefaultRateLimiterConfig returns a config with sensible defaults

type SampledLogger

type SampledLogger struct {
	// contains filtered or unexported fields
}

SampledLogger wraps a Logger with sampling and rate limiting

func NewSampledLogger

func NewSampledLogger(logger *Logger, samplerConfig SamplerConfig, rateLimiterConfig RateLimiterConfig) *SampledLogger

NewSampledLogger creates a new sampled logger

func (*SampledLogger) Debug

func (sl *SampledLogger) Debug(msg string, key string, fields ...zap.Field)

Debug logs a debug message with sampling and rate limiting

func (*SampledLogger) Error

func (sl *SampledLogger) Error(err error, msg string, key string, fields ...zap.Field)

Error logs an error message with rate limiting (errors are not sampled)

func (*SampledLogger) Info

func (sl *SampledLogger) Info(msg string, isSuccess bool, key string, fields ...zap.Field)

Info logs an info message with sampling and rate limiting

func (*SampledLogger) Warn

func (sl *SampledLogger) Warn(msg string, key string, fields ...zap.Field)

Warn logs a warning message with rate limiting (warnings are not sampled)

type Sampler

type Sampler struct {
	// contains filtered or unexported fields
}

Sampler provides log sampling functionality

func NewSampler

func NewSampler(config SamplerConfig) *Sampler

NewSampler creates a new log sampler with the given configuration

func (*Sampler) ShouldLog

func (s *Sampler) ShouldLog(level zapcore.Level, isSuccess bool) bool

ShouldLog determines if a log entry should be logged based on sampling rate

type SamplerConfig

type SamplerConfig struct {
	// InfoSamplingRate is the rate at which INFO level logs are sampled (0.0-1.0)
	// 0.1 means 10% of INFO logs will be logged
	InfoSamplingRate float64

	// DebugSamplingRate is the rate at which DEBUG level logs are sampled (0.0-1.0)
	DebugSamplingRate float64

	// SuccessSamplingRate is the rate at which successful operation logs are sampled (0.0-1.0)
	// This applies to INFO logs for successful operations (e.g., 200 OK responses)
	SuccessSamplingRate float64

	// ErrorSamplingRate is the rate at which ERROR level logs are sampled (0.0-1.0)
	// Typically 1.0 (100%) - we want to log all errors
	ErrorSamplingRate float64

	// WarnSamplingRate is the rate at which WARN level logs are sampled (0.0-1.0)
	// Typically 1.0 (100%) - we want to log all warnings
	WarnSamplingRate float64
}

SamplerConfig configures log sampling behavior

func DefaultSamplerConfig

func DefaultSamplerConfig() SamplerConfig

DefaultSamplerConfig returns a config with sensible defaults

Jump to

Keyboard shortcuts

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