logray

package module
v0.0.0-...-684fe44 Latest Latest
Warning

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

Go to latest
Published: Oct 9, 2017 License: Apache-2.0 Imports: 14 Imported by: 3 modules, 4 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

Logray

Goals

Multiple outputs

Our previous library had this, and logrus does through hooks. This is important to start using syslog.

(As an aside, the hooks approach is odd. In terms of practicality, you could view writing to syslog as more of an output instead of hook. Additionally, it makes sense to configure it as you would an output, with things like the loglevels it should send there. Additionally, viewing the formatter and output as two separate things like logrus does does not mesh with our outstanding).

Field propagation

Logrus added a fields map which allowed for more valuable metadata. We liked this and wanted to extend it, but logrus didn’t have fields building on fields. We wanted to take a context and pass it further down into the system, and have the fields build upon it as its actions got more specific. Logrus only lets you do a WithFields, which gave you an Entry, and could write multiple things on that, but couldn’t really have it turtle further down.

Contextually specific log formatting

At different places in the system, you care about different data related to log messages. The logging changes allow formats/outputs to be overwritten in certain places where the format we see directly matters in a slightly different way.

Simple to use

This library needed to be simple to use. So starting out, basically all you have have to do is write logger := logray.New() to start logging. (Note, perhaps writing to stdout by default should be added to the library). Want to add fields? You can write logger.SetField(key, value). Want to pass it further down where separate fields might be set? That's just logger2 := logger.Clone().

Documentation

Index

Constants

View Source
const (
	// Trace class logging.
	//
	// Logs in this class are typically dumping complete received message, etc. A
	// typical example of Tracing would be to dump the headers and POST data for a
	// request received via HTTP. Generally it should be expected that Trace class
	// calls will only be enabled when specific problems are being tracked.
	TRACE = LogClass(1)

	// Debug class logging.
	//
	// Debugging logging should show the general code path and should be used to
	// highlight edge case code deviations and such. This class will also not be
	// enabled by default.
	DEBUG = LogClass(TRACE << 1)

	// Info class logging.
	//
	// Info class logging is used to inform the admin of situations which are in
	// the normal code path. Examples of Info class logging include startup, shut
	// down notifications, or generalized query logs.
	INFO = LogClass(DEBUG << 1)

	// Warn class logging.
	//
	// Warnings are thrown when a problem happens that can be corrected.  Examples
	// of this type of logging include reconnect or disconnect notices. Logging
	// events in this class should not prevent anything from completing. For
	// example, if a query is delayed, but still completes then this is the right
	// class, but if the query fails then look at Error instead.
	WARN = LogClass(INFO << 1)

	// Error class logging.
	//
	// Error logging is for anything that impacts a query in a way that is
	// unrecoverable. Examples of this might be the inability to reconnect to a
	// backend, or a timeout on an operational call. Generally errors should be
	// reserved for specific failures which indicate that a request is failing.
	ERROR = LogClass(WARN << 1)

	// Fatal class logging.
	//
	// Fatal logs are used to report that something is wrong with the process
	// directly. A completely unexpected nil pointer, or a error writing to the
	// file system, etc. These are things for which recovery may not even be
	// possible and therefor further operation of the process is in question.
	FATAL = LogClass(ERROR << 1)

	// None, used to specify that no logging should be done.
	NONE = LogClass(0)

	// All, used when you want to change settings on all classes at once.
	ALL = (TRACE | DEBUG | INFO | WARN | ERROR | FATAL)

	// Trace+ is a set of TRACE, DEBUG, INFO, WARN, ERROR, FATAL and is used in
	// configuration to set all of those classes.
	TRACEPLUS = TRACE | DEBUG | INFO | WARN | ERROR | FATAL | isPLUSDEF

	// Debug+ is a set of DEBUG, INFO, WARN, ERROR, FATAL and is used in
	// configuration to set all of those classes.
	DEBUGPLUS = DEBUG | INFO | WARN | ERROR | FATAL | isPLUSDEF

	// Info+ is a set of INFO, WARN, ERROR, FATAL and is used in configuration to
	// set all of those classes.
	INFOPLUS = INFO | WARN | ERROR | FATAL | isPLUSDEF

	// WARN+ is a set of WARN, ERROR, FATAL and is used in configuration to set
	// all of those classes.
	WARNPLUS = WARN | ERROR | FATAL | isPLUSDEF

	// Trace+ is a set of ERROR, FATAL and is used in configuration to set all of
	// those classes.
	ERRORPLUS = ERROR | FATAL | isPLUSDEF

	// Fatal+ is a set of just FATAL. Its not expected to be used much however it
	// is provided to complete the API.
	FATALPLUS = FATAL | isPLUSDEF
)

