logger

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: Mar 3, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const LevelCritical = slog.LevelError + 1

LevelCritical is the slog level for CRITICAL severity (e.g. panic). Use with GetLogger().LogAttrs.

Variables

This section is empty.

Functions

func Debug

func Debug(msg string, fields Fields)

Debug logs at level Debug with fields (no context).

func Debugf

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

Debugf logs at level Debug (no context).

func DebugfContext added in v0.1.11

func DebugfContext(ctx context.Context, format string, args ...interface{})

DebugfContext logs at level Debug with trace/span/correlation from ctx.

func Error

func Error(msg string, fields Fields)

Error logs at level Error with fields (no context).

func ErrorStructuredContext added in v0.4.1

func ErrorStructuredContext(ctx context.Context, err error)

ErrorStructuredContext logs an error with type, message, and optional stack/cause from context.

func Errorf

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

Errorf logs at level Error (no context).

func ErrorfContext added in v0.1.11

func ErrorfContext(ctx context.Context, format string, args ...interface{})

ErrorfContext logs at level Error with trace/span/correlation from ctx.

func Fatalf

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

Fatalf logs at level Error and exits with code 1. Use only for startup failures; in request handlers use Errorf + abort.

func GetCorrelationID added in v0.1.11

func GetCorrelationID(ctx context.Context) string

GetCorrelationID returns the correlation ID from ctx if set.

func GetLogger

func GetLogger() *slog.Logger

GetLogger returns the global slog.Logger.

func GetSpanID added in v0.4.1

func GetSpanID(ctx context.Context) string

GetSpanID returns the span ID from ctx if set.

func GetTraceID added in v0.1.11

func GetTraceID(ctx context.Context) string

GetTraceID returns the trace ID from ctx if set.

func GetWriter added in v0.2.0

func GetWriter() io.Writer

GetWriter returns the io.Writer used for logging (e.g. for GORM).

func Info

func Info(msg string, fields Fields)

Info logs at level Info with fields (no context).

func Infof

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

Infof logs at level Info (no context).

func InfofContext added in v0.1.11

func InfofContext(ctx context.Context, format string, args ...interface{})

InfofContext logs at level Info with trace/span/correlation from ctx.

func Init added in v0.4.1

func Init(cfg Config)

Init initializes the global logger with the given config. Call once at startup.

Example
package main

import (
	"log/slog"
	"os"

	"github.com/turahe/pkg/logger"
)

func main() {
	cfg := logger.Config{
		LogLevel:          slog.LevelInfo,
		EnableCaller:      false,
		EnableHTTPLogging: true,
		ProjectID:         os.Getenv("GOOGLE_CLOUD_PROJECT"),
		ServiceName:       "my-service",
		ServiceVersion:    "1.0.0",
		Environment:       "production",
	}
	logger.Init(cfg)
}

func SetLogLevel

func SetLogLevel(level slog.Level)

SetLogLevel updates the log level. Kept for backward compatibility.

func Warn

func Warn(msg string, fields Fields)

Warn logs at level Warn with fields (no context).

func Warnf

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

Warnf logs at level Warn (no context).

func WarnfContext added in v0.1.11

func WarnfContext(ctx context.Context, format string, args ...interface{})

WarnfContext logs at level Warn with trace/span/correlation from ctx.

func WithCorrelationID added in v0.1.11

func WithCorrelationID(ctx context.Context, correlationID string) context.Context

WithCorrelationID returns a copy of ctx with the given correlation ID.

func WithHTTPRequest added in v0.4.1

func WithHTTPRequest(ctx context.Context, req *HTTPRequest) context.Context

WithHTTPRequest returns a copy of ctx with the given GCP httpRequest for inclusion in logs.

func WithSpanID added in v0.4.1

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

WithSpanID returns a copy of ctx with the given span ID (16-char hex for Cloud Trace).

func WithTraceID added in v0.1.11

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

WithTraceID returns a copy of ctx with the given trace ID.

Types

type Config added in v0.4.1

