slog

package module
v1.2.5 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2026 License: MIT Imports: 9 Imported by: 6

README

gin-slog

Lint and Testing Trivy Security Scan codecov Go Reference

Gin middleware for Go 1.26+ slog logging.

Overview

gin-slog is a Gin middleware that provides structured logging using Go's standard slog package (available since Go 1.21). It allows you to customize log formatting, target, level per path/status, and injection of additional context for each request, making it easy to produce standardized, production-ready logs in your Gin applications.

Features

  • Log HTTP requests with structured output via slog
  • Configurable log levels per status code or endpoint path
  • Easily skip logging for specific paths (by string or regexp)
  • Supports custom log writers and messages
  • Add custom fields or alter records/context per request
  • Output in standard text format compatible with slog
  • Fully extensible via Options pattern
  • Sensitive request headers (like Authorization/Cookie/etc) are hidden by default in logs, and can be customized

Installation

go get github.com/gin-contrib/slog

Requires Go 1.26+.

Usage

Basic Example
package main

import (
  "net/http"

  "github.com/gin-contrib/slog"
  "github.com/gin-gonic/gin"
)

func main() {
  r := gin.New()

  // Add slog middleware with default settings
  r.Use(slog.SetLogger())

  // Example route
  r.GET("/", func(c *gin.Context) {
    slog.Get(c).Info("Hello World!")
    c.String(http.StatusOK, "ok")
  })

  r.Run()
}
Customization

You can customize the middleware via options:

import (
  "os"
  "log/slog"
  "regexp"
  
  "github.com/gin-gonic/gin"
  "github.com/gin-contrib/slog"
)

func main() {
  r := gin.New()

  r.Use(slog.SetLogger(
    // Change log writer
    slog.WithWriter(os.Stdout),
    // Use UTC timestamps
    slog.WithUTC(true),
    // Skip health check and static routes
    slog.WithSkipPath([]string{"/healthz", "/metrics"}),
    // Skip paths matching pattern (e.g., static assets)
    slog.WithSkipPathRegexps(regexp.MustCompile(`\.ico$`), regexp.MustCompile(`^/static/`)),
    // Change default log levels
    slog.WithDefaultLevel(slog.LevelDebug),
    slog.WithClientErrorLevel(slog.LevelWarn),
    slog.WithServerErrorLevel(slog.LevelError),
    // Log message customization
    slog.WithMessage("Handled request"),
    // Set specific log level for a given path
    slog.WithPathLevel(map[string]slog.Level{"/foo": slog.LevelInfo}),
    // Set log level by status code
    slog.WithSpecificLogLevelByStatusCode(map[int]slog.Level{418: slog.LevelDebug}),
    // Inject custom info/context into logs
    slog.WithContext(func(c *gin.Context, rec *slog.Record) *slog.Record {
      rec.Add("user_agent", c.Request.UserAgent())
      return rec
    }),
    // Provide your own logger (to add global fields, etc.)
    slog.WithLogger(func(c *gin.Context, l *slog.Logger) *slog.Logger {
      return l.With("request_id", c.GetString("request_id"))
    }),
    // Custom Skipper (function: skip logging if ...), example:
    slog.WithSkipper(func(c *gin.Context) bool {
      return c.Request.Method == "OPTIONS"
    }),
    // Hide sensitive request headers from logs (optional, default hides Authorization/Cookie/etc)
    slog.WithRequestHeader(true), // Set to false to disable logging all request headers
    slog.WithHiddenRequestHeaders([]string{
      "authorization", "cookie", "x-csrf-token", // set your own or reset
    }),
  ))

  r.Run()
}

Logged Fields

Each HTTP request log will include by default:

  • status (int): Response HTTP status code
  • method (string): HTTP method
  • path (string): URL path
  • query (string): Raw query string (excluding ? if empty)
  • route (string): Registered Gin route path (e.g. /api/:name)
  • ip (string): Client IP address
  • latency (duration): Time to handle request
  • referer (string): Client's Referer header, if present
  • user_agent (string): Client's User-Agent header
  • headers (object): (Optional) All HTTP request headers, as a group—see WithRequestHeader and WithHiddenRequestHeaders. Sensitive headers such as Authorization, Cookie, Set-Cookie, x-csrf-token, x-auth-token, x-xsrf-token are hidden by default.
  • body_size (int): Size of the response body

Additional fields can be injected via WithContext.

Log level is determined by status code, per-route configuration, or explicit mapping (see below).

API

Middleware
slog.SetLogger(opts ...Option) gin.HandlerFunc

Creates a Gin middleware handler. All customization is done via options (see next section).

slog.Get(c *gin.Context) *slog.Logger

Retrieves the underlying *slog.Logger from Gin's context. Access this in your handlers for structured custom logging.


Options

All the options below can be passed to SetLogger().

Option Description
WithLogger(fn) Inject a custom logger for each request: func(*gin.Context, *slog.Logger) *slog.Logger
WithContext(fn) Alter the log record per request: func(*gin.Context, *slog.Record) *slog.Record
WithWriter(w io.Writer) Set log output (default: gin.DefaultWriter; e.g., os.Stdout)
WithMessage(msg string) Set a custom message for each log line (default: "Request")
WithSkipPath([]string) List of URL paths to skip logging
WithSkipPathRegexps(...*regexp.Regexp) Regexps to match paths to skip logging
WithSkipper(fn) Custom Skipper function: func(c *gin.Context) bool—return true to skip this request
WithUTC(bool) Use UTC instead of local time
WithDefaultLevel(slog.Level) Level for requests with status < 400 (default: Info)
WithClientErrorLevel(slog.Level) Level for 4xx (default: Warn)
WithServerErrorLevel(slog.Level) Level for 5xx (default: Error)
WithPathLevel(map[string]slog.Level) Map of URL paths to log levels
WithSpecificLogLevelByStatusCode(map[int]slog.Level) Set log level for specific status codes
WithRequestHeader(enabled) Enable or disable logging all HTTP request headers (except hidden ones)
WithHiddenRequestHeaders([]string) Set which request headers to hide from logs (default hides Authorization, Cookie, Set-Cookie, x-auth-token, x-csrf-token, x-xsrf-token). Case-insensitive.

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Get

