logger

package
v0.0.0-...-145cf54 Latest Latest
Warning

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

Go to latest
Published: Jan 16, 2026 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Index

Constants

View Source
const (
	ReqIDKey            contextKey = "request_id"
	TransactionIDCtxKey contextKey = "transaction_id" // Database transaction ID
	TraceIDCtxKey       contextKey = "trace_id"
	SpanIDCtxKey        contextKey = "span_id"
	ClusterIDCtxKey     contextKey = "cluster_id"
	ResourceTypeCtxKey  contextKey = "resource_type"
	ResourceIDCtxKey    contextKey = "resource_id"
)

Context keys for storing correlation fields

View Source
const (
	FieldBindAddress = "bind_address"
	FieldEnvironment = "environment"
	FieldLogLevel    = "level"
	FieldLogFormat   = "format"
	FieldLogOutput   = "output"
)

Server/Config related fields

View Source
const (
	FieldMigrationID = "migration_id"
	// FieldConnectionString - WARNING: Always sanitize connection strings before logging
	// to prevent exposing passwords. Never log raw connection strings.
	FieldConnectionString = "connection_string"
	FieldTable            = "table"
	FieldChannel          = "channel"
)

Database related fields

View Source
const (
	FieldOTelEnabled      = "otel_enabled"
	FieldSamplingRate     = "sampling_rate"
	FieldExporterEndpoint = "exporter_endpoint"
)

OpenTelemetry related fields

View Source
const (
	FieldAdapter   = "adapter"
	FieldErrorCode = "error_code"
	FieldFlag      = "flag"
	FieldData      = "data"
)

Generic fields

View Source
const (
	FieldHTTPMethod     = "method"
	FieldHTTPPath       = "path"
	FieldHTTPStatusCode = "status_code"
	FieldHTTPDuration   = "duration_ms"
	FieldHTTPUserAgent  = "user_agent"
)

HTTP field name constants

View Source
const (
	FieldEndpoint = "endpoint"
)

Endpoint related fields (used in handlers)

View Source
const (
	FieldNodePoolID = "nodepool_id"
)

Resource related fields

View Source
const (
	FieldSchemaPath = "schema_path"
)

Schema related fields

View Source
const (
	ReqIDHeader = "X-Request-ID"
)

HTTP header names

Variables

View Source
var ContextFieldsRegistry = []ContextField{
	{ReqIDKey, "request_id", GetRequestID},
	{TraceIDCtxKey, "trace_id", GetTraceID},
	{SpanIDCtxKey, "span_id", GetSpanID},
	{ClusterIDCtxKey, "cluster_id", GetClusterID},
	{ResourceTypeCtxKey, "resource_type", GetResourceType},
	{ResourceIDCtxKey, "resource_id", GetResourceID},
}

ContextFieldsRegistry defines all string-type context fields for logging This is the single source of truth for string field management Fields are ordered as per HyperFleet Logging Specification (docs/logging.md:384) Note: transaction_id (int64) is handled separately in logger.go

Functions

func Debug

func Debug(ctx context.Context, msg string)

Debug logs at Debug level with context fields only. For temporary fields, use With().

func Error

func Error(ctx context.Context, msg string)

Error logs at Error level with context fields only. For temporary fields, use With().

func GetClusterID

func GetClusterID(ctx context.Context) (string, bool)

GetClusterID retrieves cluster ID from context

func GetLogger

func GetLogger() *slog.Logger

GetLogger returns the global logger instance

func GetRequestID

func GetRequestID(ctx context.Context) (string, bool)

GetRequestID retrieves request ID from context

func GetResourceID

func GetResourceID(ctx context.Context) (string, bool)

GetResourceID retrieves resource ID from context

func GetResourceType

func GetResourceType(ctx context.Context) (string, bool)

GetResourceType retrieves resource type from context

func GetSpanID

func GetSpanID(ctx context.Context) (string, bool)

GetSpanID retrieves span ID from context

func GetTraceID

func GetTraceID(ctx context.Context) (string, bool)

GetTraceID retrieves trace ID from context

func GetTransactionID

func GetTransactionID(ctx context.Context) (int64, bool)

GetTransactionID retrieves transaction ID from context

func HTTPDuration

func HTTPDuration(d time.Duration) slog.Attr

HTTPDuration returns a slog attribute for HTTP request duration in milliseconds

func HTTPMethod

func HTTPMethod(method string) slog.Attr

HTTPMethod returns a slog attribute for HTTP method

func HTTPPath

func HTTPPath(path string) slog.Attr

HTTPPath returns a slog attribute for HTTP path

func HTTPRequestAttrs

