logger

package
v0.36.0 Latest Latest
Warning

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

Go to latest
Published: Jul 7, 2026 License: MIT Imports: 14 Imported by: 0

Documentation

Overview

Package logger provides colorized console logging and file-based access/error logging.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func AccessClose

func AccessClose()

AccessClose closes all access log files.

func AccessEnabled

func AccessEnabled() bool

AccessEnabled reports whether any access log output is active (file or console). Used by the handler to skip building AccessEntry when nothing would be emitted.

func AccessReopenFiles

func AccessReopenFiles() error

AccessReopenFiles reopens all access log files (called during SIGHUP rotation).

func ClientIP

func ClientIP(r *http.Request) string

ClientIP extracts the client IP address from a request, checking X-Forwarded-For, X-Real-Ip, and RemoteAddr in order.

func Close

func Close()

Close flushes and closes all managed log files.

func LogAccess

func LogAccess(routeID string, entry AccessEntry)

LogAccess writes an access log entry to the appropriate file and console.

Console output uses slog with level based on status code:

2xx/3xx → info, 4xx → warn, 5xx → error

File output is JSON lines (one object per line).

func NewServerErrorLog

func NewServerErrorLog() *log.Logger

NewServerErrorLog returns a *log.Logger that routes all messages through slog at DEBUG level. Set this as the ErrorLog field on http.Server.

func ParseLevel

func ParseLevel(s string) slog.Level

ParseLevel converts a level string to slog.Level.

func ReopenFiles

func ReopenFiles() error

ReopenFiles closes and re-opens all log files. Designed for SIGHUP-triggered rotation with external tools like logrotate.

func Setup

func Setup(cfg Config) error

Setup configures the global slog default with a colorized console handler and an optional error log file handler.

func SetupAccess

func SetupAccess(globalPath string, routePaths map[string]string) error

SetupAccess configures access log file destinations. globalPath sets the default access log file. routePaths maps route IDs to per-route log files. The special value "off" disables all access logging (both file and console) for that route. Routes without an explicit path fall back to the global file.

Types

type AccessEntry

type AccessEntry struct {
	Timestamp time.Time `json:"ts"`
	Service   string    `json:"service"`
	Method    string    `json:"method"`
	Path      string    `json:"path"`
	Status    int       `json:"status"`
	Duration  float64   `json:"duration_ms"`
	BytesOut  int64     `json:"bytes_out"`
	ClientIP  string    `json:"client_ip"`
	UserAgent string    `json:"user_agent,omitempty"`
}

AccessEntry represents a single access log record.

type Config

type Config struct {
	Level    string // "debug", "info", "warn", "error"
	ErrorLog string // file path for error-level log (empty = disabled)
}

Config holds logger initialization parameters.

type ConsoleHandler

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

ConsoleHandler is a slog.Handler that writes colorized, compact log lines to a writer.

Output format:

15:04:05 INF message key=value key2=value2

func NewConsoleHandler

func NewConsoleHandler(w io.Writer, opts *slog.HandlerOptions) *ConsoleHandler

NewConsoleHandler creates a handler that writes compact, human-friendly log lines. Color output is auto-detected based on terminal capabilities.

func (*ConsoleHandler) Enabled

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

func (*ConsoleHandler) Handle

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

func (*ConsoleHandler) WithAttrs

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

func (*ConsoleHandler) WithGroup

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

type FileWriter

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

FileWriter is a thread-safe file writer that supports reopen for log rotation. Designed to work with external rotation tools (e.g. logrotate) via SIGHUP.

func NewFileWriter

func NewFileWriter(path string) (*FileWriter, error)

NewFileWriter opens a file in append mode for writing log entries.

func (*FileWriter) Close

func (w *FileWriter) Close() error

Close flushes and closes the underlying file.

func (*FileWriter) Reopen

func (w *FileWriter) Reopen() error

Reopen closes and re-opens the file. This allows external log rotation tools to rename the file and have the writer create a fresh one.

func (*FileWriter) Write

func (w *FileWriter) Write(p []byte) (int, error)

type ResponseCapture

type ResponseCapture struct {
	http.ResponseWriter
	// contains filtered or unexported fields
}

ResponseCapture wraps http.ResponseWriter to record the status code and bytes written. It is used by the access log middleware. When the connection is hijacked (WebSocket), Status() returns 101 to reflect the protocol switch.

func NewResponseCapture

func NewResponseCapture(w http.ResponseWriter) *ResponseCapture

NewResponseCapture wraps a ResponseWriter for access log capturing.

func (*ResponseCapture) BytesOut

func (rc *ResponseCapture) BytesOut() int64

BytesOut returns the total bytes written to the response body.

func (*ResponseCapture) Hijack

func (rc *ResponseCapture) Hijack() (net.Conn, *bufio.ReadWriter, error)

Hijack implements http.Hijacker. It marks the connection as hijacked so Status() reports 101 (Switching Protocols) in the access log.

func (*ResponseCapture) Reset

func (rc *ResponseCapture) Reset(w http.ResponseWriter)

Reset reinitializes a ResponseCapture for reuse from a pool.

func (*ResponseCapture) Status

func (rc *ResponseCapture) Status() int

Status returns the recorded HTTP status code. For hijacked connections (WebSocket), returns 101 Switching Protocols.

func (*ResponseCapture) Unwrap

func (rc *ResponseCapture) Unwrap() http.ResponseWriter

Unwrap returns the original ResponseWriter. This allows http.ResponseController to discover interfaces like http.Flusher and http.Hijacker on the inner writer.

func (*ResponseCapture) Write

func (rc *ResponseCapture) Write(b []byte) (int, error)

func (*ResponseCapture) WriteHeader

func (rc *ResponseCapture) WriteHeader(code int)

Jump to

Keyboard shortcuts

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