func Get(c *gin.Context) *slog.Logger

Get retrieves the *slog.Logger instance from the given gin.Context. It assumes that the logger has been previously set in the context with the key loggerKey. If the logger is not found, it will panic.

Parameters:

c - the gin.Context from which to retrieve the logger.

Returns:

*slog.Logger - the logger instance stored in the context.

func ParseLevel

func ParseLevel(levelStr string) (slog.Level, error)

ParseLevel parses a string representation of a log level and returns the corresponding slog.Level. It takes a single argument:

  • levelStr: a string representing the log level (e.g., "debug", "info", "warn", "error").

It returns:

  • slog.Level: the parsed log level.
  • error: an error if the log level string is invalid.

func SetLogger

func SetLogger(opts ...Option) gin.HandlerFunc

SetLogger returns a gin.HandlerFunc (middleware) that logs requests using slog. It accepts a variadic number of Option functions to customize the logger's behavior.

The logger configuration includes:

  • defaultLevel: the default logging level (default: slog.LevelInfo).
  • clientErrorLevel: the logging level for client errors (default: slog.LevelWarn).
  • serverErrorLevel: the logging level for server errors (default: slog.LevelError).
  • output: the output writer for the logger (default: gin.DefaultWriter).
  • skipPath: a list of paths to skip logging.
  • skipPathRegexps: a list of regular expressions to skip logging for matching paths.
  • logger: a custom logger function to use instead of the default logger.

The middleware logs the following request details:

  • method: the HTTP method of the request.
  • path: the URL path of the request.
  • ip: the client's IP address.
  • user_agent: the User-Agent header of the request.
  • status: the HTTP status code of the response.
  • latency: the time taken to process the request.
  • body_size: the size of the response body.

The logging level for each request is determined based on the response status code:

  • clientErrorLevel for 4xx status codes.
  • serverErrorLevel for 5xx status codes.
  • defaultLevel for other status codes.
  • Custom levels can be set for specific paths using the pathLevels configuration.

Types

type EventFn

type EventFn func(*gin.Context, *slog.Record) *slog.Record

EventFn is a function type that takes a gin.Context and a *slog.Record as parameters, and returns a *slog.Record. It is typically used to modify or enhance the record within the context of a Gin HTTP request.

type Fn

type Fn func(*gin.Context, *slog.Logger) *slog.Logger

Fn is a function type that takes a gin.Context and a *slog.Logger as parameters, and returns a *slog.Logger. It is typically used to modify or enhance the logger within the context of a Gin HTTP request.

type Option

type Option interface {
	// contains filtered or unexported methods
}

func WithClientErrorLevel

func WithClientErrorLevel(lvl slog.Level) Option

WithClientErrorLevel sets client error log level (400-499).

func WithContext

func WithContext(fn func(*gin.Context, *slog.Record) *slog.Record) Option

WithContext sets a custom context handler for slog.Record.

func WithDefaultLevel

func WithDefaultLevel(lvl slog.Level) Option

WithDefaultLevel sets config defaultLevel (<400 status).

func WithHiddenRequestHeaders added in v1.1.0

func WithHiddenRequestHeaders(headers []string) Option

WithHiddenRequestHeaders sets request header names to be hidden. Only works with WithRequestHeader enabled.

func WithLogger

func WithLogger(fn func(*gin.Context, *slog.Logger) *slog.Logger) Option

WithLogger sets a logger function to the config.

func WithMessage

func WithMessage(message string) Option

WithMessage sets a custom log message for requests.

func WithPathLevel

func WithPathLevel(m map[string]slog.Level) Option

WithPathLevel sets path-specific logging levels.

func WithRequestHeader added in v1.1.0

func WithRequestHeader(enabled bool) Option

WithRequestHeader enables/disables logging all HTTP request headers.

func WithServerErrorLevel

func WithServerErrorLevel(lvl slog.Level) Option

WithServerErrorLevel sets server error log level.

func WithSkipPath

func WithSkipPath(s []string) Option

WithSkipPath sets URL path list for skipPath in config.

func WithSkipPathRegexps

func WithSkipPathRegexps(regs ...*regexp.Regexp) Option

WithSkipPathRegexps appends regexp rules for skipPathRegexps in config.

func WithSkipper

func WithSkipper(s Skipper) Option

WithSkipper sets a function to skip logging for certain requests.

func WithSpecificLogLevelByStatusCode

func WithSpecificLogLevelByStatusCode(statusCodes map[int]slog.Level) Option

WithSpecificLogLevelByStatusCode sets specific log level per HTTP status.

func WithUTC

func WithUTC(s bool) Option

WithUTC sets UTC mode for logging time.

func WithWriter

func WithWriter(s io.Writer) Option

WithWriter sets the log output destination.

type Skipper

type Skipper func(c *gin.Context) bool

Skipper defines a function to skip middleware. It takes a gin.Context as input and returns a boolean indicating whether to skip the middleware for the given context.

Jump to

Keyboard shortcuts

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