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 http://granitic.io/1.0/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 (see package documentation for the ioc pacakge). 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 (see 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 http://granitic.io/1.0/ref/logging#output

Runtime control

Global log levels and component log levels can be changed at runtime, if your application has the RuntimeCtl facility enabled. See http://granitic.io/1.0/ref/runtime-ctl 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. See http://granitic.io/1.0/ref/logging#prefix

Index

Package Files

console.go format.go level.go logger.go manager.go writer.go

Constants

const (
    All   = 0
    Trace = 10
    Debug = 20
    Info  = 40
    Warn  = 50
    Error = 60
    Fatal = 70
)
const (
    AllLabel   = "ALL"
    TraceLabel = "TRACE"
    DebugLabel = "DEBUG"
    InfoLabel  = "INFO"
    WarnLabel  = "WARN"
    ErrorLabel = "ERROR"
    FatalLabel = "FATAL"
)
const FrameworkPresetPrefix = "framework"
const PresetFormatFramework = "%{02/Jan/2006:15:04:05 Z0700}t %P [%c] "

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.

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
}

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 (cw *AsynchFileWriter) Busy() bool

Returns true if one or more messages are queued for writing.

func (*AsynchFileWriter) Close Uses

func (afw *AsynchFileWriter) Close()

Closes the log file

func (*AsynchFileWriter) Init Uses

func (afw *AsynchFileWriter) Init() error

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 }

func (ByName) Less Uses

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

type ComponentLevel Uses

type ComponentLevel struct {
    Name  string
    Level LogLevel
}

Pairs a component named and its loglevel for sorting and presentation through RuntimeCtl

type ComponentLevels Uses

type ComponentLevels []*ComponentLevel

func (ComponentLevels) Len Uses

func (s ComponentLevels) Len() int

func (ComponentLevels) Swap Uses

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

type ComponentLoggerManager Uses

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

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 *LogMessageFormatter) *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

Create a new Logger for the supplied component name

func (*ComponentLoggerManager) CreateLoggerAtLevel Uses

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

Create 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

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

func (*ComponentLoggerManager) GlobalLevel Uses

func (clm *ComponentLoggerManager) GlobalLevel() LogLevel

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

func (*ComponentLoggerManager) LoggerByName Uses

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

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

Does nothing

func (*ComponentLoggerManager) ReadyToStop Uses

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

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

func (*ComponentLoggerManager) SetGlobalThreshold Uses

func (clm *ComponentLoggerManager) SetGlobalThreshold(globalThreshold LogLevel)

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{})

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.

func (*ComponentLoggerManager) Stop Uses

func (clm *ComponentLoggerManager) Stop() error

Closes all LogWriters attached to this component.

func (*ComponentLoggerManager) UpdateWritersAndFormatter Uses

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

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

type ConsoleErrorLogger Uses

type ConsoleErrorLogger struct {
}

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.

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{})

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogDebugfCtx Uses

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

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogErrorf Uses

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

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

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{})

LogErrorf 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{})

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogInfofCtx Uses

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

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogTracef Uses

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

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogTracefCtx Uses

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

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogWarnf Uses

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

Ignored - messages sent to this method are discarded.

func (*ConsoleErrorLogger) LogWarnfCtx Uses

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

Ignored - messages sent to this method are discarded.

type ConsoleWriter Uses

type ConsoleWriter struct {
}

Implementation of LogWriter that sends messages to the console/stdout using the fmt.Print method

func (*ConsoleWriter) Busy Uses

func (cw *ConsoleWriter) Busy() bool

Always returns false

func (*ConsoleWriter) Close Uses

func (cw *ConsoleWriter) Close()

Does nothing

func (*ConsoleWriter) WriteMessage Uses

func (cw *ConsoleWriter) WriteMessage(m string)

Passes message to fmt.Print

type GlobalLevel Uses

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

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

type GraniticLogger Uses

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

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

See Logger.IsLevelEnabled

func (*GraniticLogger) LogAtLevelf Uses

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

See Logger.LogAtLevelf

func (*GraniticLogger) LogAtLevelfCtx Uses

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

See Logger.LogAtLevelfCtx

func (*GraniticLogger) LogDebugf Uses

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

See Logger.LogDebugf

func (*GraniticLogger) LogDebugfCtx Uses

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

See Logger.LogDebugfCtx

func (*GraniticLogger) LogErrorf Uses

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

See Logger.LogErrorf

func (*GraniticLogger) LogErrorfCtx Uses

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

See Logger.LogErrorfCtx

func (*GraniticLogger) LogErrorfCtxWithTrace Uses

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

See Logger.LogErrorfCtxWithTrace

func (*GraniticLogger) LogErrorfWithTrace Uses

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

See Logger.LogErrorfWithTrace

func (*GraniticLogger) LogFatalf Uses

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

See Logger.LogFatalf

func (*GraniticLogger) LogFatalfCtx Uses

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

See Logger.LogFatalfCtx

func (*GraniticLogger) LogInfof Uses

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

See Logger.LogInfof

func (*GraniticLogger) LogInfofCtx Uses

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

See Logger.LogInfofCtx

func (*GraniticLogger) LogTracef Uses

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

See Logger.LogTracef

func (*GraniticLogger) LogTracefCtx Uses

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

See Logger.LogTracefCtx

func (*GraniticLogger) LogWarnf Uses

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

See Logger.LogWarnf

func (*GraniticLogger) LogWarnfCtx Uses

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

See Logger.LogWarnfCtx

func (*GraniticLogger) SetLocalThreshold Uses

func (grl *GraniticLogger) SetLocalThreshold(threshold LogLevel)

Sets the log threshold for this Logger

func (*GraniticLogger) UpdateWritersAndFormatter Uses

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

See RuntimeControllableLog.UpdateWritersAndFormatter

type LogLevel Uses

type LogLevel uint

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
    // contains filtered or unexported fields
}

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 (*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

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

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
}

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 acutally be logged. Useful to check
    //if the construction of a message would be expensive or slow.
    IsLevelEnabled(level LogLevel) bool
}

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.

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

Implemented by loggers that can be modified at runtime

Package logging imports 10 packages (graph) and is imported by 23 packages. Updated 2018-07-27. Refresh now. Tools for package owners.