log

package
v3.0.0-...-53ae084 Latest Latest
Warning

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

Go to latest
Published: Jul 30, 2024 License: MIT Imports: 19 Imported by: 0

Documentation

Overview

Package log is a log library which implements the Digital Publishing logging standards

Index

Constants

View Source
const (
	LevelDebug = slog.LevelDebug
	LevelInfo  = slog.LevelInfo
	LevelWarn  = slog.LevelWarn
	LevelError = slog.LevelError
	LevelFatal = slog.Level(12)
)
View Source
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 Default

func Default() *slog.Logger

Default returns the default slog.Logger used by log.go.

func Error

func Error(ctx context.Context, event string, err error, opts ...option)

Error wraps the Event function with the severity level set to ERROR

func Event

func Event(ctx context.Context, event string, severity severity, opts ...option)

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 Fatal

func Fatal(ctx context.Context, event string, err error, opts ...option)

Fatal wraps the Event function with the severity level set to FATAL

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

func Handler(opts ...config.Option) slog.Handler

Handler is a function that returns a slog.Logger based on the supplied config.Option vararg.

func Info

func Info(ctx context.Context, event string, opts ...option)

Info wraps the Event function with the severity level set to INFO

func Initialise

func Initialise(ns string, opts ...config.Option)

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

func LevelToSeverity(level slog.Level) severity

LevelToSeverity translates a slog.Level into a log.go severity

func Middleware

func Middleware(f http.Handler) http.Handler

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

func SetDefault(l *slog.Logger)

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

func SeverityToLevel(severity severity) slog.Level

SeverityToLevel translates a log.go severity into a slog.Level

func Warn

func Warn(ctx context.Context, event string, opts ...option)

Warn wraps the Event function with the severity level set to WARN

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.

func (*EventData) ToAttrs

func (ed *EventData) ToAttrs() []slog.Attr

ToAttrs creates a slice of slog.ToAttrs from the existing EventData

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 EventErrors

type EventErrors []EventError

EventErrors is an array of error events

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) Enabled

func (mh ModifyingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled calls the underlying base handler's Enabled method

func (ModifyingHandler) Handle

func (mh ModifyingHandler) Handle(ctx context.Context, record slog.Record) error

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

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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