tlog

package module
v1.2.0 Latest Latest
Warning

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

Go to latest
Published: Feb 3, 2026 License: MIT Imports: 17 Imported by: 4

README

tlog

A reusable Go logging package built on Zap, with integrations for Gin and GORM.

Features

  • Fast & Structured: Built on Zap for high-performance structured logging
  • Multi-output: Console and file output with rotation (via lumberjack)
  • Environment-aware: Development (colored console) and production (JSON) modes
  • Context-aware: Request tracing with request_id, user_id, trace_id
  • Gin Middleware: Request logging with body capture on errors
  • Sensitive Field Masking: Regex-based masking for sensitive data in request/response bodies
  • GORM Adapter: SQL logging with slow query detection
  • Vietnam Timezone: Default timezone set to UTC+7

Installation

go get github.com/thienel/tlog

Quick Start

Basic Usage
package main

import (
    "github.com/thienel/tlog"
    "go.uber.org/zap"
)

func main() {
    // Initialize with defaults (development mode, console output, Vietnam timezone)
    if err := tlog.InitWithDefaults(); err != nil {
        panic(err)
    }
    defer tlog.Sync()

    // Log messages with different levels
    tlog.Debug("Debug message", zap.String("key", "value"))
    tlog.Info("Application started", zap.Int("port", 8080))
    tlog.Warn("Warning message", zap.String("warning", "low disk space"))
    tlog.Error("Error occurred", zap.Error(errors.New("something went wrong")))
    
    // Fatal will log and exit(1)
    // tlog.Fatal("Fatal error", zap.Error(err))
    
    // Panic will log and panic
    // tlog.Panic("Panic error", zap.Error(err))
}
Using Logger Instance
// Get global logger
logger := tlog.L()
logger.Info("Using logger instance")

// Get sugared logger (slower but more convenient)
sugar := tlog.S()
sugar.Infof("Hello %s", "world")
sugar.Infow("User login", "user_id", 123, "ip", "192.168.1.1")

// Create child logger with fields
childLogger := tlog.With(zap.String("service", "user-service"))
childLogger.Info("This log will always have service field")

Configuration

Config Struct
type Config struct {
    Environment   string          // "development" | "production"
    Level         string          // "debug" | "info" | "warn" | "error"
    AppName       string          // Service identifier in logs
    Version       string          // Application version in logs
    
    // Console output
    EnableConsole bool            // Enable stdout output
    
    // File output
    EnableFile    bool            // Enable file output
    FilePath      string          // Path to log file
    MaxSizeMB     int             // Maximum size before rotation (MB)
    MaxBackups    int             // Number of old files to keep
    MaxAgeDays    int             // Maximum age in days
    Compress      bool            // Compress rotated files
    
    Timezone      *time.Location  // Timezone for timestamps
}
Default Values
Option Default Description
Environment "development" Log format (development=colored console, production=JSON)
Level "info" Minimum log level (debug, info, warn, error)
AppName "app" Service identifier in logs (service field)
Version "1.0.0" Application version in logs (version field)
EnableConsole true Enable stdout output
EnableFile false Enable file output
FilePath "logs/app.log" Log file path
MaxSizeMB 100 Max file size before rotation
MaxBackups 3 Number of old files to keep (0=unlimited)
MaxAgeDays 30 Max days to keep files (0=unlimited)
Compress true Compress rotated files with gzip
Timezone Asia/Ho_Chi_Minh Timezone for timestamps (UTC+7)
Configuration Examples
Development Mode (Default)
// Using InitWithDefaults - recommended for development
tlog.InitWithDefaults()

// Or explicitly
cfg := tlog.DefaultConfig()
tlog.Init(cfg)

Output:

15:04:05    INFO    tlog/main.go:10    Application started    {"port": 8080}
Production Mode (JSON)
cfg := tlog.DefaultConfig().
    WithEnvironment("production").
    WithLevel("info").
    WithAppName("my-service").
    WithVersion("2.0.1")

tlog.Init(cfg)

Output:

