phlogger

package
v1.10.1 Latest Latest
Warning

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

Go to latest
Published: Apr 29, 2026 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	Log  = golog.New()
	Logf = Log.Logf
)
View Source
var GinLevel golog.Level = 6

Functions

func ClearLogHooks

func ClearLogHooks()

ClearLogHooks removes all registered hooks. Primarily for testing.

func IncrementMetric

func IncrementMetric(event string)

IncrementMetric records one occurrence of a named event via the registered hook. If no hook is registered, the call is a no-op (zero overhead).

Use this instead of logging for events that happen thousands of times per second:

phlogger.IncrementMetric("cache.miss")

func IncrementMetricBy

func IncrementMetricBy(event string, n int64)

IncrementMetricBy records `n` occurrences of a named event via the registered hook. If no hook is registered, the call is a no-op.

func InitializeLogger

func InitializeLogger()

func InitializeSampler

func InitializeSampler(cfg SamplerConfig)

InitializeSampler sets the global sampler config. Called automatically by InitializeLogger with env-aware defaults. Safe to call multiple times — last call wins.

func LogD

func LogD(format string, args ...interface{})

LogD logs at Debug level.

func LogDRated

func LogDRated(key string, format string, args ...interface{})

LogDRated logs at Debug level with sampling using a custom key.

func LogDRatedW

func LogDRatedW(key string, window time.Duration, format string, args ...interface{})

LogDRatedW logs at Debug level with a time-window limiter.

func LogE

func LogE(format string, args ...interface{})

LogE logs at Error level.

func LogERated

func LogERated(key string, format string, args ...interface{})

LogERated logs at Error level with sampling using a custom key.

func LogERatedW

func LogERatedW(key string, window time.Duration, format string, args ...interface{})

LogERatedW logs at Error level with a time-window limiter.

func LogErr

func LogErr(err error)

LogErr logs an error value.

func LogF

func LogF(format string, args ...interface{})

LogF logs at Fatal level. Sampled by format string key. Hooks fire synchronously before os.Exit.

func LogI

func LogI(format string, args ...interface{})

LogI logs at Info level.

func LogIRated

func LogIRated(key string, format string, args ...interface{})

LogIRated logs at Info level with sampling using a custom key.

func LogIRatedW

func LogIRatedW(key string, window time.Duration, format string, args ...interface{})

LogIRatedW logs at Info level with a time-window limiter using a custom key and explicit window.

func LogJ

func LogJ(arg interface{})

LogJ logs arg as compact JSON.

func LogJI

func LogJI(arg interface{})

LogJI logs arg as indented JSON.

func LogSetLevel

func LogSetLevel(levelName string)

func LogW

func LogW(format string, args ...interface{})

LogW logs at Warning level.

func LogWRated

func LogWRated(key string, format string, args ...interface{})

LogWRated logs at Warning level with sampling using a custom key.

func LogWRatedW

func LogWRatedW(key string, window time.Duration, format string, args ...interface{})

LogWRatedW logs at Warning level with a time-window limiter.

func RegisterLogHook

func RegisterLogHook(level string, hook LogHook)

RegisterLogHook adds a hook for the given log level. Multiple hooks can be registered for the same level; all are called in order. Safe to call from multiple goroutines.

func RegisterMetricsHook

func RegisterMetricsHook(hook MetricsHook)

RegisterMetricsHook sets the global metrics callback. Call once at startup. Passing nil disables metrics forwarding.

Only one hook is active at a time — subsequent calls replace the previous hook.

Types

type KeyedLimiter

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

KeyedLimiter provides per-key token bucket rate limiting using x/time/rate. Each unique key gets its own independent limiter with identical rate and burst.

Use this when you need precise rate control (e.g. max N events/second per error type) rather than the sampling approach of the global sampler.

Thread-safe: safe for concurrent use from multiple goroutines.

Example:

limiter := NewKeyedLimiter(10, 1)  // 10 events/sec, burst of 1
if limiter.Allow("db.timeout") {
    phlogger.LogE("database timeout on host=%s", host)
}

func NewKeyedLimiter

func NewKeyedLimiter(r float64, burst int) *KeyedLimiter

NewKeyedLimiter creates a limiter allowing `r` events per second with `burst` capacity per key. A burst of 1 provides strict per-second limiting.

Parameters:

  • r: sustained events per second (e.g. 10.0 = ten events/sec per key)
  • burst: maximum burst size (events allowed in a single instant)

func (*KeyedLimiter) Allow

func (kl *KeyedLimiter) Allow(key string) bool

Allow reports whether an event for the given key should be permitted. Returns true if within rate limit, false if the event should be dropped.