type Config struct {
	// LogLevel is the minimum level to log (default: slog.LevelInfo).
	LogLevel slog.Level
	// EnableCaller enables source location (file, line, function). Disable in production for performance.
	EnableCaller bool
	// EnableHTTPLogging enables inclusion of httpRequest in log entries when present in context.
	EnableHTTPLogging bool
	// ProjectID is the GCP project ID for trace format "projects/{ProjectID}/traces/{traceID}". Set from GOOGLE_CLOUD_PROJECT when empty.
	ProjectID string
	// ServiceName is the service name for log labels (optional).
	ServiceName string
	// ServiceVersion is the service version for log labels (optional).
	ServiceVersion string
	// Environment is the deployment environment (e.g. production, staging) for log labels (optional).
	Environment string
	// Redact is called for each field value before logging; return redacted value or the original. Optional.
	Redact RedactFunc
	// ErrorStacktrace enables stack traces in structured error logging. Optional.
	ErrorStacktrace bool
}

Config configures the enterprise observability logger. Use Init(cfg) once at startup (e.g. in main or wire).

type Ctx added in v0.1.12

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

Ctx is a logger bound to a context (trace, span, correlation, httpRequest).

func WithContext added in v0.1.12

func WithContext(ctx context.Context) *Ctx

WithContext returns a context-bound logger. Use in handlers after trace/HTTP middleware.

Example
package main

import (
	"github.com/turahe/pkg/logger"
)

func main() {
	// In a Gin handler, after middlewares (CloudTraceMiddleware, HTTPInstrumentation):
	//   log := logger.WithContext(c.Request.Context())
	//   log.Infof("request processed: %s", id)
	//   log.Info("event", logger.Fields{"key": "value"})
	_ = logger.WithContext
}

func (*Ctx) Debug added in v0.1.12

func (c *Ctx) Debug(msg string, fields Fields)

Debug logs at Debug with fields.

func (*Ctx) Debugf added in v0.1.12

func (c *Ctx) Debugf(format string, args ...interface{})

Debugf logs at level Debug with context.

func (*Ctx) Error added in v0.1.12

func (c *Ctx) Error(msg string, fields Fields)

Error logs at Error with fields.

func (*Ctx) ErrorStructured added in v0.4.1

func (c *Ctx) ErrorStructured(err error)

ErrorStructured logs an error with type, message, and optional stack/cause chain. Use from context-bound logger: logger.WithContext(ctx).ErrorStructured(err).

func (*Ctx) Errorf added in v0.1.12

func (c *Ctx) Errorf(format string, args ...interface{})

Errorf logs at level Error with context.

func (*Ctx) Fatalf added in v0.1.12

func (c *Ctx) Fatalf(format string, args ...interface{})

Fatalf logs at Error and exits. Do not use in request context; use Errorf + abort.

func (*Ctx) Info added in v0.1.12

func (c *Ctx) Info(msg string, fields Fields)

Info logs at Info with fields.

func (*Ctx) Infof added in v0.1.12

func (c *Ctx) Infof(format string, args ...interface{})

Infof logs at level Info with context.

func (*Ctx) Warn added in v0.1.12

func (c *Ctx) Warn(msg string, fields Fields)

Warn logs at Warn with fields.

func (*Ctx) Warnf added in v0.1.12

func (c *Ctx) Warnf(format string, args ...interface{})

Warnf logs at level Warn with context.

type Fields

type Fields map[string]interface{}

Fields is a map of key-value pairs for structured logging.

type HTTPRequest added in v0.4.1

type HTTPRequest struct {
	RequestMethod string `json:"requestMethod,omitempty"`
	RequestURL    string `json:"requestUrl,omitempty"`
	RequestSize   int64  `json:"requestSize,omitempty"`
	Status        int    `json:"status,omitempty"`
	ResponseSize  int64  `json:"responseSize,omitempty"`
	UserAgent     string `json:"userAgent,omitempty"`
	RemoteIP      string `json:"remoteIp,omitempty"`
	Latency       string `json:"latency,omitempty"` // Duration in seconds, e.g. "0.123s"
}

HTTPRequest is the GCP LogEntry httpRequest shape for structured logging. See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#HttpRequest

func GetHTTPRequest added in v0.4.1

func GetHTTPRequest(ctx context.Context) *HTTPRequest

GetHTTPRequest returns the GCP httpRequest from ctx if set.

type RedactFunc added in v0.4.1

type RedactFunc func(key string, value interface{}) interface{}

RedactFunc redacts sensitive values. Return the redacted string or the original. Used for audit-safe logs in fintech (e.g. card numbers, tokens).

Jump to

Keyboard shortcuts

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