logging

package
v2.2.2 Latest Latest
Warning

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

Go to latest
Published: Sep 11, 2020 License: Apache-2.0 Imports: 15 Imported by: 3

Documentation

Overview

Package logging provides a component-based logging framework for user and built-in Granitic components.

Logging in Granitic is covered in detail at https://granitic.io/ref/logging a brief description of the key concepts and types follows.

Component logging

Every struct that is registered as a component in Granitic's IoC container has the option of having a Logger injected into it. Components are classified as framework components (built-in components that are created when you enable a facility in your application) and application components - named components defined in your application's component definition files.

Obtaining a Logger

Any component in your application will have a Logger injected into it if the underlying struct for that component declares a field:

Log logging.Logger

The Logger is injected during the 'decoration' phase of container startup ( implements package documentation for the ioc package). This means the Logger is safe to use in any method in your component.

Log levels

A log level is a label indicating the relative significance of a message to be logged. In order of significance they are:

TRACE, DEBUG, INFO, WARN, ERROR, FATAL

These levels have no set meanings, but a rough set of meanings follows:

TRACE

Very detailed low level messages showing almost line-by-line commentary of a procedure.

DEBUG

Information that might be significant when trying to diagnose a fault (connection URLs, resource utilisation etc).

INFO

Status information that might be of interest to outside observers of an application (ready messages, declaring which ports HTTP servers are listening to, shutdown notifications).

WARN

An undesirable but managed situation where application or request integrity has not suffered (approaching a resource limit, having to retry a connection to an external system).

ERROR

A problem that has not affected application integrity, but has caused a user request to terminate abnormally (problem inserting into a database, downstream system unavailable after retries).

FATAL

A serious problem that has affected the integrity of the application such that it should be restarted or has crashed.

Log methods

The Logger interface ( implements below) provides methods to log a message at a particular level. E.g.

Log.LogDebugf("A %s message", "DEBUG")

Global and component thresholds

A log level threshold is the minimum significance of a message that will be actually written to a log file or console. Granitic maintains a separate global log level for application components and framework components. This separation means that you could, for example, set your application's global log level to DEBUG without having's Granitic's built-in components filling your log files with clutter.

The log levels can be adjusted in the configuration of your application by setting the following configuration in your application's configuration file:

{
  "FrameworkLogger":{
	"GlobalLogLevel": "INFO"
  },
  "ApplicationLogger":{
	"GlobalLogLevel": "INFO"
  }
}

The above example is the default setting for Granitic applications, meaning that only messages with a log level of INFO or higher will actually be written to the console and/or log file.

The global log level can be overridden for individual components by setting configuration similar to:

{
  "FrameworkLogger":{
	"GlobalLogLevel": "FATAL",
	"ComponentLogLevels": {
	  "grncHTTPServer": "TRACE"
	}
  },
  "ApplicationLogger":{
	"GlobalLogLevel": "INFO",
	"ComponentLogLevels": {
	  "noisyComponent": "ERROR"
	}
  }
}

In this example, all framework components are effectively silenced (apart from fatal errors), but the HTTP server is allowed to output TRACE messages. Application components are allowed to log at INFO and above, but one component is too chatty so is only allowed to log at ERROR or above.

Log output

Output of log messages to file and console is controlled by the LogWriting configuration element. The default settings look something like:

{
  "LogWriting": {
	"EnableConsoleLogging": true,
	"EnableFileLogging": false,
	"File": {
	  "LogPath": "./granitic.log",
	  "BufferSize": 50
	},
	"Format": {
	  "UtcTimes":     true,
	  "Unset": "-"
	}
  }
}

For more information on these settings, refer to https://granitic.io/ref/logging-format-output

Runtime control

Global log levels and component log levels can be changed at runtime, if your application has the RuntimeCtl facility enabled. implements https://granitic.io/ref/runtime-control for more information

Log message prefixes

Every message written to a log file or console can be given a customisable prefix containing meta-data like time of logging or information from a Context. implements https://granitic.io/ref/logging-format-output

Index

Constants

