Skip to main content

Overview

The logger middleware logs HTTP requests with configurable format, output destination, and filtering. It captures method, path, status, latency, and custom fields. Use it when you need:
  • HTTP request logging
  • Access logs for debugging
  • Request timing metrics

Installation

Quick Start

Configuration

Options

Format Tags

Examples

Default Logger

Custom Format

JSON Format

Write to File

Skip Health Checks

Include Request ID

Full Access Log

API Reference

Functions

Technical Details

Implementation Architecture

The logger middleware captures HTTP request metrics by wrapping the response writer and measuring execution time:
  1. Response Writer Wrapping: A custom responseWriter type wraps the standard http.ResponseWriter to capture:
    • HTTP status code (defaults to 200)
    • Response size in bytes
  2. Timing Measurement: Uses time.Now() before request processing and time.Since() after to calculate latency with nanosecond precision.
  3. Client IP Detection: Implements intelligent IP extraction with fallback chain:
    • Checks X-Forwarded-For header (uses first IP if comma-separated list)
    • Checks X-Real-IP header
    • Falls back to RemoteAddr from the request
  4. Format String Processing: The formatLog function performs template tag replacement:
    • Basic tags use strings.ReplaceAll() for simple substitution
    • Dynamic tags (${header:name}, ${form:name}) use index-based parsing to extract custom values
    • Supports all standard HTTP request/response attributes
  5. Skip Function: Optional predicate function allows conditional logging based on request context, executed before timing starts to avoid overhead.

Performance Characteristics

  • Minimal overhead: Single writer wrap and string replacement operations
  • Zero allocations for skipped requests
  • String concatenation deferred until after request completion
  • No buffering of response body (streaming-friendly)

Best Practices

  • Skip logging for health check endpoints
  • Use structured (JSON) format for log aggregation
  • Include request IDs for tracing
  • Log to stderr in containers for proper log handling

Testing

The logger middleware includes comprehensive test coverage for all features and edge cases: