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 ¶
- func AlertFlag(shouldAlert bool) zap.Field
- func AuditActionField(action AuditAction) zap.Field
- func AuditResultField(result AuditResult) zap.Field
- func AuditTypeField(auditType string) zap.Field
- func Bool(key string, value bool) zap.Field
- func CacheHit(hit bool) zap.Field
- func ClusterID(id string) zap.Field
- func Component(name string) zap.Field
- func ConcurrentOperations(count int) zap.Field
- func ConfigKeyField(key string) zap.Field
- func DBDurationMs(ms int64) zap.Field
- func DBQuery(query string) zap.Field
- func DataTypeField(dataType string) zap.Field
- func Duration(key string, value time.Duration) zap.Field
- func Error(err error) zap.Field
- func ErrorCategoryField(category ErrorCategory) zap.Field
- func ErrorCode(code string) zap.Field
- func ErrorFields(err error, errorCode string) []zap.Field
- func ErrorStackField(stack string) zap.Field
- func EventType(eventType string) zap.Field
- func ExternalEndpoint(endpoint string) zap.Field
- func ExternalService(service string) zap.Field
- func ExtractErrorCode(err error) string
- func ExtractTraceContext(req *http.Request) context.Context
- func FilePath(path string) zap.Field
- func FileSizeBytes(size int64) zap.Field
- func Float64(key string, value float64) zap.Field
- func GetClusterID(ctx context.Context) string
- func GetRequestID(ctx context.Context) string
- func GetResourceID(ctx context.Context) string
- func GetSpanID(ctx context.Context) string
- func GetStackTrace(skip int) string
- func GetTenantID(ctx context.Context) string
- func GetTraceID(ctx context.Context) string
- func GetUserID(ctx context.Context) string
- func HTTPMethod(method string) zap.Field
- func HTTPPath(path string) zap.Field
- func HTTPStatus(status int) zap.Field
- func HealthCheckHealthy(healthy bool) zap.Field
- func HealthCheckName(name string) zap.Field
- func Int(key string, value int) zap.Field
- func Int64(key string, value int64) zap.Field
- func IsClientError(err error) bool
- func IsRetryableError(err error) bool
- func IsServerError(err error) bool
- func Kind(kind string) zap.Field
- func Latency(d time.Duration) zap.Field
- func LatencyMs(ms int64) zap.Field
- func MaskEmail(email string) string
- func MaskIP(ip string) string
- func MaskToken(token string) string
- func MaskUUID(uuid string) string
- func MessageCount(count int) zap.Field
- func MetricName(name string) zap.Field
- func MetricUnit(unit string) zap.Field
- func MetricValue(value float64) zap.Field
- func Name(name string) zap.Field
- func Namespace(ns string) zap.Field
- func NewErrorWithCode(code, message string) error
- func NewErrorWithCodeAndCause(code, message string, cause error) error
- func Node(node string) zap.Field
- func Operation(op string) zap.Field
- func PermissionField(permission string) zap.Field
- func Pod(pod string) zap.Field
- func PropagateTraceHeaders(ctx context.Context, req *http.Request)
- func QueueName(name string) zap.Field
- func RedactPassword(password string) string
- func RedactSecret(secret string) string
- func RemoteAddr(addr string) zap.Field
- func RequestID(id string) zap.Field
- func RequestSizeBytes(size int64) zap.Field
- func ResourceID(id string) zap.Field
- func ResourceType(resourceType string) zap.Field
- func ResponseSizeBytes(size int64) zap.Field
- func RetryCount(count int) zap.Field
- func RowsAffected(count int64) zap.Field
- func SanitizeSQL(query string) string
- func Severity(severity string) zap.Field
- func SpanID(id string) zap.Field
- func String(key, value string) zap.Field
- func Strings(key string, values []string) zap.Field
- func TenantID(id string, maskUUID bool) zap.Field
- func ThroughputBytesPerSecond(throughput float64) zap.Field
- func TraceID(id string) zap.Field
- func UserAgent(ua string) zap.Field
- func UserID(id string, maskUUID bool) zap.Field
- func WithClusterID(ctx context.Context, clusterID string) context.Context
- func WithRequestID(ctx context.Context, requestID string) context.Context
- func WithResourceID(ctx context.Context, resourceID string) context.Context
- func WithSpanID(ctx context.Context, spanID string) context.Context
- func WithTenantID(ctx context.Context, tenantID string) context.Context
- func WithTraceID(ctx context.Context, traceID string) context.Context
- func WithUserID(ctx context.Context, userID string) context.Context
- func WrapError(err error, msg string) error
- func WrapErrorf(err error, format string, args ...interface{}) error
- type AuditAction
- type AuditLogger
- func (al *AuditLogger) LogAuthorization(ctx context.Context, resourceType, resourceID, permission string, ...)
- func (al *AuditLogger) LogConfigChange(ctx context.Context, configKey string, oldValue, newValue interface{}, ...)
- func (al *AuditLogger) LogDataAccess(ctx context.Context, dataType, resourceID string, fields ...zap.Field)
- func (al *AuditLogger) LogLogin(ctx context.Context, result AuditResult, ipAddress, userAgent string, ...)
- func (al *AuditLogger) LogResourceOperation(ctx context.Context, action AuditAction, resourceType, resourceID string, ...)
- func (al *AuditLogger) LogUserAction(ctx context.Context, action AuditAction, resourceType, resourceID string, ...)
- type AuditResult
- type EnhancedErrorLogger
- type ErrorCategory
- type ErrorContext
- type ErrorWithCode
- type Field
- type Logger
- func (l *Logger) Debug(msg string, fields ...zap.Field)
- func (l *Logger) DebugC(ctx context.Context, msg string, fields ...zap.Field)
- func (l *Logger) Error(err error, msg string, fields ...zap.Field)
- func (l *Logger) ErrorC(ctx context.Context, err error, msg string, fields ...zap.Field)
- func (l *Logger) Info(msg string, fields ...zap.Field)
- func (l *Logger) InfoC(ctx context.Context, msg string, fields ...zap.Field)
- func (l *Logger) Warn(msg string, fields ...zap.Field)
- func (l *Logger) WarnC(ctx context.Context, msg string, fields ...zap.Field)
- func (l *Logger) WithComponent(component string) *Logger
- func (l *Logger) WithContext(ctx context.Context) *Logger
- func (l *Logger) WithField(key string, value interface{}) *Logger
- func (l *Logger) WithFields(fields map[string]interface{}) *Logger
- type LoggerConfig
- type MonitoringLogger
- func (ml *MonitoringLogger) LogCounter(ctx context.Context, counterName string, increment int64, fields ...zap.Field)
- func (ml *MonitoringLogger) LogCriticalEvent(ctx context.Context, eventName, severity string, fields ...zap.Field)
- func (ml *MonitoringLogger) LogGauge(ctx context.Context, gaugeName string, value float64, fields ...zap.Field)
- func (ml *MonitoringLogger) LogHealthCheck(ctx context.Context, checkName string, healthy bool, duration time.Duration, ...)
- func (ml *MonitoringLogger) LogHistogram(ctx context.Context, histogramName string, value float64, bucket string, ...)
- func (ml *MonitoringLogger) LogMetric(ctx context.Context, metricName string, value float64, unit string, ...)
- type PerformanceLogger
- func (pl *PerformanceLogger) LogCacheOperation(ctx context.Context, operation, key string, hit bool, duration time.Duration, ...)
- func (pl *PerformanceLogger) LogDBCall(ctx context.Context, operation, query string, duration time.Duration, ...)
- func (pl *PerformanceLogger) LogExternalAPICall(ctx context.Context, service, endpoint, method string, statusCode int, ...)
- func (pl *PerformanceLogger) LogFileOperation(ctx context.Context, operation, filePath string, fileSize int64, ...)
- func (pl *PerformanceLogger) LogMessageQueueOperation(ctx context.Context, operation, queueName string, messageCount int, ...)
- func (pl *PerformanceLogger) LogRequestProcessed(ctx context.Context, operation string, duration time.Duration, statusCode int, ...)
- func (pl *PerformanceLogger) MeasureDuration(ctx context.Context, operation string, fn func() error) error
- func (pl *PerformanceLogger) MeasureDurationWithFields(ctx context.Context, operation string, fields []zap.Field, fn func() error) error
- type RateLimiter
- type RateLimiterConfig
- type SampledLogger
- func (sl *SampledLogger) Debug(msg string, key string, fields ...zap.Field)
- func (sl *SampledLogger) Error(err error, msg string, key string, fields ...zap.Field)
- func (sl *SampledLogger) Info(msg string, isSuccess bool, key string, fields ...zap.Field)
- func (sl *SampledLogger) Warn(msg string, key string, fields ...zap.Field)
- type Sampler
- type SamplerConfig
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
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 ¶
AuditTypeField creates an audit_type field
func ConcurrentOperations ¶
ConcurrentOperations creates a concurrent_operations field
func ConfigKeyField ¶
ConfigKeyField creates a config_key field (for config change audits)
func DBDurationMs ¶
DBDurationMs creates a db_duration_ms field
func DataTypeField ¶
DataTypeField creates a data_type field (for data access audits)
func ErrorCategoryField ¶
func ErrorCategoryField(category ErrorCategory) zap.Field
ErrorCategoryField creates a zap field for error category
func ErrorFields ¶
ErrorFields extracts all error-related fields for logging This is a convenience function that extracts category, code, and optionally stack trace
func ErrorStackField ¶
ErrorStackField creates a zap field for error stack trace (only in debug mode)
func ExternalEndpoint ¶
ExternalEndpoint creates an external_endpoint field
func ExternalService ¶
ExternalService creates an external_service field
func ExtractErrorCode ¶
ExtractErrorCode extracts the error code from an error if it implements ErrorWithCode
func ExtractTraceContext ¶
ExtractTraceContext extracts trace context from HTTP request headers Supports W3C TraceContext (via OpenTelemetry) and custom headers
func FileSizeBytes ¶
FileSizeBytes creates a file_size_bytes field
func GetClusterID ¶
GetClusterID retrieves cluster ID from context
func GetRequestID ¶
GetRequestID retrieves request ID from context
func GetResourceID ¶
GetResourceID retrieves a generic resource ID from context
func GetSpanID ¶
GetSpanID retrieves span ID from context (tries OpenTelemetry first, then custom key)
func GetStackTrace ¶
GetStackTrace returns the stack trace for the current goroutine Only includes stack frames up to the caller (skips logging package frames)
func GetTenantID ¶
GetTenantID retrieves tenant ID from context
func GetTraceID ¶
GetTraceID retrieves trace ID from context (tries OpenTelemetry first, then custom key)
func HealthCheckHealthy ¶
HealthCheckHealthy creates a health_check_healthy field
func HealthCheckName ¶
HealthCheckName creates a health_check_name field
func IsClientError ¶
IsClientError checks if an error is a client error (4xx)
func IsRetryableError ¶
IsRetryableError checks if an error is likely retryable based on its category
func IsServerError ¶
IsServerError checks if an error is a server error (5xx)
func MaskEmail ¶
MaskEmail masks an email address (shows first 3 chars + domain) Security: Protects PII in logs
func MaskToken ¶
MaskToken masks a token/API key (shows first 4 chars) Security: Prevents leaking credentials in logs
func MaskUUID ¶
MaskUUID masks a UUID for logging (shows first 8 chars) Security: Prevents leaking full UUIDs in logs
func MessageCount ¶
MessageCount creates a message_count field
func MetricValue ¶
MetricValue creates a metric_value field
func NewErrorWithCode ¶
NewErrorWithCode creates a new error with an associated code
func NewErrorWithCodeAndCause ¶
NewErrorWithCodeAndCause creates a new error with code and underlying cause
func PermissionField ¶
PermissionField creates a permission field (for authorization audits)
func PropagateTraceHeaders ¶
PropagateTraceHeaders adds trace headers to HTTP requests for unified distributed tracing Supports W3C TraceContext format and custom headers
func RedactPassword ¶
RedactPassword ensures passwords are never logged Security: Hard redaction for passwords
func RedactSecret ¶
RedactSecret ensures secrets are never logged Security: Hard redaction for secrets
func RemoteAddr ¶
RemoteAddr creates a remote_addr field (IP address should be masked if sensitive)
func RequestSizeBytes ¶
RequestSizeBytes creates a request_size_bytes field
func ResourceID ¶
ResourceID creates a resource_id field (generic resource identifier)
func ResourceType ¶
ResourceType creates a resource_type field
func ResponseSizeBytes ¶
ResponseSizeBytes creates a response_size_bytes field
func RowsAffected ¶
RowsAffected creates a rows_affected field
func SanitizeSQL ¶
SanitizeSQL sanitizes SQL queries for logging (removes values, keeps structure) Security: Prevents leaking sensitive data from SQL queries
func TenantID ¶
TenantID creates a tenant_id field with optional masking maskUUID: if true, applies UUID masking for security
func ThroughputBytesPerSecond ¶
ThroughputBytesPerSecond creates a throughput_bytes_per_second field
func WithClusterID ¶
WithClusterID adds cluster ID to context
func WithRequestID ¶
WithRequestID adds request ID to context
func WithResourceID ¶
WithResourceID adds a generic resource ID to context (for multi-tenant systems)
func WithSpanID ¶
WithSpanID adds span ID to context (W3C TraceContext)
func WithTenantID ¶
WithTenantID adds tenant ID to context
func WithTraceID ¶
WithTraceID adds trace ID to context (W3C TraceContext)
func WithUserID ¶
WithUserID adds user ID to context
func WrapError ¶
WrapError wraps an error with additional context Returns a new error that includes the original error and context
func WrapErrorf ¶
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
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 ¶
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 Logger ¶
Logger wraps zap.Logger with component-specific context
func NewLogger ¶
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) Error ¶
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) InfoC ¶
InfoC logs an info message with context (extracts context values automatically)
func (*Logger) WithComponent ¶
WithComponent adds component name to log context
func (*Logger) WithContext ¶
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) WithFields ¶
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 ¶
Error logs an error message with rate limiting (errors 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
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