Creates a new limiter for unseen keys automatically (lazy initialization).

type LogContext

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

LogContext is a child logger that prepends key-value context fields to every log message. Use it for request-scoped or operation-scoped logging where you want consistent context without repeating fields in every call.

Thread-safe: the prefix is built once at creation time (immutable).

Example:

ctx := NewLogContext("req_id", "abc-123", "merchant", "M001")
ctx.LogI("processing payment amount=%d", 5000)
// output: [req_id=abc-123 merchant=M001] processing payment amount=5000

func NewLogContext

func NewLogContext(fields ...string) *LogContext

NewLogContext creates a child logger with key-value context fields. Fields are provided as alternating key, value strings. Odd trailing keys are silently dropped.

Example:

ctx := NewLogContext("req_id", "abc-123", "user", "U42")

func (*LogContext) LogD

func (lc *LogContext) LogD(format string, args ...interface{})

LogD logs at Debug level with context prefix.

func (*LogContext) LogE

func (lc *LogContext) LogE(format string, args ...interface{})

LogE logs at Error level with context prefix.

func (*LogContext) LogF

func (lc *LogContext) LogF(format string, args ...interface{})

LogF logs at Fatal level with context prefix.

func (*LogContext) LogI

func (lc *LogContext) LogI(format string, args ...interface{})

LogI logs at Info level with context prefix.

func (*LogContext) LogW

func (lc *LogContext) LogW(format string, args ...interface{})

LogW logs at Warning level with context prefix.

func (*LogContext) With

func (lc *LogContext) With(fields ...string) *LogContext

With returns a new LogContext that merges the parent's fields with additional key-value pairs. Useful for adding scope without losing parent context.

Example:

parent := NewLogContext("req_id", "abc-123")
child := parent.With("step", "validate")
child.LogI("checking input") // [req_id=abc-123 step=validate] checking input

type LogForwardConfig

type LogForwardConfig struct {
	ForwardDebug bool // Forward Debug logs (default: false)
	ForwardInfo  bool // Forward Info logs (default: false)
	ForwardWarn  bool // Forward Warning logs (default: false)
	ForwardError bool // Forward Error logs (default: true)
	ForwardFatal bool // Forward Fatal logs (default: true)
}

LogForwardConfig controls which log levels are forwarded to an external sink (e.g. Sentry). By default only Fatal forwarding is enabled when Sentry is initialized.

func LogForwardConfigFromEnv

func LogForwardConfigFromEnv() LogForwardConfig

LogForwardConfigFromEnv constructs a LogForwardConfig reading from environment variables. Variables: LOG_FORWARD_FATAL (default "true"), LOG_FORWARD_ERROR (default "true"), LOG_FORWARD_WARN, LOG_FORWARD_INFO, LOG_FORWARD_DEBUG (default "false").

type LogHook

type LogHook func(level, message string)

LogHook is a callback invoked after a log line is emitted. level is one of: "debug", "info", "warn", "error", "fatal". message is the formatted log string.

type MetricsHook

type MetricsHook func(event string, count int64)

MetricsHook is a callback invoked when a metric event is recorded. Consumers wire their own counter backends (prometheus, statsd, etc.).

Parameters:

  • event: stable identifier string (e.g. "cache.miss", "db.timeout")
  • count: number of occurrences to add (usually 1)

Example with prometheus:

RegisterMetricsHook(func(event string, count int64) {
    myCounter.WithLabelValues(event).Add(float64(count))
})

type SamplerConfig

type SamplerConfig struct {
	Initial    int           // log first N per period per key (0 = disabled)
	Thereafter int           // after Initial, log every Nth (0 = drop all after initial)
	Period     time.Duration // sampling window (default: 1s)
}

SamplerConfig controls log sampling behavior per key per period.

Initial is the number of log lines allowed per key in each Period. After Initial is exhausted, only every Thereafter-th message is emitted. If Initial <= 0, sampling is disabled and all logs pass through.

Environment defaults:

  • production: Initial=5, Thereafter=50, Period=1s
  • staging: Initial=10, Thereafter=10, Period=1s
  • develop: disabled (all logs pass through)

func SamplerConfigForEnv

func SamplerConfigForEnv(env string) SamplerConfig

SamplerConfigForEnv returns production-tuned defaults based on environment string. Uses the same env values as phhelper.GetAppEnv(): "production", "prod", "staging", "stg".

func SamplerConfigFromAppEnv

func SamplerConfigFromAppEnv() SamplerConfig

SamplerConfigFromAppEnv returns a SamplerConfig based on the current APP_ENV. Convenience wrapper: reads phhelper.GetAppEnv() and calls SamplerConfigForEnv.

Jump to

Keyboard shortcuts

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