Documentation
¶
Index ¶
- Constants
- Variables
- func DefaultLogFormatter(param LogFormatterParams) string
- func HandlerWithConfig(conf LoggerConfig, next http.Handler) (http.Handler, error)
- func HandlerWithFormatter(f LogFormatter, next http.Handler) (http.Handler, error)
- func HandlerWithFormatterAndName(routerName string, f LogFormatter, next http.Handler) (http.Handler, error)
- func HandlerWithName(routerName string, next http.Handler) (http.Handler, error)
- func HandlerWithWriter(out io.Writer, next http.Handler, notlogged ...string) (http.Handler, error)
- func Logger(next http.Handler) (http.Handler, error)
- func RemoteIP(r *http.Request) string
- func RequestBodyLogFormatter(param LogFormatterParams) string
- func RequestHeaderLogFormatter(param LogFormatterParams) string
- func ResponseBodyLogFormatter(param LogFormatterParams) string
- func ResponseHeaderLogFormatter(param LogFormatterParams) string
- func ShortLogFormatter(param LogFormatterParams) string
- func ValidateConfig(conf LoggerConfig) error
- type ColorMode
- type ConfigBuilder
- func (b *ConfigBuilder) Build() (LoggerConfig, error)
- func (b *ConfigBuilder) WithAsyncLogging(enabled bool, bufferSize int) *ConfigBuilder
- func (b *ConfigBuilder) WithCaptureRequestBody(capture bool) *ConfigBuilder
- func (b *ConfigBuilder) WithCaptureResponseBody(capture bool) *ConfigBuilder
- func (b *ConfigBuilder) WithColorMode(mode ColorMode) *ConfigBuilder
- func (b *ConfigBuilder) WithFormatter(f LogFormatter) *ConfigBuilder
- func (b *ConfigBuilder) WithHideHeaderKeys(keys ...string) *ConfigBuilder
- func (b *ConfigBuilder) WithMinLevel(level Level) *ConfigBuilder
- func (b *ConfigBuilder) WithOutput(w io.Writer) *ConfigBuilder
- func (b *ConfigBuilder) WithProxyHandler(proxy *Proxy) *ConfigBuilder
- func (b *ConfigBuilder) WithRouterName(name string) *ConfigBuilder
- func (b *ConfigBuilder) WithSampleRate(rate float64) *ConfigBuilder
- func (b *ConfigBuilder) WithSkipPaths(paths ...string) *ConfigBuilder
- type Level
- type LogFormatter
- type LogFormatterParams
- type LoggerConfig
- type LoggingMiddleware
- func LoggerWithConfig(conf LoggerConfig) (*LoggingMiddleware, error)
- func LoggerWithFormatter(f LogFormatter) (*LoggingMiddleware, error)
- func LoggerWithFormatterAndName(routerName string, f LogFormatter) (*LoggingMiddleware, error)
- func LoggerWithName(routerName string) (*LoggingMiddleware, error)
- func LoggerWithWriter(out io.Writer, notlogged ...string) (*LoggingMiddleware, error)
- type Proxy
- type ProxyType
- type ResponseWriter
Constants ¶
const ( // ProxyGoogleAppEngine when running on Google App Engine. Trust X-Appengine-Remote-Addr // for determining the client's IP ProxyGoogleAppEngine = "X-Appengine-Remote-Addr" // ProxyCloudflare when using Cloudflare's CDN. Trust CF-Connecting-IP for determining // the client's IP ProxyCloudflare = "CF-Connecting-IP" // ProxyDefaultType represents default proxy type ProxyDefaultType = "" )
Supported proxies
Variables ¶
var DefaultErrorWriter io.Writer = os.Stderr
DefaultErrorWriter is the default io.Writer used by httplog to debug errors
var DefaultLogFormatterWithRequestHeader = ChainLogFormatter(DefaultLogFormatter, RequestHeaderLogFormatter)
DefaultLogFormatterWithHeaders is a combination of default log formatter and header log formatter
var DefaultLogFormatterWithRequestHeadersAndBody = ChainLogFormatter(DefaultLogFormatter, RequestHeaderLogFormatter, RequestBodyLogFormatter)
DefaultLogFormatterWithHeadersAndBody is a combination of default log formatter, header log formatter and json body
var DefaultLogFormatterWithResponseHeader = ChainLogFormatter(DefaultLogFormatter, ResponseHeaderLogFormatter)
DefaultLogFormatterWithHeader is a combination of default log formatter and header log formatter
var DefaultLogFormatterWithResponseHeadersAndBody = ChainLogFormatter(DefaultLogFormatter, ResponseHeaderLogFormatter, ResponseBodyLogFormatter)
DefaultLogFormatterWithHeadersAndBody is a combination of default log formatter, header log formatter and json body
var DefaultRemoteIPHeaders = []string{"X-Forwarded-For", "X-Real-IP"}
Default proxy remote IP headers
var DefaultWriter io.Writer = os.Stdout
DefaultWriter is the default io.Writer used by httplog for middleware output Logger() and Body(). To support coloring in Windows use:
import "github.com/mattn/go-colorable" httplog.DefaultWriter = colorable.NewColorableStdout()
var FullFormatterWithRequestAndResponseHeadersAndBody = ChainLogFormatter(DefaultLogFormatter, RequestHeaderLogFormatter, RequestBodyLogFormatter, ResponseHeaderLogFormatter, ResponseBodyLogFormatter)
Functions ¶
func DefaultLogFormatter ¶
func DefaultLogFormatter(param LogFormatterParams) string
DefaultLogFormatter is the default log format function Logger middleware uses.
func HandlerWithConfig ¶
HandlerWithConfig instance a Logger handler with config and next handler.
func HandlerWithFormatter ¶
HandlerWithFormatter instance a Logger handler with the specified log format function and next handler.
func HandlerWithFormatterAndName ¶
func HandlerWithFormatterAndName(routerName string, f LogFormatter, next http.Handler) (http.Handler, error)
HandlerWithFormatterAndName instance a Logger handler with the specified log format function and next handler.
func HandlerWithName ¶
HandlerWithName instance a Logger handler with the specified prefix name and next handler.
func HandlerWithWriter ¶
HandlerWithWriter instance a Logger handler with the specified writer buffer and next handler. Example: os.Stdout, a file opened in write mode, a socket...
func Logger ¶
Logger instances a Logger middleware that will write the logs to console. By default, gin.DefaultWriter = os.Stdout.
func RemoteIP ¶
RemoteIP parses the IP from Request.RemoteAddr, normalizes and returns the IP (without the port).
func RequestBodyLogFormatter ¶
func RequestBodyLogFormatter(param LogFormatterParams) string
RequestBodyLogFormatter format function with JSON body output or text Note: Requires CaptureRequestBody to be enabled in LoggerConfig
func RequestHeaderLogFormatter ¶
func RequestHeaderLogFormatter(param LogFormatterParams) string
HeaderLogFormatter format function with headers output.
func ResponseBodyLogFormatter ¶
func ResponseBodyLogFormatter(param LogFormatterParams) string
ResponseBodyLogFormatter format function with JSON body output or text
func ResponseHeaderLogFormatter ¶
func ResponseHeaderLogFormatter(param LogFormatterParams) string
ResponseHeaderLogFormatter format function with headers output.
func ShortLogFormatter ¶
func ShortLogFormatter(param LogFormatterParams) string
func ValidateConfig ¶
func ValidateConfig(conf LoggerConfig) error
ValidateConfig validates LoggerConfig before middleware creation Returns detailed error if invalid, nil if valid
Types ¶
type ConfigBuilder ¶
type ConfigBuilder struct {
// contains filtered or unexported fields
}
ConfigBuilder provides fluent API for building LoggerConfig
func NewConfigBuilder ¶
func NewConfigBuilder() *ConfigBuilder
NewConfigBuilder creates a new builder with defaults
func (*ConfigBuilder) Build ¶
func (b *ConfigBuilder) Build() (LoggerConfig, error)
Build creates LoggerConfig and validates it Returns error if configuration is invalid
func (*ConfigBuilder) WithAsyncLogging ¶
func (b *ConfigBuilder) WithAsyncLogging(enabled bool, bufferSize int) *ConfigBuilder
WithAsyncLogging enables async logging with buffer size
func (*ConfigBuilder) WithCaptureRequestBody ¶
func (b *ConfigBuilder) WithCaptureRequestBody(capture bool) *ConfigBuilder
WithCaptureRequestBody enables request body capture
func (*ConfigBuilder) WithCaptureResponseBody ¶
func (b *ConfigBuilder) WithCaptureResponseBody(capture bool) *ConfigBuilder
WithCaptureResponseBody enables response body capture
func (*ConfigBuilder) WithColorMode ¶
func (b *ConfigBuilder) WithColorMode(mode ColorMode) *ConfigBuilder
WithColorMode sets the color mode
func (*ConfigBuilder) WithFormatter ¶
func (b *ConfigBuilder) WithFormatter(f LogFormatter) *ConfigBuilder
WithFormatter sets the log formatter
func (*ConfigBuilder) WithHideHeaderKeys ¶
func (b *ConfigBuilder) WithHideHeaderKeys(keys ...string) *ConfigBuilder
WithHideHeaderKeys adds header keys to mask
func (*ConfigBuilder) WithMinLevel ¶
func (b *ConfigBuilder) WithMinLevel(level Level) *ConfigBuilder
WithMinLevel sets the minimum log level
func (*ConfigBuilder) WithOutput ¶
func (b *ConfigBuilder) WithOutput(w io.Writer) *ConfigBuilder
WithOutput sets the output writer
func (*ConfigBuilder) WithProxyHandler ¶
func (b *ConfigBuilder) WithProxyHandler(proxy *Proxy) *ConfigBuilder
WithProxyHandler sets the proxy handler
func (*ConfigBuilder) WithRouterName ¶
func (b *ConfigBuilder) WithRouterName(name string) *ConfigBuilder
WithRouterName sets the router name prefix
func (*ConfigBuilder) WithSampleRate ¶
func (b *ConfigBuilder) WithSampleRate(rate float64) *ConfigBuilder
WithSampleRate sets the sample rate (0.0-1.0)
func (*ConfigBuilder) WithSkipPaths ¶
func (b *ConfigBuilder) WithSkipPaths(paths ...string) *ConfigBuilder
WithSkipPaths adds paths to skip logging
type Level ¶
type Level int
Level represents log severity level
func LevelFromStatusCode ¶
LevelFromStatusCode determines log level from HTTP status code
type LogFormatter ¶
type LogFormatter func(params LogFormatterParams) string
LogFormatter gives the signature of the formatter function passed to LoggerWithFormatter you can use predefined, like httplog.DefaultLogFormatter or httplog.ShortLogFormatter or you can create your custom
func ChainLogFormatter ¶
func ChainLogFormatter(formatters ...LogFormatter) LogFormatter
ChainLogFormatter chain a list of log formatters
func DefaultSlogLogger ¶
func DefaultSlogLogger(logger *slog.Logger) LogFormatter
DefaultSlogLogger creates a default slog formatter with Info level
func DefaultSlogLoggerWithHeaders ¶
func DefaultSlogLoggerWithHeaders(logger *slog.Logger) LogFormatter
DefaultSlogLoggerWithHeaders creates a slog formatter that also logs headers
func SlogLogger ¶
SlogLogger returns a LogFormatter that logs to slog Parameters:
- logger: *slog.Logger instance
- level: slog.Level (LevelDebug, LevelInfo, LevelWarn, LevelError)
- message: Log message prefix (e.g., "HTTP Request")
The formatter extracts trace ID from context (if present) and logs structured attributes: method, path, status, latency, client_ip, body_size
Example:
slogger := slog.New(slog.NewJSONHandler(os.Stdout, nil))
conf := httplog.LoggerConfig{
Formatter: httplog.SlogLogger(slogger, slog.LevelInfo, "HTTP"),
}
middleware, _ := httplog.LoggerWithConfig(conf)
type LogFormatterParams ¶
type LogFormatterParams struct {
Request *http.Request
// Context from http.Request for trace ID extraction, etc.
Context context.Context
// Router prints router name in the log.
// If you have more than one router it is useful to get one's name in a console output.
RouterName string
// TimeStamp shows the time after the server returns a response.
TimeStamp time.Time
// StatusCode is HTTP response code.
StatusCode int
// Latency is how much time the server cost to process a certain request.
Latency time.Duration
// ClientIP calculated real IP of requester, see Proxy for details.
ClientIP string
// Method is the HTTP method given to the request.
Method string
// Path is a path the client requests.
Path string
// BodySize is the size of the Response Body
BodySize int
// ResponseBody is the response body content (if captured)
ResponseBody []byte
// RequestBody is the request body content (if captured)
RequestBody []byte
// Response header
ResponseHeader http.Header
// RequestHeader are the request headers (masked if configured)
RequestHeader http.Header
// Level is the log level for this request
Level Level
// contains filtered or unexported fields
}
LogFormatterParams is the structure any formatter will be handed when time to log comes
func (*LogFormatterParams) IsOutputColor ¶
func (p *LogFormatterParams) IsOutputColor() bool
IsOutputColor indicates whether can colors be outputted to the log.
func (*LogFormatterParams) MethodColor ¶
func (p *LogFormatterParams) MethodColor() string
MethodColor is the ANSI color for appropriately logging http method to a terminal.
func (*LogFormatterParams) ResetColor ¶
func (p *LogFormatterParams) ResetColor() string
ResetColor resets all escape attributes.
func (*LogFormatterParams) StatusCodeColor ¶
func (p *LogFormatterParams) StatusCodeColor() string
StatusCodeColor is the ANSI color for appropriately logging http status code to a terminal.
type LoggerConfig ¶
type LoggerConfig struct {
// ColorMode controls color output behavior
// Default: ColorAuto (detect terminal)
ColorMode ColorMode
// Optional. Default value is httplog.DefaultLogFormatter
Formatter LogFormatter
// Output is a writer where logs are written.
// Optional. Default value is httplog.DefaultWriter.
Output io.Writer
// SkipPaths is an url path array which logs are not written.
// Could be a regexp like: /user/payment/*
// Optional.
SkipPaths []string
// HideHeader is a header keys array which value should be masked with ****.
// Optional.
HideHeaderKeys []string
// ProxyHandler is a instance of Proxy struct with could get remote IP using proxy data
// Default is default httplog.NewLogger()
// If you run you instance on Google App engine or Cloudflare,
// you need to create explicit Proxy instance with httplog.NewLoggerWithType(...)
ProxyHandler *Proxy
// Router prints router name in the log.
// If you have more than one router it is useful to get one's name in a console output.
RouterName string
// CaptureResponseBody saves response body copy for debug purposes
// WARNING: Increases memory usage, use for debugging only
// Default: false
CaptureResponseBody bool
// CaptureRequestBody enables request body capture
// Captured in middleware (not formatter) to prevent mutation
// WARNING: Increases memory usage, use for debugging only
// Default: false
CaptureRequestBody bool
// SampleRate controls what percentage of requests to log
// Range: 0.0 (0% - log nothing) to 1.0 (100% - log all)
// Use -1 or leave unset to use default (100%)
// Example: 0.01 = 1%, 0.1 = 10%
// Default: -1 (100% - log all requests)
SampleRate float64
// DeterministicSampling uses hash-based sampling instead of random
// When true, same request path/method will consistently be sampled or not
// Useful for reproducible behavior and debugging
// Default: false (random sampling)
DeterministicSampling bool
// AsyncLogging enables asynchronous log writing
// Reduces request latency, but may lose logs on crash
// Default: false (synchronous)
AsyncLogging bool
// AsyncBufferSize is the channel buffer size for async logging
// Only used if AsyncLogging is true
// Default: 1000
AsyncBufferSize int
// MinLevel is the minimum log level to output
// Requests below this level are not logged
// Level determined by status code:
// - 2xx, 3xx: Info
// - 4xx: Warn
// - 5xx: Error
// Default: LevelInfo
MinLevel Level
}
LoggerConfig defines the config for Logger middleware.
type LoggingMiddleware ¶
type LoggingMiddleware struct {
Handler func(next http.Handler) http.Handler
// contains filtered or unexported fields
}
LoggingMiddleware wraps the logging middleware with lifecycle methods
func LoggerWithConfig ¶
func LoggerWithConfig(conf LoggerConfig) (*LoggingMiddleware, error)
LoggerWithConfig instance a Logger middleware with config.
func LoggerWithFormatter ¶
func LoggerWithFormatter(f LogFormatter) (*LoggingMiddleware, error)
LoggerWithFormatter instance a Logger middleware with the specified log format function.
func LoggerWithFormatterAndName ¶
func LoggerWithFormatterAndName(routerName string, f LogFormatter) (*LoggingMiddleware, error)
LoggerWithFormatterAndName instance a Logger middleware with the specified log format function.
func LoggerWithName ¶
func LoggerWithName(routerName string) (*LoggingMiddleware, error)
LoggerWithName instance a Logger middleware with the specified name prefix.
func LoggerWithWriter ¶
func LoggerWithWriter(out io.Writer, notlogged ...string) (*LoggingMiddleware, error)
LoggerWithWriter instance a Logger middleware with the specified writer buffer. Example: os.Stdout, a file opened in write mode, a socket...
func (*LoggingMiddleware) Close ¶
func (m *LoggingMiddleware) Close()
Close cleanly shuts down async logging goroutine
type Proxy ¶
type Proxy struct {
RemoteIPHeaders []string
// contains filtered or unexported fields
}
func NewProxy ¶
func NewProxy() *Proxy
NewProxy creates and returns default proxy with default params
func NewProxyWithType ¶
NewProxy creates and returns proxy with specific type
func NewProxyWithTypeAndHeaders ¶
NewProxy creates and returns proxy with specific type and proxy headers
func (*Proxy) ClientIP ¶
ClientIP implements one best effort algorithm to return the real client IP. It calls c.RemoteIP() under the hood, to check if the remote IP is a trusted proxy or not. If it is it will then try to parse the headers defined in Engine.RemoteIPHeaders (defaulting to [X-Forwarded-For, X-Real-Ip]). If the headers are not syntactically valid OR the remote IP does not correspond to a trusted proxy, the remote IP (coming from Request.RemoteAddr) is returned.
type ResponseWriter ¶
type ResponseWriter interface {
http.ResponseWriter
http.Hijacker
http.Flusher
http.Pusher
// Status returns the status code of the response or 0 if the response has
// not been written
Status() int
// Written returns whether or not the ResponseWriter has been written.
Written() bool
// Size returns the size of the response body.
Size() int
// Before allows for a function to be called before the ResponseWriter has been written to. This is
// useful for setting headers or any other operations that must happen before a response has been written.
Before(func(ResponseWriter))
// Optional copy of response body
// If you need to log or save full response bodies - use it
// But extra memory and CPU will be used for that
Body() []byte
// Manually set Status and Size if you need, written is set as well after call
Set(status, size int)
}
ResponseWriter is a wrapper around http.ResponseWriter that provides extra information about the response. It is recommended that middleware handlers use this construct to wrap a responsewriter if the functionality calls for it.
func NewResponseWriter ¶
func NewResponseWriter(rw http.ResponseWriter) ResponseWriter
NewResponseWriter creates a ResponseWriter that wraps an http.ResponseWriter
func NewResponseWriterWithBody ¶
func NewResponseWriterWithBody(rw http.ResponseWriter) ResponseWriter
NewResponseWriterWithBody creates a ResponseWriter that wraps an http.ResponseWriter and copy the body of response. The body is not copied if you use ReadFrom for obvious reason
func NewWriter ¶
func NewWriter(rw http.ResponseWriter, captureBody bool) ResponseWriter
NewWriter creates a ResponseWriter that wraps an http.ResponseWriter and optionaly capture body