Variables

View Source
var (
	// The default format string that will be applied when outputs are created.
	DefaultFormatString = "" +
		"%color:class%[%classfixed% " +
		"%year%-%month%-%day% %hour%:%minute%:%second%.%nanosecond% " +
		"%tzoffset% %tz% pid=%pid%" +
		"]%color:default% " +
		"%message%"
)

Functions

func AddDefaultOutput

func AddDefaultOutput(uri string, classes ...LogClass) error

AddDefaultOutput adds a new default output which will be used on newly created Loggers.

func AddNewOutputFunc

func AddNewOutputFunc(name string, f NewOutputFunc) bool

Adds a new output type to the map of possible outputs. This defines the Scheme that will be provided via the URL. Fragments are managed by the Output system rather than being dealt with in this function.

func ResetCachedOutputs

func ResetCachedOutputs()

ResetCachedOutputs clears all the cached outputs that were previously instantiated.

func ResetDefaultLogLevel

func ResetDefaultLogLevel(classes ...LogClass)

ResetDefaultLogLevel can be used to reconfigure the existing default outputs all be at a new log level.

func ResetDefaultOutput

func ResetDefaultOutput()

ResetDefaultOutput clears all the previously defined default outputs for new Loggers.

Types

type LineData

type LineData struct {
	Fields          map[string]interface{} `json:"fields"`
	Message         string                 `json:"message"`
	Class           LogClass               `json:"class"`
	TimeStamp       time.Time              `json:"time"`
	CallingPackage  string                 `json:"calling_package"`
	CallingFunction string                 `json:"calling_function"`
	SourceFile      string                 `json:"source_file"`
	SourceLine      int                    `json:"source_line"`
}

Data elements that are passed to an Output's Write function. In order to improve performance these are not copied prior to being passed to an Output's Write function and as such they should not be modified in the Output.Write call.

type LogClass

type LogClass uint32

The type used to specify class for log functions.

func ParseLogClass

func ParseLogClass(s string) (LogClass, error)

Parses a logclass string into a LogClass object. This call is case insensitive. If the string is not recognised then an error will be returned and LogClass will be set to NONE.

func (LogClass) String

func (l LogClass) String() string

Returns string representation of the given class.

type Logger

type Logger struct {
	// Fields represents metadata that has been captured to be associated with the
	// log messages.
	Fields map[string]interface{}
	// contains filtered or unexported fields
}

Logger represents the core struct that is used in order to write output from the application. It exposes all of the functions for log levels, fields for additional metadata, and has the outputs for log data associated with it.

func New

func New() *Logger

New returns a new Logger with the default configuration.

func (*Logger) AddOutput

func (logger *Logger) AddOutput(uri string, classes ...LogClass) error

AddOutput adds a new output for the Logger based on the provided URI.

func (*Logger) ClearFields

func (logger *Logger) ClearFields()

ClearFields resets the Field on the Logger.

func (*Logger) Clone

func (logger *Logger) Clone() *Logger

Clone returns a new Logger object and copies over the configuration and all fields along with it.

func (*Logger) Debug

func (logger *Logger) Debug(args ...interface{})

Injects a log in the debug class for this category if logging for this category is enabled, otherwise this does nothing. This will format the given arguments using fmt.Sprint. If a format string is desired then use Debugf() instead.

func (*Logger) Debugf

func (logger *Logger) Debugf(format string, args ...interface{})

Injects a log in the debug class for this category if logging for this category is enabled, otherwise this does nothing. This formats the log line using the format string provided (See fmt.Sprintf).

