slogging

package
v0.0.0-...-e9624ed Latest Latest
Warning

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

Go to latest
Published: Nov 14, 2025 License: Apache-2.0 Imports: 17 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Initialize

func Initialize(config Config) error

Initialize sets up the global logger

func LogWebSocketConnection

func LogWebSocketConnection(event string, sessionID, userID, diagramID string, config WebSocketLoggingConfig)

LogWebSocketConnection logs WebSocket connection events (compatibility with original signature)

func LogWebSocketError

func LogWebSocketError(errorType, errorMessage, sessionID, userID string, config WebSocketLoggingConfig)

LogWebSocketError logs WebSocket-related errors (compatibility with original signature)

func LogWebSocketMessage

func LogWebSocketMessage(direction WSMessageDirection, sessionID, userID string, messageType string, data []byte, config WebSocketLoggingConfig)

LogWebSocketMessage logs WebSocket messages with optional token redaction

func LogWebSocketMetrics

func LogWebSocketMetrics(sessionID string, metrics map[string]interface{})

LogWebSocketMetrics logs WebSocket performance metrics

func LoggerMiddleware

func LoggerMiddleware() gin.HandlerFunc

LoggerMiddleware returns a Gin middleware for logging requests using slog

func NewRedactionHandler

func NewRedactionHandler(handler slog.Handler, config RedactionConfig) (slog.Handler, error)

NewRedactionHandler creates a new redaction handler

func PerformanceMiddleware

func PerformanceMiddleware(slowRequestThreshold time.Duration) gin.HandlerFunc

PerformanceMiddleware logs performance metrics for requests

func Recoverer

func Recoverer() gin.HandlerFunc

Recoverer creates middleware for recovering from panics using slog

func RedactHeaders

func RedactHeaders(headers map[string][]string) map[string][]string

RedactHeaders creates a copy of headers map with sensitive values redacted

func RedactSensitiveInfo

func RedactSensitiveInfo(input string) string

RedactSensitiveInfo removes or masks sensitive information from strings (legacy compatibility)

func RedactWebSocketMessage

func RedactWebSocketMessage(message string) string

RedactWebSocketMessage applies redaction rules to WebSocket message content

func RequestResponseLogger

func RequestResponseLogger(config RequestResponseLoggingConfig) gin.HandlerFunc

RequestResponseLogger creates middleware for detailed request/response logging

func RequestTracingMiddleware

func RequestTracingMiddleware(enableBodyLogging bool) gin.HandlerFunc

RequestTracingMiddleware adds detailed request tracing for debugging

func SanitizeLogMessage

func SanitizeLogMessage(message string) string

SanitizeLogMessage removes newlines and other control characters from log messages

func StructuredLogHandler

func StructuredLogHandler() gin.HandlerFunc

StructuredLogHandler provides a Gin handler for structured logging endpoints

Types

type Config

type Config struct {
	// Level is the minimum log level to output
	Level LogLevel
	// IsDev indicates if this is a development build (includes file/line info)
	IsDev bool
	// LogDir is the directory to store log files
	LogDir string
	// MaxAgeDays is the maximum number of days to retain logs
	MaxAgeDays int
	// MaxSizeMB is the maximum size of a log file in MB before rotation
	MaxSizeMB int
	// MaxBackups is the maximum number of old log files to retain
	MaxBackups int
	// AlsoLogToConsole controls if logs also go to stdout/stderr
	AlsoLogToConsole bool
	// SuppressUnauthenticatedLogs controls whether to log requests without authenticated users
	SuppressUnauthenticatedLogs bool
	// RedactionConfig controls sensitive data redaction (optional, uses defaults if nil)
	RedactionConfig *RedactionConfig
}

Config holds configuration options for the logger (maintained for compatibility)

type ContextLogger

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

ContextLogger adds request context to log messages

func (*ContextLogger) Debug

func (cl *ContextLogger) Debug(format string, args ...any)

Debug logs a debug-level message with context (compatibility method)

func (*ContextLogger) DebugCtx

func (cl *ContextLogger) DebugCtx(msg string, attrs ...slog.Attr)

DebugCtx logs a debug message with additional structured attributes

func (*ContextLogger) Error

func (cl *ContextLogger) Error(format string, args ...any)

Error logs an error-level message with context (compatibility method)

func (*ContextLogger) ErrorCtx

func (cl *ContextLogger) ErrorCtx(msg string, attrs ...slog.Attr)

ErrorCtx logs an error message with additional structured attributes

func (*ContextLogger) GetSlogger

func (cl *ContextLogger) GetSlogger() *slog.Logger

GetSlogger returns the underlying slog.Logger for this context

func (*ContextLogger) Info

func (cl *ContextLogger) Info(format string, args ...any)