{"timestamp":"2024-12-27T15:04:05.123+07:00","level":"INFO","caller":"main.go:10","message":"Application started","service":"my-service","version":"2.0.1","port":8080}
With File Output
cfg := tlog.DefaultConfig().
    WithEnvironment("production").
    WithLevel("debug").
    WithAppName("my-api").
    WithVersion("1.2.3").
    WithFile("logs/app.log").
    WithFileRotation(100, 5, 7, true)  // 100MB, 5 backups, 7 days, compress
    
tlog.Init(cfg)
Both Console and File
cfg := tlog.DefaultConfig().
    WithEnvironment("production").
    WithConsole(true).                  // Keep console output
    WithFile("logs/app.log")            // Also write to file
    
tlog.Init(cfg)
Custom Timezone
// Use UTC
cfg := tlog.DefaultConfig().
    WithTimezone(time.UTC)

// Use specific timezone
loc, _ := time.LoadLocation("America/New_York")
cfg := tlog.DefaultConfig().
    WithTimezone(loc)
    
tlog.Init(cfg)
Full Configuration Example
import (
    "time"
    "github.com/thienel/tlog"
)

func main() {
    // Load from environment or config file
    cfg := tlog.Config{
        Environment:   "production",
        Level:         "debug",
        AppName:       "my-service",
        Version:       "2.0.0",
        EnableConsole: true,
        EnableFile:    true,
        FilePath:      "/var/log/my-service/app.log",
        MaxSizeMB:     200,
        MaxBackups:    10,
        MaxAgeDays:    30,
        Compress:      true,
        Timezone:      time.UTC,
    }
    
    if err := tlog.Init(cfg); err != nil {
        panic(err)
    }
    defer tlog.Sync()
}

Context-Aware Logging

Context Keys

tlog provides built-in context keys for request tracing:

  • RequestIDKey - Request ID for tracing
  • UserIDKey - Authenticated user ID
  • TraceIDKey - Distributed trace ID
Adding Context Values
import (
    "context"
    "github.com/thienel/tlog"
)

func main() {
    ctx := context.Background()
    
    // Add individual values
    ctx = tlog.WithRequestID(ctx, "req-abc-123")
    ctx = tlog.WithUserID(ctx, 42)
    ctx = tlog.WithTraceID(ctx, "trace-xyz-789")
    
    // Or add multiple at once
    ctx = tlog.ContextWithFields(ctx, "req-abc-123", 42, "trace-xyz-789")
}
Logging with Context
// Use context-aware log functions
tlog.InfoCtx(ctx, "Processing request", zap.String("action", "create"))
tlog.ErrorCtx(ctx, "Failed to process", zap.Error(err))
tlog.DebugCtx(ctx, "Debug info")
tlog.WarnCtx(ctx, "Warning message")

// Output includes context fields automatically:
// {"message":"Processing request","request_id":"req-abc-123","user_id":42,"trace_id":"trace-xyz-789","action":"create"}
Getting Logger with Context
// Get logger with context fields pre-attached
logger := tlog.FromContext(ctx)
logger.Info("Custom log", zap.String("extra", "field"))

// Useful in service layers
func (s *UserService) GetUser(ctx context.Context, id uint) (*User, error) {
    log := tlog.FromContext(ctx)
    log.Info("Fetching user", zap.Uint("id", id))
    // ...
}

Gin Integration

Basic Middleware Usage
import (
    "github.com/gin-gonic/gin"
    "github.com/thienel/tlog"
)

func main() {
    tlog.InitWithDefaults()
    defer tlog.Sync()
    
    r := gin.New()
    r.Use(gin.Recovery())
    
    // Add tlog middleware with default options
    r.Use(tlog.GinMiddleware())
    
    r.GET("/", func(c *gin.Context) {
        c.JSON(200, gin.H{"message": "Hello"})
    })
    
    r.Run(":8080")
}
GinConfig Options
type GinConfig struct {
    RequestIDHeader string           // Header name for request ID (default: "X-Request-ID")
    MaxBodyLogSize  int              // Max body size to log (default: 4096 bytes)
    LogRequestBody  bool             // Log request body on errors (default: true)
    LogResponseBody bool             // Log response body on errors (default: true)
    SkipPaths       []string         // Paths to skip logging
    UseUUIDv7       bool             // Use UUID v7 for request IDs (default: true)
    MaskPatterns    []*regexp.Regexp // Regex patterns for field names to mask
}
Gin Middleware Options
// Skip health check and metrics paths
r.Use(tlog.GinMiddleware(
    tlog.WithSkipPaths("/health", "/metrics", "/ready"),
))

