log

package
v2.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 27, 2023 License: MIT Imports: 23 Imported by: 468

Documentation

Overview

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

Index

Constants

View Source
const (
	// SERVICE represents a service account type
	SERVICE identityType = "service"
	// USER represents a user account type
	USER identityType = "user"
)
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

View Source
var Namespace = path.Base(os.Args[0])

Namespace is the log namespace included with every log event.

It defaults to the application binary name, but this should normally be set to a more sensible name on application startup

Functions

func Auth

func Auth(identityType identityType, identity string) option

Auth returns an option you can pass to Event to include identity information, for example the identity type and user/service ID from an inbound HTTP request

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.

When running tests, Event will panic if the same option is passed in multiple times, for example:

log.Event(nil, "event", log.Data{}, log.Data{})

It doesn't panic in normal usage because checking for duplicate entries is expensive. Where this happens, options to the right take precedence, for example:

log.Event(nil, "event", log.Data{"a": 1}, log.Data{"a": 2})
// data.a = 2

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 FormatErrors added in v2.0.1

func FormatErrors(errs []error) option

FormatErrors returns an option you can pass to Event to attach error information to a log event

It uses error.Error() to stringify the error value

It also includes the error type itself as unstructured log data. For a struct{} type, it is included directly. For all other types, it is wrapped in a Data{} struct

It also includes a full stack trace to where FormatErrors() is called, so you shouldn't normally store a log.Error for reuse (e.g. as a package level variable)

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 Info

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

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

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 SetDestination added in v2.0.7

func SetDestination(dest, fbDest io.Writer)

SetDestination allows you to set the destination and fallback destination for log output. Pass nil to either value to skip changing it.

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 CustomError added in v2.0.5

type CustomError struct {
	Message string                 `json:"message"`
	Data    map[string]interface{} `json:"data"`
}

CustomError defines an error object that abides to the error type with the extension of including data field

func (*CustomError) Error added in v2.0.5

func (c *CustomError) Error() string

Error returns the custom error message embedded in CustomError

func (CustomError) ErrorData added in v2.0.5

func (c CustomError) ErrorData() map[string]interface{}

ErrorData returns the custom error data embedded in CustomError

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 {
	// Required fields
	CreatedAt time.Time `json:"created_at"`
	Namespace string    `json:"namespace"`
	Event     string    `json:"event"`

	// 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"`
	Auth *eventAuth `json:"auth,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.

type EventErrors added in v2.0.1

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.

Jump to

Keyboard shortcuts

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