logger

package
v0.5.0 Latest Latest
Warning

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

Go to latest
Published: Nov 18, 2026 License: MIT, MIT Imports: 22 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

logger

GoDoc

logger is an HTTP request logger that implements correlated logging to one of several supported platforms. Each HTTP request is logged as the parent log, with all logs generated during the request as child logs.

The Logging destination is configured with an Exporter. This package provides Exporters for Google Cloud Logging, AWS Logging, and Console Logging.

The GoogleCloudExporter will also correlate logs to Cloud Trace if you instrument your code with tracing.

The ConsoleExporter is useful for local development and debugging.

The AWSExporter will also correlate logs to AWS X-Ray if you instrument your code with tracing and have logs sent to Cloudwatch. Note that additional configuration in the tracing is required to enable the correlation. In the tracing configuration, you must set the log group names to where the logs are being sent.

What a request writes: the policy

Each request, and each command-line run, carries a policy that decides at its end whether the parent entry is written. Lines the application logs during the request attach to it as child entries. The policy is one of four words:

Word Constructor The parent entry is written when
always logger.Always() the request ends, whatever happened. Today's behavior and the default of every exporter.
on event logger.OnEvent() a line attached to the request, or the request failed: it answered 400 or above, or the run returned an error. A 500 raises the entry to error.
sampled logger.Sampled(fraction) as on event, plus the declared fraction of the quiet requests, drawn once per request. The fraction must be above 0 and at most 1; anything else is refused with a panic.
never logger.Never() not at all, whatever happened. A health check wants this.

MinSeverity adds a floor to any word: logger.OnEvent().MinSeverity(logging.Warning) drops lines below Warning before they attach, so they neither count as an event nor appear as child entries.

The nearest declaration wins, from the outside in:

  1. The exporter's own default: always, or on event for GoogleCloudExporter.LogAll(false) and NewAWSExporter(false).
  2. The request logger's options. logger.DefaultPolicy(p) sets the application default. logger.PolicyByPrefix(map[string]logger.Policy{...}) sets the policy from the request path, longest prefix first, before the default; it is how routes an application mounts by hand get theirs. Both are options of NewRequestLogger; NewCliLogger takes DefaultPolicy.
  3. logger.WithPolicy(p), a middleware on a group of routes or on one route. Deeper setters override earlier ones.
  4. logger.FromCtx(ctx).SetPolicy(p) inside a handler, which promotes or demotes its own request.
r.Use(logger.NewRequestLogger(exporter,
	logger.DefaultPolicy(logger.Always()),
	logger.PolicyByPrefix(map[string]logger.Policy{"/files/": logger.OnEvent()}),
))
r.With(logger.WithPolicy(logger.Never())).Get("/healthz", health)

Every exporter honors the decision, the console included, so a local run shows the same behavior as the cloud. Policy.String() names a policy for a comment: on event, Warning and above.

The equivalence with LogAll

GoogleCloudExporter.LogAll(false) and NewAWSExporter(false) keep working: they set the exporter's default policy to on event, where LogAll(true) and NewAWSExporter(true), the defaults, set always. A DefaultPolicy option on the request logger overrides the exporter's default. One thing changes under on event: a request that answered 400 or above, or a run that returned an error, now writes its entry even when no line attached to it, where LogAll(false) used to drop it. A failure is an event.

Switching the destination at run time

logger.SwitchableExporter is an Exporter whose destination can be replaced while the application runs: a device starts on the console, moves to the cloud once it can reach it, and comes back to the console when it loses that.

exporter := logger.NewSwitchableExporter(nil) // nil means the console exporter
r.Use(logger.NewRequestLogger(exporter))

// once the cloud is reachable
previous := exporter.Swap(logger.NewGoogleCloudExporter(client, projectID))

// and when it is not any more
previous = exporter.Swap(logger.NewConsoleExporter())

A request or run goes to the exporter current when it starts and finishes on it even if a swap happens meanwhile. Swap is safe for concurrent use and returns the previous exporter so the caller can flush or close whatever stands behind it; the Exporter interface has no Close, so that is done on the concrete type the caller built.

Documentation

Overview

Package logger is an HTTP request logger that implements correlated logging to one of several supported platforms. Each HTTP request is logged as the parent log, with all logs generated during the request as child logs.