View Source
const (
	// All allows all messages to be logged
	All = 0
	// Trace allows messages with a significance of Trace or higher to be logged
	Trace = 10
	// Debug allows messages with a significance of Debug or higher to be logged
	Debug = 20
	// Info allows messages with a significance of Info or higher to be logged
	Info = 40
	// Warn allows messages with a significance of Warn or higher to be logged
	Warn = 50
	// Error allows messages with a significance of Error or higher to be logged
	Error = 60
	// Fatal allows messages with a significance of Fatal or higher to be logged
	Fatal = 70
)
View Source
const (
	//AllLabel maps the string ALL to the numeric log level All
	AllLabel = "ALL"
	//TraceLabel maps the string TRACE to the numeric log level Trace
	TraceLabel = "TRACE"
	//DebugLabel maps the string DEBUG to the numeric log level Debug
	DebugLabel = "DEBUG"
	//InfoLabel maps the string INFO to the numeric log level Debug
	InfoLabel = "INFO"
	//WarnLabel maps the string WARN to the numeric log level Warn
	WarnLabel = "WARN"
	//ErrorLabel maps the string ERROR to the numeric log level Error
	ErrorLabel = "ERROR"
	//FatalLabel maps the string FATAL to the numeric log level Fatal
	FatalLabel = "FATAL"
)
View Source
const FrameworkPresetPrefix = "framework"

FrameworkPresetPrefix is the flag used in configuration to indicate your app wants to use the default format for log lines

View Source
const PresetFormatFramework = "%{02/Jan/2006:15:04:05 Z0700}t %P [%c] "

PresetFormatFramework is the default prefix format for log lines

Variables

This section is empty.

Functions

func LabelFromLevel

func LabelFromLevel(ll LogLevel) string

LabelFromLevel takes a member of the LogLevel enumeration (All, Fatal) and converts it to a string code ('ALL', 'FATAL'). If the supplied LogLevel cannot be mapped to a defined level, the word 'CUSTOM' is returned.

func ValidateJSONFields added in v2.2.0

func ValidateJSONFields(fields []*JSONField) error

ValidateJSONFields checks that the configuration of a JSON application log entry is correct

Types

type AsynchFileWriter

type AsynchFileWriter struct {

	//The number of messages that can be queued for writing before calls to WriteMessage block.
	BufferSize int

	//The file (absolute path or relative to application's working directory) that log messages should be appended to.
	LogPath string
	// contains filtered or unexported fields
}

AsynchFileWriter is an implementation of LogWriter that appends a message to a file. Messages will be written asynchronously as long as the number of messages queued for writing does not exceed the value of BufferSize

func (*AsynchFileWriter) Busy

func (afw *AsynchFileWriter) Busy() bool

Busy returns true if one or more messages are queued for writing.

func (*AsynchFileWriter) Close

func (afw *AsynchFileWriter) Close()

Close closes the log file

func (*AsynchFileWriter) Init

func (afw *AsynchFileWriter) Init() error

Init creates a channel to act as a buffer for queued messages

func (*AsynchFileWriter) WriteMessage

func (afw *AsynchFileWriter) WriteMessage(m string)

WriteMessage queues a message for writing and returns immediately, as long as the number of queued messages does not exceed BufferSize.

type ByName

type ByName struct{ ComponentLevels }

ByName allows ComponentLevels to be sorted by name

func (ByName) Less

func (s ByName) Less(i, j int) bool

Less supports sorting by name

type ComponentLevel

type ComponentLevel struct {
	Name  string
	Level LogLevel
}

ComponentLevel pairs a component name and its loglevel for sorting and presentation through RuntimeCtl

type ComponentLevels

type ComponentLevels []*ComponentLevel

ComponentLevels allows a slice of ComponentLevel structs to be sorted

func (ComponentLevels) Len

func (s ComponentLevels) Len() int

Len supports sorting

func (ComponentLevels) Swap

func (s ComponentLevels) Swap(i, j int)

Swap supports sorting

type ComponentLoggerManager

type ComponentLoggerManager struct {
	ContextFilter ContextFilter
	// contains filtered or unexported fields
}

ComponentLoggerManager creates new Logger instances for a particular scope (e.g. framework or application).

func CreateComponentLoggerManager

func CreateComponentLoggerManager(globalThreshold LogLevel, initalComponentLogLevels map[string]interface{},
	writers []LogWriter, formatter StringFormatter, buffer bool) *ComponentLoggerManager

CreateComponentLoggerManager creates a new ComponentLoggerManager with a global level and default values for named components.

func (*ComponentLoggerManager) CreateLogger

func (clm *ComponentLoggerManager) CreateLogger(componentID string) Logger

CreateLogger creates a new Logger for the supplied component name

func (*ComponentLoggerManager) CreateLoggerAtLevel