Info logs an info-level message with context (compatibility method)

func (*ContextLogger) InfoCtx

func (cl *ContextLogger) InfoCtx(msg string, attrs ...slog.Attr)

InfoCtx logs an info message with additional structured attributes

func (*ContextLogger) Warn

func (cl *ContextLogger) Warn(format string, args ...any)

Warn logs a warning-level message with context (compatibility method)

func (*ContextLogger) WarnCtx

func (cl *ContextLogger) WarnCtx(msg string, attrs ...slog.Attr)

WarnCtx logs a warning message with additional structured attributes

func (*ContextLogger) WithAttrs

func (cl *ContextLogger) WithAttrs(attrs ...slog.Attr) *ContextLogger

WithAttrs returns a new ContextLogger with additional attributes

func (*ContextLogger) WithGroup

func (cl *ContextLogger) WithGroup(name string) *ContextLogger

WithGroup returns a new ContextLogger with a group name

type FallbackLogger

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

FallbackLogger provides a simple logger that writes to gin's output (compatibility)

func (*FallbackLogger) Debug

func (l *FallbackLogger) Debug(format string, args ...any)

Debug logs debug level messages

func (*FallbackLogger) Error

func (l *FallbackLogger) Error(format string, args ...any)

Error logs error level messages

func (*FallbackLogger) Info

func (l *FallbackLogger) Info(format string, args ...any)

Info logs info level messages

func (*FallbackLogger) Warn

func (l *FallbackLogger) Warn(format string, args ...any)

Warn logs warning level messages

type GinContextLike

type GinContextLike interface {
	Get(key any) (any, bool)
	GetHeader(key string) string
	ClientIP() string
}

GinContextLike defines a minimal interface for contexts that can be used with the logger

type LogLevel

type LogLevel int

LogLevel represents logging verbosity (maintained for compatibility)

const (
	// LogLevelDebug includes detailed debug information
	LogLevelDebug LogLevel = iota
	// LogLevelInfo includes general request information
	LogLevelInfo
	// LogLevelWarn includes warnings and errors only
	LogLevelWarn
	// LogLevelError includes only errors
	LogLevelError
)

func ParseLogLevel

func ParseLogLevel(level string) LogLevel

ParseLogLevel converts a string log level to LogLevel

func (LogLevel) String

func (l LogLevel) String() string

String returns the string representation of the log level

type Logger

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

Logger is the slog-based logging component

func Get

func Get() *Logger

Get returns the global logger instance, initializing with defaults if needed

func NewLogger

func NewLogger(config Config) (*Logger, error)

NewLogger creates a new slog-based logger instance

func (*Logger) Close

func (l *Logger) Close() error

Close properly closes the logger

func (*Logger) Debug

func (l *Logger) Debug(format string, args ...interface{})

Debug logs a debug-level message (compatibility method)

func (*Logger) DebugCtx

func (l *Logger) DebugCtx(ctx context.Context, msg string, attrs ...slog.Attr)

DebugCtx logs a debug message with context and structured attributes

func (*Logger) Error

func (l *Logger) Error(format string, args ...interface{})

Error logs an error-level message (compatibility method)

func (*Logger) ErrorCtx

func (l *Logger) ErrorCtx(ctx context.Context, msg string, attrs ...slog.Attr)

ErrorCtx logs an error message with context and structured attributes

func (*Logger) GetSlogger

func (l *Logger) GetSlogger() *slog.Logger

GetSlogger returns the underlying slog.Logger for advanced usage

func (*Logger) Info

func (l *Logger) Info(format string, args ...interface{})

Info logs an info-level message (compatibility method)

func (*Logger) InfoCtx

func (l *Logger) InfoCtx(ctx context.Context, msg string, attrs ...slog.Attr)

InfoCtx logs an info message with context and structured attributes

func (*Logger) Warn

func (l *Logger) Warn(format string, args ...interface{})

Warn logs a warning-level message (compatibility method)

func (*Logger) WarnCtx

func (l *Logger) WarnCtx(ctx context.Context, msg string, attrs ...slog.Attr)

WarnCtx logs a warning message with context and structured attributes

func (*Logger) WithContext

func (l *Logger) WithContext(c GinContextLike) *ContextLogger

WithContext returns a context-aware logger that includes request information

type RedactionAction

type RedactionAction string

RedactionAction defines how sensitive data should be handled

const (
	// RedactionOmit removes the field entirely from logs
	RedactionOmit RedactionAction = "omit"
	// RedactionObfuscate replaces the value with [REDACTED]
	RedactionObfuscate RedactionAction = "obfuscate"
	// RedactionPartial shows first and last few characters with middle redacted
	RedactionPartial RedactionAction = "partial"
)

type RedactionConfig