func HTTPRequestAttrs(r *http.Request) []slog.Attr

HTTPRequestAttrs returns a slice of slog attributes for HTTP request

func HTTPResponseAttrs

func HTTPResponseAttrs(statusCode int, duration time.Duration) []slog.Attr

HTTPResponseAttrs returns a slice of slog attributes for HTTP response

func HTTPStatusCode

func HTTPStatusCode(code int) slog.Attr

HTTPStatusCode returns a slog attribute for HTTP status code

func HTTPUserAgent

func HTTPUserAgent(ua string) slog.Attr

HTTPUserAgent returns a slog attribute for HTTP user agent

func Info

func Info(ctx context.Context, msg string)

Info logs at Info level with context fields only. For temporary fields, use With().

func InitGlobalLogger

func InitGlobalLogger(cfg *LogConfig)

InitGlobalLogger initializes the global logger with the given configuration. This function is idempotent (safe to call multiple times).

Concurrency note: This function uses atomic.Value without sync.Once intentionally. Current call sites are serialized (single-threaded main() and sync.Once in tests). If concurrent initialization occurs, the last Store() wins, which is acceptable. For stricter guarantees in future use cases, callers should wrap this with sync.Once or equivalent synchronization.

func NewHyperFleetHandler

func NewHyperFleetHandler(cfg *LogConfig) slog.Handler

NewHyperFleetHandler creates a HyperFleet logger handler Returns slog.Handler interface to support both HyperFleetHandler (JSON) and HyperFleetTextHandler (Text)

func NewOCMLoggerBridge

func NewOCMLoggerBridge() sdk.Logger

NewOCMLoggerBridge creates an OCM SDK logger bridge

func ParseLogLevel

func ParseLogLevel(level string) (slog.Level, error)

ParseLogLevel converts string to slog.Level

func ParseLogOutput

func ParseLogOutput(output string) (io.Writer, error)

ParseLogOutput converts string to io.Writer

func ReconfigureGlobalLogger

func ReconfigureGlobalLogger(cfg *LogConfig)

ReconfigureGlobalLogger reconfigures the global logger with new configuration Unlike InitGlobalLogger, this can be called multiple times to update configuration This is useful when environment configuration is loaded after initial logger setup

func RequestIDMiddleware

func RequestIDMiddleware(handler http.Handler) http.Handler

RequestIDMiddleware Middleware wraps the given HTTP handler so that the details of the request are sent to the log.

func Warn

func Warn(ctx context.Context, msg string)

Warn logs at Warn level with context fields only. For temporary fields, use With().

func WithClusterID

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

WithClusterID adds cluster ID to context

func WithRequestID

func WithRequestID(ctx context.Context) context.Context

WithRequestID adds request ID to context If request ID already exists in context, it returns the context unchanged Otherwise, it generates a new KSUID and adds it to the context

func WithResourceID

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

WithResourceID adds resource ID to context

func WithResourceType

func WithResourceType(ctx context.Context, resourceType string) context.Context

WithResourceType adds resource type to context

func WithSpanID

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

WithSpanID adds span ID to context

func WithTraceID

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

WithTraceID adds trace ID to context

func WithTransactionID

func WithTransactionID(ctx context.Context, transactionID int64) context.Context

WithTransactionID adds transaction ID to context

Types

type ContextField

type ContextField struct {
	Key    contextKey
	Name   string
	Getter func(context.Context) (string, bool)
}

ContextField defines metadata for a string-type context log field

type ContextLogger

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

ContextLogger wraps a context with additional temporary key-value pairs for logging.

func With

func With(ctx context.Context, args ...any) *ContextLogger

With creates a new ContextLogger with temporary key-value pairs.

func WithError

func WithError(ctx context.Context, err error) *ContextLogger

WithError is a convenience function for adding error field to logs.

func (*ContextLogger) Debug

func (l *ContextLogger) Debug(msg string)

func (*ContextLogger) Error

func (l *ContextLogger) Error(msg string)

func (*ContextLogger) Info

func (l *ContextLogger) Info(msg string)

func (*ContextLogger) Warn

func (l *ContextLogger) Warn(msg string)

func (*ContextLogger) With

func (l *ContextLogger) With(args ...any) *ContextLogger

With adds additional temporary fields to the logger and can be chained.

func (*ContextLogger) WithError

func (l *ContextLogger) WithError(err error) *ContextLogger

WithError adds an error field to the logger and can be chained.

type GormLogger

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

func NewGormLogger

func NewGormLogger(logLevel gormlogger.LogLevel, slowThreshold time.Duration) *GormLogger

func (*GormLogger) Error

