granitic: github.com/graniticio/granitic/logging Index | Files

package logging

import "github.com/graniticio/granitic/logging"

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

Package Files

console.go contextfilter.go format.go level.go logger.go manager.go null.go structured.go writer.go

Constants

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
)
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"
)
const FrameworkPresetPrefix = "framework"

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

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

PresetFormatFramework is the default prefix format for log lines

func LabelFromLevel Uses

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 Uses

func ValidateJSONFields(fields []*JSONField) error

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

type AsynchFileWriter Uses

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 Uses

func (afw *AsynchFileWriter) Busy() bool

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

func (*AsynchFileWriter) Close Uses

func (afw *AsynchFileWriter) Close()

Close closes the log file

func (*AsynchFileWriter) Init Uses

func (afw *AsynchFileWriter) Init() error

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

func (*AsynchFileWriter) WriteMessage Uses

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 Uses

type ByName struct{ ComponentLevels }

ByName allows ComponentLevels to be sorted by name

func (ByName) Less Uses

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

Less supports sorting by name

type ComponentLevel Uses

type ComponentLevel struct {
    Name  string
    Level LogLevel
}

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

type ComponentLevels Uses

type ComponentLevels []*ComponentLevel

ComponentLevels allows a slice of ComponentLevel structs to be sorted

func (ComponentLevels) Len Uses

func (s ComponentLevels) Len() int

Len supports sorting

func (ComponentLevels) Swap Uses

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

Swap supports sorting

type ComponentLoggerManager Uses

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 Uses

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 Uses

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

CreateLogger creates a new Logger for the supplied component name

func (*ComponentLoggerManager) CreateLoggerAtLevel Uses

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 Uses

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

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

func (*ComponentLoggerManager) DeferLog Uses

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 Uses

func (clm *ComponentLoggerManager) Disable()

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

func (*ComponentLoggerManager) ForceFlush Uses

func (clm *ComponentLoggerManager) ForceFlush()

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

func (*ComponentLoggerManager) GlobalLevel Uses

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 Uses

func (clm *ComponentLoggerManager) IsDisabled() bool

IsDisabled checks to see if this manager has been disabled

func (*ComponentLoggerManager) LoggerByName Uses

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 Uses

func (clm *ComponentLoggerManager) PrepareToStop()

PrepareToStop does nothing

func (*ComponentLoggerManager) ReadyToStop Uses

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

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

func (*ComponentLoggerManager) RegisterInstanceID Uses

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

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

func (*ComponentLoggerManager) SetGlobalThreshold Uses

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 Uses

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 Uses

func (clm *ComponentLoggerManager) StartComponent() error

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

func (*ComponentLoggerManager) Stop Uses

func (clm *ComponentLoggerManager) Stop() error

Stop closes all LogWriters attached to this component.

func (*ComponentLoggerManager) UpdateWritersAndFormatter Uses

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

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

type ConsoleErrorLogger Uses

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 Uses

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

IsLevelEnabled returns true if the supplied level is >= Error

func (*ConsoleErrorLogger) LogAtLevelf Uses

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 Uses

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 Uses

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

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

func (*ConsoleErrorLogger) LogDebugfCtx Uses

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

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

func (*ConsoleErrorLogger) LogErrorf Uses

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 Uses

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 Uses

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 Uses

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 Uses

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

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

func (*ConsoleErrorLogger) LogFatalfCtx Uses

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 Uses

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

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

func (*ConsoleErrorLogger) LogInfofCtx Uses

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

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

func (*ConsoleErrorLogger) LogTracef Uses

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

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

func (*ConsoleErrorLogger) LogTracefCtx Uses

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

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

func (*ConsoleErrorLogger) LogWarnf Uses

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

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

func (*ConsoleErrorLogger) LogWarnfCtx Uses

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

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

type ConsoleWriter Uses

type ConsoleWriter struct {
}

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

func (*ConsoleWriter) Busy Uses

func (cw *ConsoleWriter) Busy() bool

Busy always returns false

func (*ConsoleWriter) Close Uses

func (cw *ConsoleWriter) Close()

Close does nothing

func (*ConsoleWriter) WriteMessage Uses

func (cw *ConsoleWriter) WriteMessage(m string)

WriteMessage passes message to fmt.Print

type ContextFilter Uses

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 Uses

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 Uses

type FilteredContextData map[string]string

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

type FixedPrefixConsoleWriter Uses

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 Uses

func (cw *FixedPrefixConsoleWriter) Busy() bool

Busy always returns false

func (*FixedPrefixConsoleWriter) Close Uses

func (cw *FixedPrefixConsoleWriter) Close()

Close does nothing

func (*FixedPrefixConsoleWriter) WriteMessage Uses

func (cw *FixedPrefixConsoleWriter) WriteMessage(m string)

WriteMessage passes message to fmt.Print

type GlobalLevel Uses

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 Uses

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 Uses

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

IsLevelEnabled implements Logger.IsLevelEnabled

func (*GraniticLogger) LogAtLevelf Uses

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

LogAtLevelf implements Logger.LogAtLevelf

func (*GraniticLogger) LogAtLevelfCtx Uses

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

LogAtLevelfCtx implements Logger.LogAtLevelfCtx

func (*GraniticLogger) LogDebugf Uses

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

LogDebugf implements Logger.LogDebugf

func (*GraniticLogger) LogDebugfCtx Uses

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