// Custom request ID header
r.Use(tlog.GinMiddleware(
    tlog.WithRequestIDHeader("X-Correlation-ID"),
))

// Increase max body log size
r.Use(tlog.GinMiddleware(
    tlog.WithMaxBodyLogSize(8192), // 8KB
))

// Disable request body logging
r.Use(tlog.GinMiddleware(
    tlog.WithLogRequestBody(false),
))

// Disable response body logging
r.Use(tlog.GinMiddleware(
    tlog.WithLogResponseBody(false),
))

// Use UUID v4 instead of v7
r.Use(tlog.GinMiddleware(
    tlog.WithUUIDv7(false),
))

// Full configuration
r.Use(tlog.GinMiddleware(
    tlog.WithRequestIDHeader("X-Request-ID"),
    tlog.WithMaxBodyLogSize(4096),
    tlog.WithLogRequestBody(true),
    tlog.WithLogResponseBody(true),
    tlog.WithSkipPaths("/health", "/metrics"),
    tlog.WithUUIDv7(true),
))
Sensitive Field Masking

Mask sensitive fields in request/response bodies using regex patterns. Values of JSON fields whose names match any pattern will be replaced with ******.

// Mask common sensitive fields
r.Use(tlog.GinMiddleware(
    tlog.WithMaskPatterns(
        `(?i)password`,      // matches "password", "Password", "PASSWORD"
        `(?i)secret`,        // matches "secret", "Secret", etc.
        `(?i)token`,         // matches "token", "accessToken", etc.
        `(?i)api[_-]?key`,   // matches "api_key", "apiKey", "API-KEY"
        `(?i)authorization`, // matches "authorization" header values
        `(?i)credit[_-]?card`, // matches "credit_card", "creditCard"
    ),
))

Example - Before masking:

{
    "username": "john",
    "password": "secret123",
    "profile": {
        "api_key": "sk-1234567890",
        "settings": {
            "secret_token": "abc-xyz"
        }
    }
}

Example - After masking (logged output):

{
    "username": "john",
    "password": "******",
    "profile": {
        "api_key": "******",
        "settings": {
            "secret_token": "******"
        }
    }
}

Features:

  • Supports regex patterns for flexible field name matching
  • Recursively masks nested objects and arrays
  • Only applies to JSON bodies (non-JSON bodies are logged unchanged)
  • No performance impact when no patterns are configured
  • Masking is applied to both request and response bodies
What the Middleware Logs

Request Received:

{
    "message": "Request received",
    "request_id": "019405a0-1234-7abc-8def-0123456789ab",
    "method": "POST",
    "path": "/api/users",
    "query": "page=1",
    "client_ip": "192.168.1.100",
    "user_agent": "Mozilla/5.0..."
}

Request Completed (Success):

{
    "message": "Request completed",
    "request_id": "019405a0-1234-7abc-8def-0123456789ab",
    "method": "POST",
    "path": "/api/users",
    "status_code": 200,
    "duration_ms": 15,
    "ip_address": "192.168.1.100",
    "protocol": "HTTP/1.1",
    "host": "api.example.com",
    "user_id": 42,
    "response_size": 256,
    "query_string": "page=1"
}

Request Completed (Error >= 400):