type RedactionConfig struct {
	// Enabled controls whether redaction is active
	Enabled bool `yaml:"enabled" json:"enabled"`
	// Rules contains all redaction rules
	Rules []RedactionRule `yaml:"rules" json:"rules"`
}

RedactionConfig holds all redaction rules

func DefaultRedactionConfig

func DefaultRedactionConfig() RedactionConfig

DefaultRedactionConfig provides sensible defaults for security

func (*RedactionConfig) CompileRules

func (rc *RedactionConfig) CompileRules() error

CompileRules compiles regex patterns for all rules

type RedactionRule

type RedactionRule struct {
	// FieldPattern is a regex pattern to match field names
	FieldPattern string `yaml:"field_pattern" json:"field_pattern"`
	// Action specifies what to do with matching fields
	Action RedactionAction `yaml:"action" json:"action"`
	// LogLevels specifies which log levels this rule applies to (empty = all levels)
	LogLevels []string `yaml:"log_levels,omitempty" json:"log_levels,omitempty"`
	// Groups specifies which log groups this rule applies to (empty = all groups)
	Groups []string `yaml:"groups,omitempty" json:"groups,omitempty"`
	// contains filtered or unexported fields
}

RedactionRule defines a single redaction rule

type RequestResponseLoggingConfig

type RequestResponseLoggingConfig struct {
	LogRequests    bool
	LogResponses   bool
	RedactTokens   bool
	MaxBodySize    int64 // Max request/response body size to log (in bytes)
	SkipPaths      []string
	OnlyDebugLevel bool // Only log at debug level
}

RequestResponseLoggingConfig holds configuration for enhanced logging

type SimpleLogger

type SimpleLogger interface {
	Debug(format string, args ...interface{})
	Info(format string, args ...interface{})
	Warn(format string, args ...interface{})
	Error(format string, args ...interface{})
}

SimpleLogger defines the basic logging interface used across the app (compatibility)

func GetContextLogger

func GetContextLogger(c GinContextLike) SimpleLogger

GetContextLogger retrieves a logger from the context or creates a fallback

func NewFallbackLogger

func NewFallbackLogger() SimpleLogger

NewFallbackLogger creates a simple logger for fallback use

type WSMessageDirection

type WSMessageDirection string

WSMessageDirection indicates the direction of the WebSocket message

const (
	WSMessageInbound  WSMessageDirection = "INBOUND"
	WSMessageOutbound WSMessageDirection = "OUTBOUND"
)

type WebSocketDebugLogger

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

WebSocketDebugLogger provides toggleable WebSocket message logging for debugging

func GetWebSocketDebugLogger

func GetWebSocketDebugLogger() *WebSocketDebugLogger

GetWebSocketDebugLogger returns the global WebSocket debug logger

func NewWebSocketDebugLogger

func NewWebSocketDebugLogger(logger *Logger) *WebSocketDebugLogger

NewWebSocketDebugLogger creates a new WebSocket debug logger

func (*WebSocketDebugLogger) ClearAllSessions

func (wsl *WebSocketDebugLogger) ClearAllSessions()

ClearAllSessions is an alias for DisableAllSessions (compatibility)

func (*WebSocketDebugLogger) DisableAllSessions

func (wsl *WebSocketDebugLogger) DisableAllSessions()

DisableAllSessions disables debug logging for all sessions

func (*WebSocketDebugLogger) DisableSessionLogging

func (wsl *WebSocketDebugLogger) DisableSessionLogging(sessionID string)

DisableSessionLogging disables debug logging for a specific session

func (*WebSocketDebugLogger) EnableSessionLogging

func (wsl *WebSocketDebugLogger) EnableSessionLogging(sessionID string)

EnableSessionLogging enables debug logging for a specific session

func (*WebSocketDebugLogger) GetEnabledSessions

func (wsl *WebSocketDebugLogger) GetEnabledSessions() []string

GetEnabledSessions returns a list of sessions with debug logging enabled

func (*WebSocketDebugLogger) IsSessionLoggingEnabled

func (wsl *WebSocketDebugLogger) IsSessionLoggingEnabled(sessionID string) bool

IsSessionLoggingEnabled checks if logging is enabled for a session

func (*WebSocketDebugLogger) LogMessage

func (wsl *WebSocketDebugLogger) LogMessage(sessionID, userID, direction string, message []byte)

LogMessage logs a WebSocket message if debug logging is enabled for the session

type WebSocketLoggingConfig

type WebSocketLoggingConfig struct {
	Enabled        bool
	RedactTokens   bool
	MaxMessageSize int64 // Max message size to log (in bytes)
	OnlyDebugLevel bool  // Only log at debug level
}

WebSocketLoggingConfig holds configuration for WebSocket message logging

Jump to

Keyboard shortcuts

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