The Logging destination is configured with an Exporter. This package provides Exporters for Google Cloud Logging, AWS CloudWatch, and Console Logging.

The GoogleCloudExporter will also correlate logs to Cloud Trace if you instrument your code with tracing.

The AWSExporter supports log correlation to AWS X-Ray if you instrument your code with tracing.

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewCliLogger

func NewCliLogger(e Exporter, opts ...RequestLoggerOption) func(ctx context.Context, command string, f func(context.Context) error) error

NewCliLogger returns a function that executes the given function and creates a top-level parent log. The provided command string is used to identify the CLI execution in the logs.

DefaultPolicy sets the Policy each run starts with; a run has no path, so PolicyByPrefix does not apply. Without it, a run starts with the exporter's own default: Always, unless LogAll(false) or NewAWSExporter(false) made it OnEvent. Under OnEvent the run's parent entry is written when a line attached or the function returned an error.

func NewCtx

func NewCtx(ctx context.Context, l *Logger) context.Context

NewCtx associates the logger with the context and returns the resulting context

func NewRequestLogger

func NewRequestLogger(e Exporter, opts ...RequestLoggerOption) func(http.Handler) http.Handler

NewRequestLogger returns a middleware that logs the request and injects a Logger into the context. This Logger can be used during the life of the request, and all logs generated will be correlated to the request log.

DefaultPolicy and PolicyByPrefix set the Policy each request starts with. With neither, a request starts with the exporter's own default and the behavior is unchanged.

If not configured, request logs are sent to stderr by default.

func WithPolicy

func WithPolicy(p Policy) func(http.Handler) http.Handler

WithPolicy returns a middleware that sets the policy on the request's record. Deeper setters override earlier ones, so the nearest declaration wins: a route's over its outlet's, an outlet's over the application default. Without a record, because the request logger did not run, it passes the request through unchanged and does nothing else.

Types

type AWSExporter

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

AWSExporter is an Exporter that logs to stdout in JSON format to be sent to cloudwatch

func NewAWSExporter

func NewAWSExporter(logAll bool) *AWSExporter

NewAWSExporter returns a new AWSExporter. logAll names its default policy: true is Always, and false is OnEvent, which writes a request only when a line attached to it or it failed. A DefaultPolicy option on the request logger overrides this default.

func (*AWSExporter) CliRunner

func (e *AWSExporter) CliRunner() func(context.Context, string, func(context.Context) error) error

CliRunner returns a function that executes the given function and creates a top-level parent log.

func (*AWSExporter) DaemonContext

func (e *AWSExporter) DaemonContext(ctx context.Context) context.Context

DaemonContext returns a context with a logger that writes directly to stdout, unbuffered.

func (*AWSExporter) Middleware

func (e *AWSExporter) Middleware() func(http.Handler) http.Handler

Middleware returns a middleware that logs the request and injects a Logger into the context.

type AttributerLogger

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

AttributerLogger holds the atrributes and logger used for creating a child logger

func (*AttributerLogger) AddAttribute

func (a *AttributerLogger) AddAttribute(key string, value any) *AttributerLogger

AddAttribute adds an attribute (kv) for the child (trace) log and returns a reference to the original AttributerLogger for method chaining purposes If the key matches a reserved key, it will be prefixed with "custom_" If the key already exists, its value is overwritten

func (*AttributerLogger) Logger

func (a *AttributerLogger) Logger() *Logger

Logger returns a Logger with the child (trace) attributes embedded

type ConsoleExporter

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

ConsoleExporter implements exporting to the console

func NewConsoleExporter

func NewConsoleExporter() *ConsoleExporter

NewConsoleExporter returns a configured ConsoleExporter. Its default policy is Always; a DefaultPolicy option on the request logger sets another, so a local run shows the same decisions as the cloud.

func (*ConsoleExporter) CliRunner

func (e *ConsoleExporter) CliRunner() func(context.Context, string, func(context.Context) error) error

CliRunner returns a function that executes the given function and creates a top-level parent log.

func (*ConsoleExporter) DaemonContext

func (e *ConsoleExporter) DaemonContext(ctx context.Context) context.Context

DaemonContext returns a context with a logger that writes directly to the console, unbuffered.