{
    "level": "WARN",
    "message": "Request completed with client error",
    "request_id": "...",
    "status_code": 400,
    "duration_ms": 5,
    "ip_address": "192.168.1.100",
    "protocol": "HTTP/1.1",
    "host": "api.example.com",
    "request_body": "{\"name\":\"\"}",
    "response_body": "{\"error\":\"name is required\"}"
}
Using Request ID in Handlers
func CreateUser(c *gin.Context) {
    // Request ID is automatically set by middleware
    requestID, _ := c.Get("request_id")
    
    // Create context with request ID for service calls
    ctx := tlog.WithRequestID(c.Request.Context(), requestID.(string))
    
    // Add user ID after authentication
    ctx = tlog.WithUserID(ctx, currentUser.ID)
    
    // Log with context
    tlog.InfoCtx(ctx, "Creating user")
    
    // Pass context to services
    user, err := userService.Create(ctx, req)
}

GORM Integration

Basic Usage
import (
    "time"
    "github.com/thienel/tlog"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
)

func main() {
    tlog.InitWithDefaults()
    
    db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
        Logger: tlog.NewGormLogger(),
    })
    if err != nil {
        tlog.Fatal("Failed to connect database", zap.Error(err))
    }
}
GormConfig Options
type GormConfig struct {
    SlowThreshold        time.Duration   // Threshold for slow query warning (default: 200ms)
    IgnoreRecordNotFound bool            // Skip logging ErrRecordNotFound (default: true)
    LogLevel             logger.LogLevel // GORM log level (default: Warn)
}
GORM Logger Options
import (
    gormlogger "gorm.io/gorm/logger"
)

// Custom slow query threshold
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{
    Logger: tlog.NewGormLogger(
        tlog.WithSlowThreshold(500 * time.Millisecond), // 500ms
    ),
})

// Don't ignore record not found errors
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{
    Logger: tlog.NewGormLogger(
        tlog.WithIgnoreRecordNotFound(false),
    ),
})

// Set GORM log level
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{
    Logger: tlog.NewGormLogger(
        tlog.WithGormLogLevel(gormlogger.Info), // Log all queries
    ),
})

// Full configuration
db, _ := gorm.Open(postgres.Open(dsn), &gorm.Config{
    Logger: tlog.NewGormLogger(
        tlog.WithSlowThreshold(200 * time.Millisecond),
        tlog.WithIgnoreRecordNotFound(true),
        tlog.WithGormLogLevel(gormlogger.Warn),
    ),
})
GORM Log Level Options
Level Description
gormlogger.Silent No logging
gormlogger.Error Log errors only
gormlogger.Warn Log errors and slow queries (default)
gormlogger.Info Log all queries
What GORM Logger Logs

Normal Query (Info level):

{
    "message": "Database query executed",
    "operation": "SELECT",
    "table": "users",
    "duration_ms": 1,
    "rows_affected": 1,
    "sql": "SELECT * FROM users WHERE id = 1",
    "caller": "user_repository.go:42",
    "request_id": "req-abc-123"
}

Slow Query (Warn level):

{
    "level": "WARN",
    "message": "Slow database query detected",
    "operation": "SELECT",
    "table": "orders",
    "duration_ms": 523,
    "rows_affected": 10000,
    "slow_query": true,
    "sql": "SELECT * FROM orders WHERE created_at > ?",
    "caller": "order_repository.go:78"
}

Error (Error level):

{
    "level": "ERROR",
    "message": "Database query failed",
    "operation": "INSERT",
    "table": "users",
    "duration_ms": 5,
    "rows_affected": 0,
    "sql": "INSERT INTO users (email) VALUES (?)",
    "error": "duplicate key value violates unique constraint",
    "caller": "user_repository.go:25"
}
Context-Aware GORM Queries
func (r *UserRepository) FindByID(ctx context.Context, id uint) (*User, error) {
    var user User
    
    // Pass context to GORM - request_id will be included in logs
    err := r.db.WithContext(ctx).First(&user, id).Error
    
    return &user, err
}

Complete Example

package main

import (
    "context"
    "errors"
    "time"

    "github.com/gin-gonic/gin"
    "github.com/thienel/tlog"
    "go.uber.org/zap"
    "gorm.io/driver/postgres"
    "gorm.io/gorm"
    gormlogger "gorm.io/gorm/logger"
)