func (*Logger) Error

func (logger *Logger) Error(args ...interface{})

Injects a log in the error class for this category if logging for this category is enabled, otherwise this does nothing. This will format the given arguments using fmt.Sprint. If a format string is desired then use Errorf() instead.

func (*Logger) Errorf

func (logger *Logger) Errorf(format string, args ...interface{})

Injects a log in the error class for this category if logging for this category is enabled, otherwise this does nothing. This formats the log line using the format string provided (See fmt.Sprintf).

func (*Logger) Flush

func (logger *Logger) Flush()

Flush is used to ensure the logger has flushed all queued log lines to its outputs before returning.

func (*Logger) Info

func (logger *Logger) Info(args ...interface{})

Injects a log in the info class for this category if logging for this category is enabled, otherwise this does nothing. This will format the given arguments using fmt.Sprint. If a format string is desired then use Infof() instead.

func (*Logger) Infof

func (logger *Logger) Infof(format string, args ...interface{})

Injects a log in the info class for this category if logging for this category is enabled, otherwise this does nothing. This formats the log line using the format string provided (See fmt.Sprintf).

func (*Logger) RemoveFields

func (logger *Logger) RemoveFields(keys ...string)

RemoveFields will remove any of the mentioned keys from the Logger's Fields.

func (*Logger) ResetOutput

func (logger *Logger) ResetOutput()

ResetOutput clears all the previously defined outputs on the Logger.

func (*Logger) SetField

func (logger *Logger) SetField(key string, value interface{})

SetField is used to set the specified field to the provided value on the current Logger.

func (*Logger) SetFields

func (logger *Logger) SetFields(fields map[string]interface{})

SetFields can be used to copy all of the values in the provided fields map to the current Logger.

func (*Logger) Trace

func (logger *Logger) Trace(args ...interface{})

Injects a log in the trace class for this category if logging for this category is enabled, otherwise this does nothing. This will format the given arguments using fmt.Sprint. If a format string is desired then use Tracef() instead.

func (*Logger) Tracef

func (logger *Logger) Tracef(format string, args ...interface{})

Injects a log in the trace class for this category if logging for this category is enabled, otherwise this does nothing. This formats the log line using the format string provided (See fmt.Sprintf).

func (*Logger) UpdateOutput

func (logger *Logger) UpdateOutput(uri string, classes ...LogClass) error

UpdateOutput updates an existing output matching for an URI scheme and exact classes match. For ex. if classes passed here are, DEBUG and ERROR, it will update Outputs with Class equals to DEBUG|ERROR.

func (*Logger) Warn

func (logger *Logger) Warn(args ...interface{})

Injects a log in the warn class for this category if logging for this category is enabled, otherwise this does nothing. This will format the given arguments using fmt.Sprint. If a format string is desired then use Warnf() instead.

func (*Logger) Warnf

func (logger *Logger) Warnf(format string, args ...interface{})

Injects a log in the warn class for this category if logging for this category is enabled, otherwise this does nothing. This formats the log line using the format string provided (See fmt.Sprintf).

type NewOutputFunc

type NewOutputFunc func(u *url.URL) (Output, error)

Function used to create a new output object.

type Output

type Output interface {
	// Writes a line into this output device.
	Write(data *LineData) error

	// Flushes the buffered output in order to ensure that data is written to this
	// output's destination.
	Flush() error
}

Output objects are used as the actual destination for log lines.

func NewIOWriterOutput

func NewIOWriterOutput(w io.Writer, format string, color string) (Output, error)

This function creates a special case of the Output object which will write to the given io.Writer interface. This special case supports formatting as well as colorization where possible.

See the Examples section of the godoc for examples of how to use this with custom code.

The format string defined in "format" follows a syntax where a code is surrounded by percent signs. What follows is a list of the working codes supported by the format function.

%% - Replaced with a literal percent sign.
%class% - Replaced with the uppercase string representation of the
    class used to generate the given log line. Examples of this field
    are 'INFO' or 'ERROR'.
%classfixed% - Replaced with the uppercase string representation of the
    class used to generate the given log line, fixed to 5 characters
    width. Similar to %class%, but will pad the text to ensure a
    consistent width.