func (*ConsoleExporter) Middleware

func (e *ConsoleExporter) Middleware() func(http.Handler) http.Handler

Middleware returns a middleware that exports logs to the console

func (*ConsoleExporter) NoColor

func (e *ConsoleExporter) NoColor(v bool) *ConsoleExporter

NoColor controls if this logger will use color to highlight log level

type Exporter

type Exporter interface {
	Middleware() func(http.Handler) http.Handler
	CliRunner() func(ctx context.Context, command string, f func(context.Context) error) error
	DaemonContext(ctx context.Context) context.Context
}

Exporter is the interface for implementing a middleware to export logs to some destination

type GoogleCloudExporter

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

GoogleCloudExporter implements exporting to Google Cloud Logging

func NewGoogleCloudExporter

func NewGoogleCloudExporter(client *logging.Client, projectID string, opts ...logging.LoggerOption) *GoogleCloudExporter

NewGoogleCloudExporter returns a configured GoogleCloudExporter

func (*GoogleCloudExporter) CliRunner

func (e *GoogleCloudExporter) CliRunner() func(context.Context, string, func(context.Context) error) error

CliRunner returns a function that executes the given function and creates a top-level parent log.

func (*GoogleCloudExporter) DaemonContext

func (e *GoogleCloudExporter) DaemonContext(ctx context.Context) context.Context

DaemonContext returns a context with a logger that writes directly to the parent log, unbuffered.

func (*GoogleCloudExporter) LogAll

LogAll sets the exporter's default policy: true is Always, the default, and false is OnEvent, which writes a request only when a line attached to it or it failed. A DefaultPolicy option on the request logger overrides this default.

func (*GoogleCloudExporter) Middleware

func (e *GoogleCloudExporter) Middleware() func(http.Handler) http.Handler

Middleware returns a middleware that exports logs to Google Cloud Logging

type Logger

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

Logger implements logging methods for this package

func FromCtx

func FromCtx(ctx context.Context) *Logger

FromCtx returns the logger from the context. If no logger is found, it will write to stderr

func FromReq

func FromReq(r *http.Request) *Logger

FromReq returns the logger from the http request. If no logger is found, it will write to stderr

func (*Logger) AddRequestAttribute

func (l *Logger) AddRequestAttribute(key string, value any) *Logger

AddRequestAttribute adds an attribute (kv) for the parent request log and returns a reference to the original logger for method chaining purposes If the key matches a reserved key, it will be prefixed with "custom_" If the key already exists, its value is overwritten

func (*Logger) Debug

func (l *Logger) Debug(v any)

Debug logs a debug message.

func (*Logger) Debugf

func (l *Logger) Debugf(format string, v ...any)

Debugf logs a debug message with format.

func (*Logger) Error

func (l *Logger) Error(v any)

Error logs an error message.

func (*Logger) Errorf

func (l *Logger) Errorf(format string, v ...any)

Errorf logs an error message with format.

func (*Logger) Info

func (l *Logger) Info(v any)

Info logs a info message.

func (*Logger) Infof

func (l *Logger) Infof(format string, v ...any)

Infof logs a info message with format.

func (*Logger) SetPolicy

func (l *Logger) SetPolicy(p Policy)

SetPolicy replaces the Policy of the request or run this logger belongs to: a handler promotes or demotes its own request. The nearest declaration wins, so this call counts over the request logger's options and over any WithPolicy on the way down. Without a request logger behind the context it does nothing.

func (*Logger) TraceID

func (l *Logger) TraceID() string

TraceID returns the trace ID of the request logs

func (*Logger) Warn

func (l *Logger) Warn(v any)

Warn logs a warning message.

func (*Logger) Warnf

func (l *Logger) Warnf(format string, v ...any)

Warnf logs a warning message with format.

func (*Logger) WithAttributes

func (l *Logger) WithAttributes() *AttributerLogger

WithAttributes returns an AttributerLogger that can be used to add child (trace) log attributes

type Policy

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

Policy declares what a request, or a command-line run, writes to the log when it ends. It is declared with one of four words, each a constructor:

  • Always writes the parent entry for every request. It is today's behavior and the zero value.
  • OnEvent writes the parent entry when a line attached to the request or the request failed: it answered 400 or above, or the run returned an error.
  • Sampled writes as OnEvent does and, for the quiet requests, draws once per request at the given fraction.
  • Never writes nothing, whatever happened.