LogDebugfCtx implements Logger.LogDebugfCtx

func (*GraniticLogger) LogErrorf Uses

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

LogErrorf implements Logger.LogErrorf

func (*GraniticLogger) LogErrorfCtx Uses

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

LogErrorfCtx implements Logger.LogErrorfCtx

func (*GraniticLogger) LogErrorfCtxWithTrace Uses

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

LogErrorfCtxWithTrace implements Logger.LogErrorfCtxWithTrace

func (*GraniticLogger) LogErrorfWithTrace Uses

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

LogErrorfWithTrace implements Logger.LogErrorfWithTrace

func (*GraniticLogger) LogFatalf Uses

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

LogFatalf implements Logger.LogFatalf

func (*GraniticLogger) LogFatalfCtx Uses

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

LogFatalfCtx implements Logger.LogFatalfCtx

func (*GraniticLogger) LogInfof Uses

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

LogInfof implements Logger.LogInfof

func (*GraniticLogger) LogInfofCtx Uses

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

LogInfofCtx implements Logger.LogInfofCtx

func (*GraniticLogger) LogTracef Uses

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

LogTracef implements Logger.LogTracef

func (*GraniticLogger) LogTracefCtx Uses

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

LogTracefCtx implements Logger.LogTracefCtx

func (*GraniticLogger) LogWarnf Uses

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

LogWarnf implements Logger.LogWarnf

func (*GraniticLogger) LogWarnfCtx Uses

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

LogWarnfCtx implements Logger.LogWarnfCtx

func (*GraniticLogger) SetLocalThreshold Uses

func (grl *GraniticLogger) SetLocalThreshold(threshold LogLevel)

SetLocalThreshold sets the log threshold for this Logger

func (*GraniticLogger) UpdateWritersAndFormatter Uses

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

UpdateWritersAndFormatter implements RuntimeControllableLog.UpdateWritersAndFormatter

type JSONConfig Uses

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 Uses

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 Uses

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

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

type JSONLogFormatter Uses

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 Uses

func (jlf *JSONLogFormatter) AllowAccess() error

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

func (*JSONLogFormatter) Format Uses

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 Uses

func (jlf *JSONLogFormatter) SetContextFilter(cf ContextFilter)

SetContextFilter provides the formatter with access selected data from a context

func (*JSONLogFormatter) SetInstanceID Uses

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

SetInstanceID accepts the current instance ID

type LogLevel Uses

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 Uses

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 Uses

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 Uses

func NewFrameworkLogMessageFormatter() *LogMessageFormatter

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

func NewNoPrefixFormatter Uses

func NewNoPrefixFormatter() *LogMessageFormatter

NewNoPrefixFormatter creates a LogMessageFormatter that doesn't apply a prefix

func (*LogMessageFormatter) Format Uses

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 Uses

func (lmf *LogMessageFormatter) Init() error

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

func (*LogMessageFormatter) SetContextFilter Uses

func (lmf *LogMessageFormatter) SetContextFilter(cf ContextFilter)

SetContextFilter provides the formatter with access selected data from a context

func (*LogMessageFormatter) SetInstanceID Uses

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

SetInstanceID accepts the current instance ID

type LogWriter Uses

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 Uses

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 Uses

func CreateAnonymousLogger(componentID string, threshold LogLevel) Logger

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

func NewStdoutLogger Uses

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 Uses

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 Uses

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 Uses

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

Build creates a map and populates it

type NullLogger Uses

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 Uses

func (n NullLogger) IsLevelEnabled(level LogLevel) bool

IsLevelEnabled always returns false

func (NullLogger) LogAtLevelf Uses

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

LogAtLevelf does nothing

func (NullLogger) LogAtLevelfCtx Uses

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

LogAtLevelfCtx does nothing

func (NullLogger) LogDebugf Uses

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

LogDebugf does nothing

func (NullLogger) LogDebugfCtx Uses

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

LogDebugfCtx does nothing

func (NullLogger) LogErrorf Uses

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

LogErrorf does nothing

func (NullLogger) LogErrorfCtx Uses

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

LogErrorfCtx does nothing

func (NullLogger) LogErrorfCtxWithTrace Uses

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

LogErrorfCtxWithTrace does nothing

func (NullLogger) LogErrorfWithTrace Uses

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

LogErrorfWithTrace does nothing

func (NullLogger) LogFatalf Uses

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

LogFatalf does nothing

func (NullLogger) LogFatalfCtx Uses

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

LogFatalfCtx does nothing

func (NullLogger) LogInfof Uses

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

LogInfof does nothing

func (NullLogger) LogInfofCtx Uses

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

LogInfofCtx does nothing

func (NullLogger) LogTracef Uses

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

LogTracef does nothing

func (NullLogger) LogTracefCtx Uses

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

LogTracefCtx does nothing

func (NullLogger) LogWarnf Uses

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

LogWarnf does nothing

func (NullLogger) LogWarnfCtx Uses

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

LogWarnfCtx does nothing

type PrioritisedContextFilter Uses

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 Uses

func (pcf *PrioritisedContextFilter) Add(cf ContextFilter)

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

func (PrioritisedContextFilter) Extract Uses

func (pcf PrioritisedContextFilter) Extract(ctx context.Context) FilteredContextData

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

type RuntimeControllableLog Uses

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 Uses

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 Uses

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

Package logging imports 15 packages (graph). Updated 2020-09-15. Refresh now. Tools for package owners.