%message% - Replaced with the message generated when logging. This is
    the string ultimately generated by the call to functions like Infof()
%nanosecond% - Replaced with the number of nanoseconds elapsed since the
    start of the last second in the time stamp. This will always be
    a 9 digit number from 000000000 to 999999999.
%second% - Replaced with the number of seconds that have elapsed since
    the start of the last minute in the time stamp. This will always
    be a 2 digit number from 00 to 59
%minute% - Replaced with the number of minutes that have elapsed since
    the start of the last hour in the time stamp. This will always be
    a 2 digit number from 00 to 59.
%hour% - Replaced with the number of hours that have elapsed since the
    start of the day in the time stamp. This is 24 hour format, and as
    such will be a 2 digit number between 00 and 23
%day% - Replaced with the number of days that have elapsed from the
    start of the month in the time stamp. This will always be a 2
    digit number between 01 and 31
%month% - Replaced with the number of months elapsed since the start
    of the year. This will always be a 2 digit number between 01 and 12.
%year% - Replaced with the number of years since the start of the
    common era. This will always be a four digit number between 0000
    and 9999, however it will most likely take the form: 2013, 2014, etc.
%epoch% - Replaced with the number of seconds that have elapsed since
    the Unix standard epoch (Midnight, Jan 1, 1970, UTC) less leap
    seconds. See http://en.wikipedia.org/wiki/Unix_time
%tzoffset% - Replaced with a decimal representation of the offset for
    a given timezone. This will be a 4 digit number, prefaced with either
    a + or a - sign. An example of this is: -0600 MDT, or +0000 GMT
%tz% - A string representation of the current time zone. This is a
    three to four character string of the form: PDT, PST, EST, UTC, etc.
%hostname% - Replaced with the current hostname of the machine.
%pid% - The PID of the current process.

There are also special color codes which allow color to be inserted into the stream. These are optionally inserted based on the value of the parameter "color". Colors are enabled for the following values: on, yes, true; and will be disabled for the following values: off, no, false. Additionally if the value is an empty string, or auto then the output module will attempt to detect color support by looking to see if the output device is a terminal.

The following color tags exist, if color is disabled then these will inject nothing into the stream, otherwise they will insert the ANSI codes required to change the color to the given value. Do not forget to reset color coding at the end of the format string by using: %color:default%.

Supported codes:

%color:black% - Changes the color for following text to black.
%color:bright-black% - Changes the color for following text to black.
%color:blue% - Changes the color for following text to blue.
%color:bright-blue% - Changes the color for following text
    to bright blue.
%color:cyan% - Changes the color for following text to cyan.
%color:bright-cyan% - Changes the color for following text
    to bright cyan.
%color:green% - Changes the color for following text to green.
%color:bright-green% - Changes the color for following text
    to bright green.
%color:magenta% - Changes the color for following text to magenta.
%color:bright-magenta% - Changes the color for following text
    to bright magenta.
%color:red% - Changes the color for following text to red.
%color:bright-red% - Changes the color for following text to bright red.
%color:white% - Changes the color for following text to a
    dim white which usually appears grey.
%color:bright-white% - Changes the color for following text to white.
%color:yellow% - Changes the color for following text to yellow.
%color:bright-yellow% - Changes the color for following text to
    bright yellow.

%color:default% - Resets the color to the default color for the console.
%color:class% - Sets the color to the color associated with the class
    of the log line being written. This is used to change the
    output color to differentiate lines visually. The default colors are:
      DEBUG: grey
      TRACE: grey
      INFO: green
      WARN: yellow
      ERROR: red
      FATAL: magenta

On success an Output interface will be returned, other wise Output will be nil and an error will be returned. The format string is parsed during this call in order to reduce the expense of logging a single line. This means that formatting errors like using an unsupported code, forgetting to close a code and such will return an error here, which in turn prevents the output from being used.

Directories

Path Synopsis
A simple package for dealing with logging module output during the unit testing cycle.
A simple package for dealing with logging module output during the unit testing cycle.

Jump to

Keyboard shortcuts

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