MinSeverity adds a floor: lines below it are dropped before they attach, so they neither count as an event nor appear as child entries. The nearest declaration wins: the request logger's options set the policy a request starts with, WithPolicy replaces it on the way down the handler chain, and a handler may replace it again for its own request through Logger.SetPolicy.

func Always

func Always() Policy

Always returns the policy that writes the parent entry for every request. It is today's behavior and the default of every exporter.

func Never

func Never() Policy

Never returns the policy that writes nothing, whatever happened. A health check wants this.

func OnEvent

func OnEvent() Policy

OnEvent returns the policy that writes the parent entry when a line attached to the request or the request failed: it answered 400 or above, or the run returned an error. It is what an exporter built with LogAll(false) or NewAWSExporter(false) defaults to.

func Sampled

func Sampled(fraction float64) Policy

Sampled returns the policy that writes the parent entry as OnEvent does and, for the quiet requests, draws once per request at the given fraction, so that share of them is written too. The fraction must be above 0 and at most 1; any other value is refused with a panic, because the policy is a declaration and a bad fraction is a mistake in the code that declares it.

func (Policy) MinSeverity

func (p Policy) MinSeverity(severity logging.Severity) Policy

MinSeverity returns a copy of the policy with the floor set: lines below the severity are dropped before they attach to the request, so they are neither counted as an event nor written as child entries. The receiver is unchanged.

func (Policy) String

func (p Policy) String() string

String names the policy the way a chain comment reads it: "always", "on event", "sampled at 0.1" or "never", followed by the floor when one is set, as in "on event, Warning and above".

type RequestLoggerOption

type RequestLoggerOption func(*requestLoggerOptions)

RequestLoggerOption configures NewRequestLogger and NewCliLogger.

func DefaultPolicy

func DefaultPolicy(p Policy) RequestLoggerOption

DefaultPolicy sets the policy every request or run starts with: the application default. It overrides the exporter's own default, which is Always unless the exporter was built with LogAll(false) or NewAWSExporter(false), where it is OnEvent.

func PolicyByPrefix

func PolicyByPrefix(prefixes map[string]Policy) RequestLoggerOption

PolicyByPrefix sets the policy a request starts with from its path: the longest prefix that matches wins, and its policy is used in place of the default. It is how routes an application mounts by hand get theirs. A run has no path, so NewCliLogger does not apply it.

type SwitchableExporter

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

SwitchableExporter is an Exporter whose destination can be replaced while the application runs: a device starts on the console, moves to the cloud once it can reach it, and comes back to the console when it loses that. Middleware, CliRunner and DaemonContext delegate to the exporter current when the request or run starts, and that request or run finishes on it even if a swap happens meanwhile. A zero SwitchableExporter serves the console exporter until the first Swap.

func NewSwitchableExporter

func NewSwitchableExporter(initial Exporter) *SwitchableExporter

NewSwitchableExporter returns a SwitchableExporter that starts on the initial exporter. A nil initial exporter means the console exporter.

func (*SwitchableExporter) CliRunner

func (s *SwitchableExporter) CliRunner() func(ctx context.Context, command string, f func(context.Context) error) error

CliRunner returns a function that runs the given function under the exporter current when the run starts.

func (*SwitchableExporter) DaemonContext

func (s *SwitchableExporter) DaemonContext(ctx context.Context) context.Context

DaemonContext returns a context with a logger from the exporter current at the call.

func (*SwitchableExporter) Middleware

func (s *SwitchableExporter) Middleware() func(http.Handler) http.Handler

Middleware returns a middleware that hands each request to the exporter current when the request starts.

func (*SwitchableExporter) Swap

func (s *SwitchableExporter) Swap(next Exporter) (previous Exporter)

Swap replaces the current exporter and returns the previous one, so the caller can flush or close whatever stands behind it; the Exporter interface has no Close, so that is done on the concrete type the caller built. A nil next exporter means the console exporter. Swap is safe for concurrent use, and a request or run that already started finishes on the exporter it started with.

Jump to

Keyboard shortcuts

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