func (clm *ComponentLoggerManager) CreateLoggerAtLevel(componentID string, threshold LogLevel) Logger

CreateLoggerAtLevel creates a new Logger for the supplied component name with the local log threshold set to the supplied level.

func (*ComponentLoggerManager) CurrentLevels

func (clm *ComponentLoggerManager) CurrentLevels() []*ComponentLevel

CurrentLevels returns the current local log level for all Loggers managed by this component.

func (*ComponentLoggerManager) DeferLog added in v2.2.0

func (clm *ComponentLoggerManager) DeferLog(levelLabel string, level LogLevel, message string, when time.Time, logger *GraniticLogger)

DeferLog buffers a log message until the log formatters and writers are finalised

func (*ComponentLoggerManager) Disable added in v2.1.0

func (clm *ComponentLoggerManager) Disable()

Disable prevents this manager from creating new loggers - a NullLogger will be returned instead

func (*ComponentLoggerManager) ForceFlush added in v2.2.0

func (clm *ComponentLoggerManager) ForceFlush()

ForceFlush writes any buffered log entries with whatever writers and formatters are currently configured

func (*ComponentLoggerManager) GlobalLevel

func (clm *ComponentLoggerManager) GlobalLevel() LogLevel

GlobalLevel returns the global log level for the scope (application, framework) that this ComponentLoggerManager is responsible for.

func (*ComponentLoggerManager) IsDisabled added in v2.1.0

func (clm *ComponentLoggerManager) IsDisabled() bool

IsDisabled checks to see if this manager has been disabled

func (*ComponentLoggerManager) LoggerByName

func (clm *ComponentLoggerManager) LoggerByName(name string) *GraniticLogger

LoggerByName finds a previously created Logger by the name it was given when it was created. Returns nil if no Logger by that name exists.

func (*ComponentLoggerManager) PrepareToStop

func (clm *ComponentLoggerManager) PrepareToStop()

PrepareToStop does nothing

func (*ComponentLoggerManager) ReadyToStop

func (clm *ComponentLoggerManager) ReadyToStop() (bool, error)

ReadyToStop returns false if any of the LogWriters attached to this component are actively writing.

func (*ComponentLoggerManager) RegisterInstanceID added in v2.2.0

func (clm *ComponentLoggerManager) RegisterInstanceID(i *instance.Identifier)

RegisterInstanceID receives the unique iD of the current instance of the application

func (*ComponentLoggerManager) SetGlobalThreshold

func (clm *ComponentLoggerManager) SetGlobalThreshold(globalThreshold LogLevel)

SetGlobalThreshold sets the global log level for the scope (application, framework) that this ComponentLoggerManager is responsible for.

func (*ComponentLoggerManager) SetInitialLogLevels

func (clm *ComponentLoggerManager) SetInitialLogLevels(ll map[string]interface{})

SetInitialLogLevels provide a map of component names to log levels. If a Logger is subsequently created for a component named in the map, the log level in the map will be used to set its local log threshold. Previously created loggers will be updated

func (*ComponentLoggerManager) StartComponent added in v2.1.0

func (clm *ComponentLoggerManager) StartComponent() error

StartComponent makes an injected ContextFilter and or InstanceID available to the formatters attached to this manager

func (*ComponentLoggerManager) Stop

func (clm *ComponentLoggerManager) Stop() error

Stop closes all LogWriters attached to this component.

func (*ComponentLoggerManager) UpdateWritersAndFormatter

func (clm *ComponentLoggerManager) UpdateWritersAndFormatter(writers []LogWriter, formatter StringFormatter)

UpdateWritersAndFormatter updates the writers and formatters of all Loggers managed by this ComponentLoggerManager.

type ConsoleErrorLogger

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

ConsoleErrorLogger is an implementation of logging.Logger that writes errors and fatal messages to the console/command line using Go's fmt.Printf function. Messages at all other levels are ignored. This implementation is used by Granitic's command line tools and is not recommended for use in user applications but can by useful for unit tests.

func (*ConsoleErrorLogger) IsLevelEnabled

func (l *ConsoleErrorLogger) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled returns true if the supplied level is >= Error

func (*ConsoleErrorLogger) LogAtLevelf