func main() {
    // Initialize logger
    cfg := tlog.DefaultConfig().
        WithEnvironment("production").
        WithLevel("debug").
        WithAppName("my-api").
        WithVersion("1.0.0").
        WithFile("logs/app.log").
        WithFileRotation(100, 5, 30, true)

    if err := tlog.Init(cfg); err != nil {
        panic(err)
    }
    defer tlog.Sync()

    // Initialize database with GORM logger
    db, err := gorm.Open(postgres.Open("..."), &gorm.Config{
        Logger: tlog.NewGormLogger(
            tlog.WithSlowThreshold(200 * time.Millisecond),
            tlog.WithGormLogLevel(gormlogger.Warn),
        ),
    })
    if err != nil {
        tlog.Fatal("Failed to connect database", zap.Error(err))
    }

    // Initialize Gin
    r := gin.New()
    r.Use(gin.Recovery())
    r.Use(tlog.GinMiddleware(
        tlog.WithSkipPaths("/health"),
        tlog.WithMaskPatterns(`(?i)password`, `(?i)token`, `(?i)secret`),
    ))

    // Health check
    r.GET("/health", func(c *gin.Context) {
        c.JSON(200, gin.H{"status": "ok"})
    })

    // API endpoint with context logging
    r.GET("/users/:id", func(c *gin.Context) {
        // Get request context with request_id
        requestID, _ := c.Get("request_id")
        ctx := tlog.WithRequestID(c.Request.Context(), requestID.(string))

        // Log with context
        tlog.InfoCtx(ctx, "Fetching user", zap.String("user_id", c.Param("id")))

        // Database query with context
        var user User
        if err := db.WithContext(ctx).First(&user, c.Param("id")).Error; err != nil {
            tlog.ErrorCtx(ctx, "User not found", zap.Error(err))
            c.JSON(404, gin.H{"error": "user not found"})
            return
        }

        c.JSON(200, user)
    })

    tlog.Info("Server starting", zap.String("addr", ":8080"))
    r.Run(":8080")
}

Best Practices

  1. Always call tlog.Sync() on shutdown - Ensures all buffered logs are flushed

  2. Use context-aware logging in services - Pass context from handlers to maintain request tracing

  3. Set appropriate log levels per environment:

    • Development: debug
    • Staging: debug or info
    • Production: info or warn
  4. Use structured fields instead of string formatting:

    // Good
    tlog.Info("User created", zap.Uint("user_id", user.ID), zap.String("email", user.Email))
    
    // Bad
    tlog.S().Infof("User created: %d - %s", user.ID, user.Email)
    
  5. Configure file rotation in production - Prevent disk space issues

  6. Skip noisy paths - Exclude health checks and metrics from logging


License

MIT License

Documentation

Index

Constants

View Source
const (
	// RequestIDKey is the context key for request ID.
	RequestIDKey contextKey = "request_id"
	// UserIDKey is the context key for user ID.
	UserIDKey contextKey = "user_id"
	// TraceIDKey is the context key for trace ID.
	TraceIDKey contextKey = "trace_id"
)
View Source
const DefaultMaskValue = "******"

DefaultMaskValue is the default replacement for masked fields.

Variables

This section is empty.

Functions

func ContextWithFields

func ContextWithFields(ctx context.Context, requestID string, userID uint, traceID string) context.Context

ContextWithFields adds multiple fields to the context at once.

func Debug

func Debug(msg string, fields ...zap.Field)

Debug logs a debug message.

func DebugCtx

func DebugCtx(ctx context.Context, msg string, fields ...zap.Field)

DebugCtx logs a debug message with context fields.

func Error

func Error(msg string, fields ...zap.Field)

Error logs an error message.

func ErrorCtx

func ErrorCtx(ctx context.Context, msg string, fields ...zap.Field)

ErrorCtx logs an error message with context fields.

func Fatal

func Fatal(msg string, fields ...zap.Field)

Fatal logs a fatal message and exits.

func FromContext

func FromContext(ctx context.Context) *zap.Logger