func (l *GormLogger) Error(ctx context.Context, msg string, data ...interface{})

func (*GormLogger) Info

func (l *GormLogger) Info(ctx context.Context, msg string, data ...interface{})

func (*GormLogger) LogMode

func (*GormLogger) Trace

func (l *GormLogger) Trace(ctx context.Context, begin time.Time, fc func() (sql string, rowsAffected int64), err error)

func (*GormLogger) Warn

func (l *GormLogger) Warn(ctx context.Context, msg string, data ...interface{})

type HyperFleetHandler

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

HyperFleetHandler implements slog.Handler interface Adds HyperFleet-specific fields: component, version, hostname, trace_id, span_id, etc.

func (*HyperFleetHandler) Enabled

func (h *HyperFleetHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled implements slog.Handler interface

func (*HyperFleetHandler) Handle

func (h *HyperFleetHandler) Handle(ctx context.Context, r slog.Record) error

Handle implements slog.Handler interface

func (*HyperFleetHandler) WithAttrs

func (h *HyperFleetHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs implements slog.Handler interface

func (*HyperFleetHandler) WithGroup

func (h *HyperFleetHandler) WithGroup(name string) slog.Handler

WithGroup implements slog.Handler interface

type HyperFleetTextHandler

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

HyperFleetTextHandler implements the HyperFleet Logging Specification text format: {timestamp} {LEVEL} [{component}] [{version}] [{hostname}] {message} {key=value}...

Example output: 2026-01-09T12:30:45Z INFO [hyperfleet-api] [v1.2.3] [pod-abc] Processing request request_id=xyz cluster_id=abc123

func NewHyperFleetTextHandler

func NewHyperFleetTextHandler(w io.Writer, component, version, hostname string, level slog.Level) *HyperFleetTextHandler

NewHyperFleetTextHandler creates a new text handler conforming to HyperFleet Logging Specification

func (*HyperFleetTextHandler) Enabled

func (h *HyperFleetTextHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level

func (*HyperFleetTextHandler) Handle

func (*HyperFleetTextHandler) WithAttrs

func (h *HyperFleetTextHandler) WithAttrs(attrs []slog.Attr) slog.Handler

func (*HyperFleetTextHandler) WithGroup

func (h *HyperFleetTextHandler) WithGroup(name string) slog.Handler

WithGroup returns a new handler with a group name

type LogConfig

type LogConfig struct {
	Level     slog.Level
	Format    LogFormat
	Output    io.Writer
	Component string
	Version   string
	Hostname  string
}

LogConfig holds the configuration for the logger

type LogFormat

type LogFormat int

LogFormat enumeration for output format

const (
	// FormatText outputs logs in human-readable text format
	FormatText LogFormat = iota
	// FormatJSON outputs logs in JSON format for structured logging
	FormatJSON
)

func ParseLogFormat

func ParseLogFormat(format string) (LogFormat, error)

ParseLogFormat converts string to LogFormat

type OCMLoggerBridge

type OCMLoggerBridge struct{}

OCMLoggerBridge bridges slog to OCM SDK's Logger interface

func (*OCMLoggerBridge) Debug

func (b *OCMLoggerBridge) Debug(ctx context.Context, format string, args ...interface{})

Debug implements sdk.Logger

func (*OCMLoggerBridge) DebugEnabled

func (b *OCMLoggerBridge) DebugEnabled() bool

DebugEnabled implements sdk.Logger

func (*OCMLoggerBridge) Error

func (b *OCMLoggerBridge) Error(ctx context.Context, format string, args ...interface{})

Error implements sdk.Logger

func (*OCMLoggerBridge) ErrorEnabled

func (b *OCMLoggerBridge) ErrorEnabled() bool

ErrorEnabled implements sdk.Logger

func (*OCMLoggerBridge) Fatal

func (b *OCMLoggerBridge) Fatal(ctx context.Context, format string, args ...interface{})

Fatal implements sdk.Logger

func (*OCMLoggerBridge) Info

func (b *OCMLoggerBridge) Info(ctx context.Context, format string, args ...interface{})

Info implements sdk.Logger

func (*OCMLoggerBridge) InfoEnabled

func (b *OCMLoggerBridge) InfoEnabled() bool

InfoEnabled implements sdk.Logger

func (*OCMLoggerBridge) Warn

func (b *OCMLoggerBridge) Warn(ctx context.Context, format string, args ...interface{})

Warn implements sdk.Logger

func (*OCMLoggerBridge) WarnEnabled

func (b *OCMLoggerBridge) WarnEnabled() bool

WarnEnabled implements sdk.Logger

Jump to

Keyboard shortcuts

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