func (l *ConsoleErrorLogger) LogAtLevelf(level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelf uses fmt.printf to write the supplied message to the console.

func (*ConsoleErrorLogger) LogAtLevelfCtx

func (l *ConsoleErrorLogger) LogAtLevelfCtx(ctx context.Context, level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelfCtx uses fmt.printf to write the supplied message to the console.

func (*ConsoleErrorLogger) LogDebugf

func (l *ConsoleErrorLogger) LogDebugf(format string, a ...interface{})

LogDebugf is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogDebugfCtx

func (l *ConsoleErrorLogger) LogDebugfCtx(ctx context.Context, s string, a ...interface{})

LogDebugfCtx is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogErrorf

func (l *ConsoleErrorLogger) LogErrorf(format string, a ...interface{})

LogErrorf uses fmt.Fprintf to write the supplied message to the console (or other writer)

func (*ConsoleErrorLogger) LogErrorfCtx

func (l *ConsoleErrorLogger) LogErrorfCtx(ctx context.Context, format string, a ...interface{})

LogErrorfCtx uses fmt.printf to write the supplied message to the console.

func (*ConsoleErrorLogger) LogErrorfCtxWithTrace

func (l *ConsoleErrorLogger) LogErrorfCtxWithTrace(ctx context.Context, format string, a ...interface{})

LogErrorfCtxWithTrace uses fmt.printf to write the supplied message to the console and appends a stack trace.

func (*ConsoleErrorLogger) LogErrorfWithTrace

func (l *ConsoleErrorLogger) LogErrorfWithTrace(format string, a ...interface{})

LogErrorfWithTrace uses fmt.printf to write the supplied message to the console and appends a stack trace.

func (*ConsoleErrorLogger) LogFatalf

func (l *ConsoleErrorLogger) LogFatalf(format string, a ...interface{})

LogFatalf uses fmt.printf to write the supplied message to the console.

func (*ConsoleErrorLogger) LogFatalfCtx

func (l *ConsoleErrorLogger) LogFatalfCtx(ctx context.Context, format string, a ...interface{})

LogFatalfCtx uses fmt.printf to write the supplied message to the console.

func (*ConsoleErrorLogger) LogInfof

func (l *ConsoleErrorLogger) LogInfof(format string, a ...interface{})

LogInfof is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogInfofCtx

func (l *ConsoleErrorLogger) LogInfofCtx(ctx context.Context, s string, a ...interface{})

LogInfofCtx is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogTracef

func (l *ConsoleErrorLogger) LogTracef(format string, a ...interface{})

LogTracef is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogTracefCtx

func (l *ConsoleErrorLogger) LogTracefCtx(ctx context.Context, s string, a ...interface{})

LogTracefCtx is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogWarnf

func (l *ConsoleErrorLogger) LogWarnf(format string, a ...interface{})

LogWarnf is ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogWarnfCtx

func (l *ConsoleErrorLogger) LogWarnfCtx(ctx context.Context, s string, a ...interface{})

LogWarnfCtx is ignored - messages sent to this method are discarded.

type ConsoleWriter

type ConsoleWriter struct {
}

ConsoleWriter is an implementation of LogWriter that sends messages to the console/stdout using the fmt.Print method

func (*ConsoleWriter) Busy

func (cw *ConsoleWriter) Busy() bool

Busy always returns false

func (*ConsoleWriter) Close

func (cw *ConsoleWriter) Close()

Close does nothing

func (*ConsoleWriter) WriteMessage

func (cw *ConsoleWriter) WriteMessage(m string)

WriteMessage passes message to fmt.Print

type ContextFilter added in v2.1.0

type ContextFilter interface {
	Extract(ctx context.Context) FilteredContextData
}

ContextFilter takes a context and extracts some or all of the data in it a returns in a form suitable for inclusion in application and access logs.

type FilterPriority added in v2.2.0

type FilterPriority interface {
	Priority() int64
}

FilterPriority is implemented by ContextFilters that need to make sure their view of FilteredContextData is prioritised over those in another ContextFilter. Higher values are considered to be higher priority and negative values are allowed.

type FilteredContextData added in v2.1.0

type FilteredContextData map[string]string

FilteredContextData holds information that has been extracted from a context.Context in a format suitable for logging

type FixedPrefixConsoleWriter

type FixedPrefixConsoleWriter struct {
	Prefix string
}

FixedPrefixConsoleWriter is an implementation of LogWriter that sends messages to the console/stdout with a static prefix in front of every line

func (*FixedPrefixConsoleWriter) Busy

func (cw *FixedPrefixConsoleWriter) Busy() bool

Busy always returns false

func (*FixedPrefixConsoleWriter) Close

func (cw *FixedPrefixConsoleWriter) Close()

Close does nothing

func (*FixedPrefixConsoleWriter) WriteMessage

func (cw *FixedPrefixConsoleWriter) WriteMessage(m string)

WriteMessage passes message to fmt.Print

type GlobalLevel

type GlobalLevel interface {
	//GlobalLevel returns this component's current global log level
	GlobalLevel() LogLevel
}

GlobalLevel is implemented by Loggers able to state what the current global log level is

type GraniticLogger

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

GraniticLogger is the standard implementation of Logger which respects both a global log level and a specific level for this Logger.

func (*GraniticLogger) IsLevelEnabled

func (grl *GraniticLogger) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled implements Logger.IsLevelEnabled

func (*GraniticLogger) LogAtLevelf

func (grl *GraniticLogger) LogAtLevelf(level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelf implements Logger.LogAtLevelf

func (*GraniticLogger) LogAtLevelfCtx

func (grl *GraniticLogger) LogAtLevelfCtx(ctx context.Context, level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelfCtx implements Logger.LogAtLevelfCtx

func (*GraniticLogger) LogDebugf

func (grl *GraniticLogger) LogDebugf(format string, a ...interface{})

LogDebugf implements Logger.LogDebugf

func (*GraniticLogger) LogDebugfCtx

func (grl *GraniticLogger) LogDebugfCtx(ctx context.Context, format string, a ...interface{})

LogDebugfCtx implements Logger.LogDebugfCtx

func (*GraniticLogger) LogErrorf

func (grl *GraniticLogger) LogErrorf(format string, a ...interface{})

LogErrorf implements Logger.LogErrorf

func (*GraniticLogger) LogErrorfCtx

func (grl *GraniticLogger) LogErrorfCtx(ctx context.Context, format string, a ...interface{})

LogErrorfCtx implements Logger.LogErrorfCtx

func (*GraniticLogger) LogErrorfCtxWithTrace

func (grl *GraniticLogger) LogErrorfCtxWithTrace(ctx context.Context, format string, a ...interface{})

LogErrorfCtxWithTrace implements Logger.LogErrorfCtxWithTrace

func (*GraniticLogger) LogErrorfWithTrace

func (grl *GraniticLogger) LogErrorfWithTrace(format string, a ...interface{})

LogErrorfWithTrace implements Logger.LogErrorfWithTrace

func (*GraniticLogger) LogFatalf

func (grl *GraniticLogger) LogFatalf(format string, a ...interface{})

LogFatalf implements Logger.LogFatalf

func (*GraniticLogger) LogFatalfCtx

func (grl *GraniticLogger) LogFatalfCtx(ctx context.Context, format string, a ...interface{})

LogFatalfCtx implements Logger.LogFatalfCtx

func (*GraniticLogger) LogInfof

func (grl *GraniticLogger) LogInfof(format string, a ...interface{})

LogInfof implements Logger.LogInfof

func (*GraniticLogger) LogInfofCtx

func (grl *GraniticLogger) LogInfofCtx(ctx context.Context, format string, a ...interface{})

LogInfofCtx implements Logger.LogInfofCtx

func (*GraniticLogger) LogTracef

func (grl *GraniticLogger) LogTracef(format string, a ...interface{})

LogTracef implements Logger.LogTracef

func (*GraniticLogger) LogTracefCtx

func (grl *GraniticLogger) LogTracefCtx(ctx context.Context, format string, a ...interface{})

LogTracefCtx implements Logger.LogTracefCtx

func (*GraniticLogger) LogWarnf

func (grl *GraniticLogger) LogWarnf(format string, a ...interface{})

LogWarnf implements Logger.LogWarnf

func (*GraniticLogger) LogWarnfCtx

func (grl *GraniticLogger) LogWarnfCtx(ctx context.Context, format string, a ...interface{})

LogWarnfCtx implements Logger.LogWarnfCtx

func (*GraniticLogger) SetLocalThreshold

func (grl *GraniticLogger) SetLocalThreshold(threshold LogLevel)

SetLocalThreshold sets the log threshold for this Logger

func (*GraniticLogger) UpdateWritersAndFormatter

func (grl *GraniticLogger) UpdateWritersAndFormatter(w []LogWriter, f StringFormatter)

UpdateWritersAndFormatter implements RuntimeControllableLog.UpdateWritersAndFormatter

type JSONConfig added in v2.2.0

type JSONConfig struct {
	Prefix       string
	Fields       [][]string
	ParsedFields []*JSONField
	Suffix       string
	UTC          bool
}

JSONConfig defines the fields to be included in a JSON-formatted application log entry

type JSONField added in v2.2.0

type JSONField struct {
	Name    string
	Content string
	Arg     string
	// contains filtered or unexported fields
}

A JSONField defines the rules for outputting a single field in a JSON-formatted application log entry

func ConvertFields added in v2.2.0

func ConvertFields(unparsed [][]string) []*JSONField

ConvertFields converts from the config representation of a field list to the internal version

type JSONLogFormatter added in v2.2.0

type JSONLogFormatter struct {
	Config     *JSONConfig
	MapBuilder *MapBuilder
}

A JSONLogFormatter is a component able to take a message to be written to a log file and format it as JSON document

func (*JSONLogFormatter) AllowAccess added in v2.2.2

func (jlf *JSONLogFormatter) AllowAccess() error

AllowAccess checks that a context filter has been injected (if the field configuration needs on)

func (*JSONLogFormatter) Format added in v2.2.0

func (jlf *JSONLogFormatter) Format(ctx context.Context, levelLabel, loggerName, message string) string

Format takes the message and prefixes it according the the rule specified in PrefixFormat or PrefixPreset

func (*JSONLogFormatter) SetContextFilter added in v2.2.0

func (jlf *JSONLogFormatter) SetContextFilter(cf ContextFilter)

SetContextFilter provides the formatter with access selected data from a context

func (*JSONLogFormatter) SetInstanceID added in v2.2.0

func (jlf *JSONLogFormatter) SetInstanceID(i *instance.Identifier)

SetInstanceID accepts the current instance ID

type LogLevel

type LogLevel uint

LogLevel is the numeric score of the significance of a message, where zero is non-significant and higher values are more significant.

func LogLevelFromLabel

func LogLevelFromLabel(label string) (LogLevel, error)

LogLevelFromLabel takes a string name for a log level (TRACE, DEBUG etc) and finds a numeric threshold associated with that type of message.

type LogMessageFormatter

type LogMessageFormatter struct {

	// The pattern to be used as a template when generating prefixes. Mutally exclusive with PrefixPreset
	PrefixFormat string

	// The name of a pre-defined prefix template (e.g. 'framework'). Mutally exclusive with PrefixFormat
	PrefixPreset string

	// Convert timestamps in prefixes to UTC
	UtcTimes bool

	// The symbol to use in place of an unset variable in a log line prefix.
	Unset string

	// A component able to extract information from a context.Context into a loggable format
	ContextFilter ContextFilter
	// contains filtered or unexported fields
}

A LogMessageFormatter is a component able to take a message to be written to a log file and prefix it with a formatted template which can include log times, data from a Context etc.

func NewFrameworkLogMessageFormatter

func NewFrameworkLogMessageFormatter() *LogMessageFormatter

NewFrameworkLogMessageFormatter creates a new LogMessageFormatter using the default 'framework' pattern for log line prefixes and UTC timestamps.

func NewNoPrefixFormatter

func NewNoPrefixFormatter() *LogMessageFormatter

NewNoPrefixFormatter creates a LogMessageFormatter that doesn't apply a prefix

func (*LogMessageFormatter) Format

func (lmf *LogMessageFormatter) Format(ctx context.Context, levelLabel, loggerName, message string) string

Format takes the message and prefixes it according the the rule specified in PrefixFormat or PrefixPreset

func (*LogMessageFormatter) Init

func (lmf *LogMessageFormatter) Init() error

Init checks that a valid format has been provided for the log message prefixes.

func (*LogMessageFormatter) SetContextFilter added in v2.2.0

func (lmf *LogMessageFormatter) SetContextFilter(cf ContextFilter)

SetContextFilter provides the formatter with access selected data from a context

func (*LogMessageFormatter) SetInstanceID added in v2.2.0

func (lmf *LogMessageFormatter) SetInstanceID(i *instance.Identifier)

SetInstanceID accepts the current instance ID

type LogWriter

type LogWriter interface {
	// WriteMessage request that the supplied message be written. Depending on implementation, may be asynchronous.
	WriteMessage(string)

	// Close any resources (file handles etc) that this LogWriter might be holding.
	Close()

	// Returns true if the LogWriter is currently in the process of writing a log line.
	Busy() bool
}

LogWriter is implemented by components able to write a log message (to a file, console etc)

type Logger

type Logger interface {
	//LogTracefCtx log a message at TRACE level with a Context
	LogTracefCtx(ctx context.Context, format string, a ...interface{})

	//LogDebugfCtx log a message at DEBUG level with a Context
	LogDebugfCtx(ctx context.Context, format string, a ...interface{})

	//LogInfofCtx log a message at INFO level with a Context
	LogInfofCtx(ctx context.Context, format string, a ...interface{})

	//LogWarnfCtx log a message at WARN level with a Context
	LogWarnfCtx(ctx context.Context, format string, a ...interface{})

	//LogErrorfCtx log a message at ERROR level with a Context
	LogErrorfCtx(ctx context.Context, format string, a ...interface{})

	//LogErrorfCtxWithTrace log a message at ERROR level with a Context. Message output will be followed by a partial stack trace.
	LogErrorfCtxWithTrace(ctx context.Context, format string, a ...interface{})

	//LogFatalfCtx log a message at FATAL level with a Context
	LogFatalfCtx(ctx context.Context, format string, a ...interface{})

	//LogAtLevelfCtx log at the specified level with a Context
	LogAtLevelfCtx(ctx context.Context, level LogLevel, levelLabel string, format string, a ...interface{})

	//LogTracef log a message at TRACE level
	LogTracef(format string, a ...interface{})

	//LogDebugf log a message at DEBUG level
	LogDebugf(format string, a ...interface{})

	//LogInfof log a message at INFO level
	LogInfof(format string, a ...interface{})

	//LogWarnf log a message at WARN level
	LogWarnf(format string, a ...interface{})

	//LogErrorf log a message at ERROR level
	LogErrorf(format string, a ...interface{})

	//LogErrorfWithTrace log a message at ERROR level. Message output will be followed by a partial stack trace.
	LogErrorfWithTrace(format string, a ...interface{})

	//LogFatalf log a message at FATAL level
	LogFatalf(format string, a ...interface{})

	//LogAtLevelfCtx log at the specified level
	LogAtLevelf(level LogLevel, levelLabel string, format string, a ...interface{})

	//IsLevelEnabled returns true if a message at the supplied level would actually be logged. Useful to check
	//if the construction of a message would be expensive or slow.
	IsLevelEnabled(level LogLevel) bool
}

Logger is the interface used by application code to submit a message to potentially be logged to a file or console. Methods are of the form

Log[Level]f
Log[Level]fCtx

The Ctx versions of methods accept a Context. The Context is made available to the LogWriter implementations that write to files so that information in the Context can be potentially included in log line prefixes.

The f suffix indicates that the methods accept the same templates and variadic arguments as fmt.Printf

func CreateAnonymousLogger

func CreateAnonymousLogger(componentID string, threshold LogLevel) Logger

CreateAnonymousLogger creates a new Logger without attaching it to a LogManager. Useful for tests.

func NewStdoutLogger

func NewStdoutLogger(level LogLevel, prefix ...string) Logger

NewStdoutLogger creates a Granitic logger that logs to the console/stdout and respects log levels, but does not format the message or provide any formatting of the message

type MapBuilder added in v2.2.0

type MapBuilder struct {
	RequiresContextFilter bool
	// contains filtered or unexported fields
}

MapBuilder creates a map[string]interface{} representing a log entry, ready for JSON encoding

func CreateMapBuilder added in v2.2.0

func CreateMapBuilder(cfg *JSONConfig) (*MapBuilder, error)

CreateMapBuilder builds a component able to generate a log entry based on the rules in the supplied fields.

func (*MapBuilder) Build added in v2.2.0

func (mb *MapBuilder) Build(ctx context.Context, levelLabel, loggerName, message string) map[string]interface{}

Build creates a map and populates it

type NullLogger added in v2.1.0

type NullLogger struct {
}

NullLogger is a logger that ignores all supplied messages and always returns false for 'is level enabled' tests. Used when the application logging facility has been disabled

func (NullLogger) IsLevelEnabled added in v2.1.0

func (n NullLogger) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled always returns false

func (NullLogger) LogAtLevelf added in v2.1.0

func (n NullLogger) LogAtLevelf(level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelf does nothing

func (NullLogger) LogAtLevelfCtx added in v2.1.0

func (n NullLogger) LogAtLevelfCtx(ctx context.Context, level LogLevel, levelLabel string, format string, a ...interface{})

LogAtLevelfCtx does nothing

func (NullLogger) LogDebugf added in v2.1.0

func (n NullLogger) LogDebugf(format string, a ...interface{})

LogDebugf does nothing

func (NullLogger) LogDebugfCtx added in v2.1.0

func (n NullLogger) LogDebugfCtx(ctx context.Context, format string, a ...interface{})

LogDebugfCtx does nothing

func (NullLogger) LogErrorf added in v2.1.0

func (n NullLogger) LogErrorf(format string, a ...interface{})

LogErrorf does nothing

func (NullLogger) LogErrorfCtx added in v2.1.0

func (n NullLogger) LogErrorfCtx(ctx context.Context, format string, a ...interface{})

LogErrorfCtx does nothing

func (NullLogger) LogErrorfCtxWithTrace added in v2.1.0

func (n NullLogger) LogErrorfCtxWithTrace(ctx context.Context, format string, a ...interface{})

LogErrorfCtxWithTrace does nothing

func (NullLogger) LogErrorfWithTrace added in v2.1.0

func (n NullLogger) LogErrorfWithTrace(format string, a ...interface{})

LogErrorfWithTrace does nothing

func (NullLogger) LogFatalf added in v2.1.0

func (n NullLogger) LogFatalf(format string, a ...interface{})

LogFatalf does nothing

func (NullLogger) LogFatalfCtx added in v2.1.0

func (n NullLogger) LogFatalfCtx(ctx context.Context, format string, a ...interface{})

LogFatalfCtx does nothing

func (NullLogger) LogInfof added in v2.1.0

func (n NullLogger) LogInfof(format string, a ...interface{})

LogInfof does nothing

func (NullLogger) LogInfofCtx added in v2.1.0

func (n NullLogger) LogInfofCtx(ctx context.Context, format string, a ...interface{})

LogInfofCtx does nothing

func (NullLogger) LogTracef added in v2.1.0

func (n NullLogger) LogTracef(format string, a ...interface{})

LogTracef does nothing

func (NullLogger) LogTracefCtx added in v2.1.0

func (n NullLogger) LogTracefCtx(ctx context.Context, format string, a ...interface{})

LogTracefCtx does nothing

func (NullLogger) LogWarnf added in v2.1.0

func (n NullLogger) LogWarnf(format string, a ...interface{})

LogWarnf does nothing

func (NullLogger) LogWarnfCtx added in v2.1.0

func (n NullLogger) LogWarnfCtx(ctx context.Context, format string, a ...interface{})

LogWarnfCtx does nothing

type PrioritisedContextFilter added in v2.2.0

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

PrioritisedContextFilter groups together a series of other ContextFilter implementations in a priority order. When requests are received for filtered data, the data is gathered from the ContextFilter with the lowest priority. If the key is present in a higher priority filter, it overwrites the value in the lower priority filter.

func (*PrioritisedContextFilter) Add added in v2.2.0

Add inserts another ContextFilter to the list of prioritised filters and sorts the list

func (PrioritisedContextFilter) Extract added in v2.2.0

Extract takes all of the FilteredContextData from the lowest priority Context filter then overwrites it with data from higher priority instances.

type RuntimeControllableLog

type RuntimeControllableLog interface {
	//SetThreshold sets the logger's log level to the specified level
	SetThreshold(threshold LogLevel)

	//UpdateWritersAndFormatter causes the Logger to discard its current LogWriters and LogMessageFormatter in favour of the ones supplied.
	UpdateWritersAndFormatter([]LogWriter, *LogMessageFormatter)
}

RuntimeControllableLog is implemented by loggers that can be modified at runtime

type StringFormatter added in v2.2.0

type StringFormatter interface {
	// Format takes the message and prefixes it according the the rule specified in PrefixFormat or PrefixPreset
	Format(ctx context.Context, levelLabel, loggerName, message string) string

	//SetContextFilter provides the formatter with access selected data from a context
	SetContextFilter(cf ContextFilter)

	SetInstanceID(i *instance.Identifier)
}

A StringFormatter is a component able to take some logging message and associated data and format it as a string ready to be logged to a file or stream

type ValueGenerator added in v2.2.0

type ValueGenerator func(fcd FilteredContextData, levelLabel, loggerName, message string, field *JSONField) interface{}

ValueGenerator functions are able to generate a value for a field in a JSON formatted log entry

Jump to

Keyboard shortcuts

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