FromContext returns a logger with context fields (request_id, user_id, trace_id). If no context is provided or no fields are found, returns the global logger.

func GinMiddleware

func GinMiddleware(opts ...GinOptionFunc) gin.HandlerFunc

GinMiddleware returns a Gin middleware that logs HTTP requests.

func Info

func Info(msg string, fields ...zap.Field)

Info logs an info message.

func InfoCtx

func InfoCtx(ctx context.Context, msg string, fields ...zap.Field)

InfoCtx logs an info message with context fields.

func Init

func Init(cfg Config) error

Init initializes the global logger with the provided configuration.

func InitWithDefaults

func InitWithDefaults() error

InitWithDefaults initializes the logger with default configuration.

func L

func L() *zap.Logger

L returns the global logger.

func Panic

func Panic(msg string, fields ...zap.Field)

Panic logs a panic message and panics.

func S

func S() *zap.SugaredLogger

S returns the global sugared logger.

func Sync

func Sync() error

Sync flushes any buffered log entries.

func Warn

func Warn(msg string, fields ...zap.Field)

Warn logs a warning message.

func WarnCtx

func WarnCtx(ctx context.Context, msg string, fields ...zap.Field)

WarnCtx logs a warning message with context fields.

func With

func With(fields ...zap.Field) *zap.Logger

With creates a child logger with the given fields.

func WithRequestID

func WithRequestID(ctx context.Context, requestID string) context.Context

WithRequestID adds a request ID to the context.

func WithTraceID

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

WithTraceID adds a trace ID to the context.

func WithUserID

func WithUserID(ctx context.Context, userID uint) context.Context

WithUserID adds a user ID to the context.

Types

type Config

type Config struct {
	// Environment determines the log format.
	// "development" uses colored console output, "production" uses JSON format.
	Environment string

	// Level sets the minimum log level.
	// Valid values: "debug", "info", "warn", "error"
	Level string

	// AppName is used as the service identifier in structured logs.
	AppName string

	// Version is the application version for structured logs.
	Version string

	// File output configuration
	EnableFile bool   // Enable file output
	FilePath   string // Path to log file (e.g., "logs/app.log")
	MaxSizeMB  int    // Maximum size in MB before rotation
	MaxBackups int    // Number of old files to keep (0 = unlimited)
	MaxAgeDays int    // Maximum age in days to keep (0 = unlimited)
	Compress   bool   // Compress rotated files

	// Console output
	EnableConsole bool // Enable console (stdout) output

	// Timezone for log timestamps
	Timezone *time.Location
}

Config contains all configuration options for the logger.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns a Config with sensible defaults. - Environment: "development" - Level: "info" - EnableConsole: true - EnableFile: false - Timezone: Vietnam (UTC+7)

func (*Config) Validate

func (c *Config) Validate() error

Validate checks if the configuration is valid.

func (Config) WithAppName

func (c Config) WithAppName(name string) Config

WithAppName sets the application name.

func (Config) WithConsole

func (c Config) WithConsole(enabled bool) Config

WithConsole enables or disables console output.

func (Config) WithEnvironment

func (c Config) WithEnvironment(env string) Config

WithEnvironment sets the environment.

func (Config) WithFile

func (c Config) WithFile(path string) Config

WithFile enables file output with the given path.

func (Config) WithFileRotation

func (c Config) WithFileRotation(maxSizeMB, maxBackups, maxAgeDays int, compress bool) Config

WithFileRotation configures file rotation settings.

func (Config) WithLevel

func (c Config) WithLevel(level string) Config

WithLevel sets the log level.

func (Config) WithTimezone

func (c Config) WithTimezone(loc *time.Location) Config

WithTimezone sets the timezone for log timestamps.

func (Config) WithVersion added in v1.0.1

func (c Config) WithVersion(version string) Config

WithVersion sets the application version.

type GinConfig

