logger

package
v0.1.0 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2026 License: Apache-2.0 Imports: 7 Imported by: 0

Documentation

Overview

Package logger provides HTTP request logging middleware for celeris.

The middleware logs each request with configurable fields including method, path, status, latency, and bytes written. It supports both standard slog handlers and the zero-alloc FastHandler.

Basic usage with the default slog output:

server.Use(logger.New())

Using the zero-alloc FastHandler with color output:

mw := logger.New(logger.Config{
    Output: slog.New(logger.NewFastHandler(os.Stderr, &logger.FastHandlerOptions{
        Color: true,
    })),
})
server.Use(mw)

NewFastHandler creates a FastHandler that formats log records directly into a pooled byte buffer, producing output compatible with slog.TextHandler. When FastHandlerOptions.Color is true, status codes, HTTP methods, and latency values are colored with ANSI escape codes (e.g., green for 2xx, red for 5xx). Configure its minimum level via FastHandlerOptions.

Body Capture

Set Config.CaptureRequestBody and/or Config.CaptureResponseBody to log request and response bodies. Bodies are truncated to Config.MaxCaptureBytes (default 4096).

server.Use(logger.New(logger.Config{
    CaptureRequestBody:  true,
    CaptureResponseBody: true,
    MaxCaptureBytes:     2048,
}))

Request ID Integration

The middleware automatically reads the request ID from the context store (key "request_id") first, falling back to the x-request-id header. This integrates seamlessly with the requestid middleware when both are installed. Additional fields can be added via Config.Fields.

Index

Examples

Constants

This section is empty.

Variables

View Source
var DefaultConfig = Config{}

DefaultConfig is the default logger configuration.

Functions

func New

func New(config ...Config) celeris.HandlerFunc

New creates a logger middleware with the given config.

Example
package main

import (
	"github.com/goceleris/middlewares/logger"
)

func main() {
	// Zero-config: logs to slog.Default() with INFO/WARN/ERROR levels.
	_ = logger.New()
}
Example (CustomFields)
package main

import (
	"io"
	"log/slog"

	"github.com/goceleris/middlewares/logger"
)

func main() {
	// Discard output for example; add custom fields to every log entry.
	log := slog.New(slog.NewJSONHandler(io.Discard, nil))
	_ = logger.New(logger.Config{
		Output:    log,
		SkipPaths: []string{"/health", "/ready"},
	})
}
Example (FastHandler)
package main

import (
	"log/slog"
	"os"

	"github.com/goceleris/middlewares/logger"
)

func main() {
	// FastHandler: zero-allocation structured logging with color output.
	log := slog.New(logger.NewFastHandler(os.Stderr, &logger.FastHandlerOptions{
		Color: true,
	}))
	_ = logger.New(logger.Config{Output: log})
}

Types

type Config

type Config struct {
	// Skip defines a function to skip this middleware for certain requests.
	Skip func(c *celeris.Context) bool

	// Output is the slog logger to use. Default: slog.Default().
	Output *slog.Logger

	// Level maps a response status code to a log level.
	// Default: 5xx→Error, 4xx→Warn, else→Info.
	Level func(status int) slog.Level

	// Fields adds custom fields to the log entry.
	Fields func(c *celeris.Context, latency time.Duration) []slog.Attr

	// SkipPaths lists paths to skip (exact match).
	SkipPaths []string

	// CaptureRequestBody logs the request body (truncated to MaxCaptureBytes).
	CaptureRequestBody bool

	// CaptureResponseBody logs the response body (truncated to MaxCaptureBytes).
	// Requires the response to be captured via c.CaptureResponse().
	CaptureResponseBody bool

	// MaxCaptureBytes is the maximum number of body bytes to log.
	// Default: 4096. Prevents OOM on large request/response bodies.
	MaxCaptureBytes int
}

Config defines the logger middleware configuration.

type FastHandler

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

FastHandler is a high-performance slog.Handler that formats log records directly into a pooled byte buffer with zero allocations in steady state. It produces output compatible with slog.TextHandler's format.

Use it as a drop-in replacement for slog.TextHandler when performance matters more than customization:

log := slog.New(logger.NewFastHandler(os.Stderr, nil))
mw := logger.New(logger.Config{Output: log})

func NewFastHandler

func NewFastHandler(w io.Writer, opts *FastHandlerOptions) *FastHandler

NewFastHandler creates a new FastHandler writing to w.

func (*FastHandler) Enabled

func (h *FastHandler) Enabled(_ context.Context, level slog.Level) bool

Enabled reports whether the handler handles records at the given level.

func (*FastHandler) Handle

func (h *FastHandler) Handle(_ context.Context, r slog.Record) error

Handle formats the record and writes it to the output.

func (*FastHandler) WithAttrs

func (h *FastHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a new handler with the given attributes pre-formatted.

func (*FastHandler) WithGroup

func (h *FastHandler) WithGroup(name string) slog.Handler

WithGroup returns a new handler with the given group name prepended to all subsequent attribute keys.

type FastHandlerOptions

type FastHandlerOptions struct {
	// Level is the minimum log level. Default: slog.LevelInfo.
	Level slog.Level
	// Color enables ANSI color codes in output.
	// Level names are colored: red=ERROR, yellow=WARN, green=INFO, cyan=DEBUG.
	Color bool
}

FastHandlerOptions configures a FastHandler.

Jump to

Keyboard shortcuts

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