Documentation ¶
Overview ¶
Package log is a log library which implements the Digital Publishing logging standards
Index ¶
- Constants
- func Default() *slog.Logger
- func Error(ctx context.Context, event string, err error, opts ...option)
- func Event(ctx context.Context, event string, severity severity, opts ...option)
- func Fatal(ctx context.Context, event string, err error, opts ...option)
- func HTTP(req *http.Request, statusCode int, responseContentLength int64, ...) option
- func Handler(opts ...config.Option) slog.Handler
- func Info(ctx context.Context, event string, opts ...option)
- func Initialise(ns string, opts ...config.Option)
- func LevelToSeverity(level slog.Level) severity
- func Middleware(f http.Handler) http.Handler
- func SetDefault(l *slog.Logger)
- func SeverityToLevel(severity severity) slog.Level
- func Warn(ctx context.Context, event string, opts ...option)
- type Data
- type EventData
- type EventError
- type EventErrors
- type EventHTTP
- type EventStackTrace
- type ModifyingHandler
Constants ¶
const ( LevelDebug = slog.LevelDebug LevelInfo = slog.LevelInfo LevelWarn = slog.LevelWarn LevelError = slog.LevelError LevelFatal = slog.Level(12) )
const ( // FATAL is an option you can pass to Event to specify a severity of FATAL/0 FATAL severity = 0 // ERROR is an option you can pass to Event to specify a severity of ERROR/1 ERROR severity = 1 // WARN is an option you can pass to Event to specify a severity of WARN/2 WARN severity = 2 // INFO is an option you can pass to Event to specify a severity of INFO/3 INFO severity = 3 )
Variables ¶
This section is empty.
Functions ¶
func Event ¶
Event logs an event, to STDOUT if possible, or STDERR if not.
Context can be nil.
An event string should be static strings which do not use concatenation or Sprintf, e.g.
"connecting to database"
rather than
"connecting to database: " + databaseURL
Additional data should be stored using Data{}
You can also pass in additional options which log extra event data, for example using the HTTP, Auth, Severity, Data and Error functions.
log.Event(nil, "connecting to database", log.Data{"url": databaseURL})
If HUMAN_LOG environment variable is set to a true value (true, TRUE, 1) the log output will be syntax highlighted pretty printed JSON. Otherwise, the output is JSONLines format, with one JSON object per line.
func HTTP ¶
func HTTP(req *http.Request, statusCode int, responseContentLength int64, startedAt, endedAt *time.Time) option
HTTP returns an option you can pass to Event to log HTTP request data with a log event.
It converts the port number to a integer if possible, otherwise the port number is 0.
It splits the URL into its component parts, and stores the scheme, host, port, path and query string individually.
It also calculates the duration if both startedAt and endedAt are passed in, for example when wrapping a http.Handler.
func Handler ¶
Handler is a function that returns a slog.Logger based on the supplied config.Option vararg.
func Initialise ¶
Initialise is a helper function that creates a new slog.Logger with common options and sets it as the default logger for the app. Specifically it adds a namespace attribute to all logs, gets other config from environment variables. It can be configured with extra options passed in as arguments
func LevelToSeverity ¶
LevelToSeverity translates a slog.Level into a log.go severity
func Middleware ¶
Middleware implements the logger middleware and captures HTTP request data
It implements http.Handler, and wraps an inbound HTTP request to log useful information including the URL, request start/complete times and duration, status codes, and number of bytes written.
If the request context includes a trace ID, this will be included in the event data automatically.
Each request will produce two log entries - one when the request is received, and another when the response has completed.
See the Event and HTTP functions for additional information.
func SetDefault ¶
SetDefault makes l the default slog.Logger used by log.go, which is used by the top-level functions Info, [Debug] and so on.
func SeverityToLevel ¶
SeverityToLevel translates a log.go severity into a slog.Level
Types ¶
type Data ¶
type Data map[string]interface{}
Data can be used to include arbitrary key/value pairs in the structured log output.
This should only be used where a predefined field isn't already available, since data included in a Data{} value isn't easily indexable.
You can also create nested log data, for example:
Data { "key": Data{}, }
type EventData ¶
type EventData struct { // Optional fields TraceID string `json:"trace_id,omitempty"` SpanID string `json:"span_id,omitempty"` Severity *severity `json:"severity,omitempty"` // Optional nested data HTTP *EventHTTP `json:"http,omitempty"` Data *Data `json:"data,omitempty"` // Error data Errors *EventErrors `json:"errors,omitempty"` }
EventData is the data structure used for logging an event
It is the top level structure which contains all other log event data.
It isn't very useful to export, other than for documenting the data structure it outputs.
type EventError ¶
type EventError struct { Message string `json:"message,omitempty"` StackTrace []EventStackTrace `json:"stack_trace,omitempty"` // This uses interface{} type, but should always be a type of kind struct // (which serialises to map[string]interface{}) // See `func FormatErrors` switch block for more info Data interface{} `json:"data,omitempty"` }
EventError is the data structure used for logging a error event.
It isn't very useful to export, other than for documenting the data structure it outputs.
func FormatAsErrors ¶
func FormatAsErrors(err error) []EventError
FormatAsErrors takes an error and unwraps and wrapped errors and returns this as a slice. If any of the wrapped errors also contain a stack trace, this will also be extracted. Currently, stack traces provided by the following errors packages are supported... - golang.org/x/xerrors - github.com/pkg/errors
type EventHTTP ¶
type EventHTTP struct { StatusCode *int `json:"status_code,omitempty"` Method string `json:"method,omitempty"` // URL data Scheme string `json:"scheme,omitempty"` Host string `json:"host,omitempty"` Port int `json:"port,omitempty"` Path string `json:"path,omitempty"` Query string `json:"query,omitempty"` // Timing data StartedAt *time.Time `json:"started_at,omitempty"` EndedAt *time.Time `json:"ended_at,omitempty"` Duration *time.Duration `json:"duration,omitempty"` ResponseContentLength int64 `json:"response_content_length,omitempty"` }
EventHTTP is the data structure used for logging a HTTP event.
It isn't very useful to export, other than for documenting the data structure it outputs.
type EventStackTrace ¶
type EventStackTrace struct { File string `json:"file,omitempty"` Line int `json:"line,omitempty"` Function string `json:"function,omitempty"` }
EventStackTrace is the data structure used for logging a stack trace.
It isn't very useful to export, other than for documenting the data structure it outputs.
type ModifyingHandler ¶
type ModifyingHandler struct {
// contains filtered or unexported fields
}
ModifyingHandler implements a slog.Handler that wraps attrs in a 'data' group and adds a severity attribute translated from the log level of the record.
This can be used with a default logger so that logging from third party libraries is translated into a format that matches the dp standard logging structure.
func (ModifyingHandler) Handle ¶
Handle adds a severity slog.Attr to the record translated from the log level and then loops over the record's attrs, wrapping them within a `data` group. It then calls the underlying Handle method on the base handler
func (ModifyingHandler) WithAttrs ¶
func (mh ModifyingHandler) WithAttrs(attrs []slog.Attr) slog.Handler
WithAttrs returns a new ModifyingHandler using the underlying base handler's WithAttrs method
func (ModifyingHandler) WithGroup ¶
func (mh ModifyingHandler) WithGroup(name string) slog.Handler
WithGroup returns a new ModifyingHandler using the underlying base handler's WithGroup method