type GinConfig struct {
	// RequestIDHeader is the header key for request ID.
	// Default: "X-Request-ID"
	RequestIDHeader string

	// MaxBodyLogSize limits the size of request/response body to log.
	// Default: 4096 bytes
	MaxBodyLogSize int

	// LogRequestBody enables logging request body on errors (>= 400).
	// Default: true
	LogRequestBody bool

	// LogResponseBody enables logging response body on errors (>= 400).
	// Default: true
	LogResponseBody bool

	// SkipPaths is a list of paths to skip logging.
	SkipPaths []string

	// UseUUIDv7 uses UUID v7 (time-ordered) for request IDs.
	// Default: true
	UseUUIDv7 bool

	// MaskPatterns is a list of compiled regex patterns for field names to mask.
	// Values of fields whose names match any pattern will be replaced with "******".
	MaskPatterns []*regexp.Regexp
}

GinConfig contains configuration for the Gin middleware.

func DefaultGinConfig

func DefaultGinConfig() GinConfig

DefaultGinConfig returns a GinConfig with sensible defaults.

type GinOptionFunc

type GinOptionFunc func(*GinConfig)

GinOptionFunc is a function that configures GinConfig.

func WithLogRequestBody

func WithLogRequestBody(enabled bool) GinOptionFunc

WithLogRequestBody enables/disables request body logging.

func WithLogResponseBody

func WithLogResponseBody(enabled bool) GinOptionFunc

WithLogResponseBody enables/disables response body logging.

func WithMaskPatterns added in v1.2.0

func WithMaskPatterns(patterns ...string) GinOptionFunc

WithMaskPatterns sets regex patterns for field names to mask in request/response bodies. Values of JSON fields whose names match any pattern will be replaced with "******". Example: WithMaskPatterns(`(?i)password`, `(?i)secret`, `(?i)token`)

func WithMaxBodyLogSize

func WithMaxBodyLogSize(size int) GinOptionFunc

WithMaxBodyLogSize sets the maximum body size to log.

func WithRequestIDHeader

func WithRequestIDHeader(header string) GinOptionFunc

WithRequestIDHeader sets the request ID header name.

func WithSkipPaths

func WithSkipPaths(paths ...string) GinOptionFunc

WithSkipPaths sets paths to skip logging.

func WithUUIDv7

func WithUUIDv7(enabled bool) GinOptionFunc

WithUUIDv7 enables/disables UUID v7 for request IDs.

type GormConfig

type GormConfig struct {
	// SlowThreshold is the threshold for marking queries as "slow".
	// Default: 200ms
	SlowThreshold time.Duration

	// IgnoreRecordNotFound skips logging ErrRecordNotFound errors.
	// Default: true
	IgnoreRecordNotFound bool

	// LogLevel sets the GORM log level.
	// Default: gormlogger.Warn
	LogLevel gormlogger.LogLevel
}

GormConfig contains configuration for the GORM logger adapter.

func DefaultGormConfig

func DefaultGormConfig() GormConfig

DefaultGormConfig returns a GormConfig with sensible defaults.

type GormLogger

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

GormLogger is a custom GORM logger that uses tlog.

func NewGormLogger

func NewGormLogger(opts ...GormOption) *GormLogger

NewGormLogger creates a new GORM logger adapter.

func (*GormLogger) Error

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

Error logs error messages.

func (*GormLogger) Info

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

Info logs informational messages.

func (*GormLogger) LogMode

LogMode sets the log level and returns a new logger.

func (*GormLogger) Trace

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

Trace logs SQL queries with timing information.

func (*GormLogger) Warn

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

Warn logs warning messages.

type GormOption

type GormOption func(*GormConfig)

GormOption is a function that configures GormConfig.

func WithGormLogLevel

func WithGormLogLevel(level gormlogger.LogLevel) GormOption

WithGormLogLevel sets the GORM log level.

func WithIgnoreRecordNotFound

func WithIgnoreRecordNotFound(ignore bool) GormOption

WithIgnoreRecordNotFound sets whether to ignore ErrRecordNotFound.

func WithSlowThreshold

func WithSlowThreshold(d time.Duration) GormOption

WithSlowThreshold sets the slow query threshold.

Jump to

Keyboard shortcuts

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