Documentation
¶
Index ¶
- Variables
- func ClearTemplate()
- func IsTTY(writer io.Writer) bool
- func Register(log *Log)
- func SetTemplate(log *Log)
- func WrapWriter(w io.Writer) io.Writer
- type ErrorCallback
- type FormatterFunc
- type ImmutableLogger
- type Level
- type Log
- func (l *Log) AddErrorCallback(fn ErrorCallback) *Log
- func (l *Log) AddFormatOverride(level Level, f FormatterFunc) *Log
- func (l *Log) Attach(name string, logger *Log) *Log
- func (l *Log) Chain(logger *Log) *Log
- func (l *Log) ClearBackend(level Level) io.Writer
- func (l *Log) DateFormat() string
- func (l *Log) Debug(v ...interface{})
- func (l *Log) Debugf(format string, v ...interface{})
- func (l *Log) Destroy(name string) *Log
- func (l *Log) Error(v ...interface{})
- func (l *Log) Errorf(format string, v ...interface{})
- func (l *Log) Fatal(v ...interface{})
- func (l *Log) Fatalf(format string, v ...interface{})
- func (l *Log) Fatalln(v ...interface{})
- func (l *Log) FullPath() string
- func (l *Log) Get(name string) *Log
- func (l *Log) Info(v ...interface{})
- func (l *Log) Infof(format string, v ...interface{})
- func (l *Log) Information(v ...interface{})
- func (l *Log) Informationf(format string, v ...interface{})
- func (l *Log) Inherit(name string) *Log
- func (l *Log) Iterate(fn func(*Log)) *Log
- func (l *Log) IterateAll(fn func(*Log)) *Log
- func (l *Log) Level() Level
- func (l *Log) Name() string
- func (l *Log) Newline() bool
- func (l *Log) Notice(v ...interface{})
- func (l *Log) Noticef(format string, v ...interface{})
- func (l *Log) Panic(v ...interface{})
- func (l *Log) Panicf(format string, v ...interface{})
- func (l *Log) Panicln(v ...interface{})
- func (l *Log) Print(v ...interface{})
- func (l *Log) Printf(format string, v ...interface{})
- func (l *Log) Println(v ...interface{})
- func (l *Log) SetBackend(backend io.Writer) *Log
- func (l *Log) SetBackendForLevel(level Level, backend io.Writer) *Log
- func (l *Log) SetDateFormat(format string) *Log
- func (l *Log) SetFormat(format string) *Log
- func (l *Log) SetFormatter(formatter FormatterFunc) *Log
- func (l *Log) SetFormatterFunc(fn func(string) FormatterFunc) *Log
- func (l *Log) SetLevel(level Level) *Log
- func (l *Log) SetNewline(nl bool) *Log
- func (l *Log) SetOnExit(fn func(string)) *Log
- func (l *Log) SetOnPanic(fn func(string)) *Log
- func (l *Log) SetOption(option string, value interface{}) *Log
- func (l *Log) SetRawBackend(backend io.Writer) *Log
- func (l *Log) SetRawBackendForLevel(level Level, backend io.Writer) *Log
- func (l *Log) SetTimezone(tz *time.Location) *Log
- func (l *Log) Warn(v ...interface{})
- func (l *Log) Warnf(format string, v ...interface{})
- func (l *Log) Warning(v ...interface{})
- func (l *Log) Warningf(format string, v ...interface{})
- func (l *Log) WithMeta(meta map[string]interface{}) *Log
- func (l *Log) WithMetaOpts(meta map[string]interface{}, opts MetaOptions) *Log
- func (l *Log) Writer() io.Writer
- type Message
- type MetaOptions
- type PkgLogger
- type StdLogger
- type SyncWriter
- type WhichCaller
- type Wrapper
Constants ¶
This section is empty.
Variables ¶
var ( // Black escape sequence (normal font type). Black = []byte{0x33, '[', '3', '0', 'm'} // Red escape sequence (normal font type). Red = []byte{0x33, '[', '3', '1', 'm'} // Green escape sequence (normal font type). Green = []byte{0x33, '[', '3', '2', 'm'} // Yellow escape sequence (normal font type). Yellow = []byte{0x33, '[', '3', '3', 'm'} // Blue escape sequence (normal font type). Blue = []byte{0x33, '[', '3', '4', 'm'} // Magenta escape sequence (normal font type). Magenta = []byte{0x33, '[', '3', '5', 'm'} // Cyan escape sequence (normal font type). Cyan = []byte{0x33, '[', '3', '6', 'm'} // White escape sequence (normal font type). White = []byte{0x33, '[', '3', '7', 'm'} // Reset escape sequence. Reset = []byte{0x33, '[', '0', 'm'} )
var Exit func(string) = _exit
Exit defines a function that is triggered, by default, for all Fatal* *Log calls. This can be overridden here by changing the value for the package as a whole, maintaining compatibility with earlier versions of go/logging.
Preferrably, this should be modified on the individual loggers via SetOnExit().
var Levels = []string{
"INHERIT",
"FATAL",
"ERROR",
"WARNING",
"NOTICE",
"INFO",
"DEBUG",
}
Levels defines the supported RFC 5424 logging levels in this package.
var Panic func(string) = _panic
Panic defines a function that is triggered, by default, for all Panic* *Log calls. This can be overridden here by changing the value for the package as a while, maintaining compatibility with earlier versions of go/logging.
Preferrably, this should be modified on the individual loggers via SetOnPanic().
var Stdout = WrapWriter(os.Stdout)
Stdout is the standard output writer, used globally by all writers by default to reduce risk of interleaving.
Functions ¶
func ClearTemplate ¶ added in v2.3.0
func ClearTemplate()
ClearTemplate resets the template logger. All generated loggers will be unique, will share no attributes, and will be configured using package defaults once this is called.
func Register ¶
func Register(log *Log)
Register the specified logger as a root logger.
N.B.: While this does not necessarily have to be a root logger and can, in fact, be any logger in particular, convention dictates that loggers registered here should not be the inheritors of any other logger.
One particularly helpful use case for registering root loggers in this manner is to avoid the implicit inheritance hierarchy: go/logging, when used with individual loggers, will interpret names containing dots as a tree of available loggers. For instance, "main.web.request" will be perceived by a logger as containing "main" at the top level, followed by "web," and then by "request." For that matter, "www.example.com" would likewise be split into individual parts ("www," "example," and "com"). As this is not desirable, registering separate top-level loggers allows both shunting logger handling into go/logging as well as avoiding the inheritance problem.
func SetTemplate ¶ added in v2.3.0
func SetTemplate(log *Log)
SetTemplate configures the template logger to the specified log. When set, all new loggers, except for the default root logger, will use this to initialize their state. All attributes will therefore be copied from this logger (meaning that per-level backends will be shared, among other attributes).
This is global state that will modify the behavior of this package. Use sparingly. Examples include overriding all generated loggers such that they use the same backend, level, etc., unless otherwise specified.
Types ¶
type FormatterFunc ¶
type FormatterFunc func(io.Writer, ImmutableLogger, *Message) error
FormatterFunc defines the type of a formatter function that can be used to override the use of Go templates. This function must accept the logger instance as its first argument followed by a single formatter (containing the message data) and return a string.
func NewDefaultFormatter ¶
func NewDefaultFormatter(format string) FormatterFunc
NewDefaultFormatter returns the defaultFormatter used by logging for inline variable string replacement.
This implementation is exceedingly basic, simple, and fairly performant. It is approximately 3 times faster than the Golang text template formatter and should be used except in rare circumstances where conditional manipulation of logging entries is required.
func NewFastFormatter ¶
func NewFastFormatter(format string) FormatterFunc
func NewTemplateFormatter ¶
func NewTemplateFormatter(tpl string, funcs map[string]interface{}) FormatterFunc
NewTemplateFormatter returns a formatter backed by Golang's text templates for line-by-line templating support.
templateFormatters support context-sensitive template functions via the `funcs` argument here and can be used to conditionally manipulate logging output.
Be aware that the templateFormatter is approximately 3 times slower than the default formatter.
type ImmutableLogger ¶
type ImmutableLogger interface { Name() string FullPath() string DateFormat() string Level() Level Newline() bool Error(...interface{}) Errorf(string, ...interface{}) Warn(...interface{}) Warnf(string, ...interface{}) Warning(...interface{}) Warningf(string, ...interface{}) Notice(...interface{}) Noticef(string, ...interface{}) Info(...interface{}) Infof(string, ...interface{}) Information(...interface{}) Informationf(string, ...interface{}) Debug(...interface{}) Debugf(string, ...interface{}) Print(...interface{}) Printf(string, ...interface{}) Println(...interface{}) Fatal(...interface{}) Fatalf(string, ...interface{}) Fatalln(...interface{}) Panic(...interface{}) Panicf(string, ...interface{}) Panicln(...interface{}) }
type Level ¶
type Level int
Level defines a type for use internally for identifying logging levels.
RFC 5424 levels (borrowed from syslog message facilities).
func LevelFromString ¶
LevelFromString returns a Level value (internally an integer) given a matching string. This serves as a simple map between string -> integer values of error levels.
Some levels have aliases. INFO and WARN can be given as "information" or "warning," respectively.
The case of input values is ignored.
type Log ¶
type Log struct { // This mutex covers the backends, log chain, options metadata, and child // loggers. sync.Mutex // Metadata options. Typically this map will be empty and isn't used // internally by the logger. However, it is provided for formatterOverrides // that may need additional metadata for configuration (such as enabling or // disabling colorized output, among other things). Options map[string]interface{} // contains filtered or unexported fields }
Log container.
func Get ¶
Get returns a new or existing root logger. Loggers created through this mechanism are registered with the global logger directory. To create a new unregistered logger, use New().
Root loggers are top level loggers from which all other loggers inherit. By default, go/logging possesses only a single root logger (the default). This function creates additional ones.
func Load ¶
Load returns a previously Register()'d logger or a logger previously created via GetLogger(). If the specified logger doesn't exist, the returned tuple will contain (nil, false).
func New ¶
New returns a new, unregistered logger. This logger, if destroyed, cannot be re-obtained unless it is first Register()'d.
func (*Log) AddErrorCallback ¶ added in v2.0.2
func (l *Log) AddErrorCallback(fn ErrorCallback) *Log
func (*Log) AddFormatOverride ¶
func (l *Log) AddFormatOverride(level Level, f FormatterFunc) *Log
AddFormatOverride injects an override function for the level specified.
func (*Log) Chain ¶
Chain another Log instance with the current logger. When a logger is configured to chain to another logger, any logging messages will be repeatedly dispatched down the chain until no more logger instances are found. In this way, it's possible to isolate multiple logger behaviors by error level.
For example, if you wish to create two loggers, one that logs only error messages (and nothing else) and another that logs everything (including error messages), such as might be necessary for applications that must write error messages to a file as well as to STDOUT, you can do the following:
errorsOnly := &bytes.Buffer{} // Error logger. errorLog := MustGetLogger("errors") errorLog.SetBackend(nil) // Clear the main backend. errorLog.SetBackendForLevel(Error, errorLog) // Everything else (remember, the default is to log to os.Stdout)... everythingLog := MustGetLogger("everything") // Chain the loggers starting with the most restrictive. errorLog.Chain(everything) // Now, when we call errorLog.*, it will always log to everythingLog. errorLog.Error("This is an error. It is written to both.") errorLog.Debug("This is a debug notice. It is written only to everythingLog.")
func (*Log) ClearBackend ¶
ClearBackend removes the backend for the specified level.
Returns the removed writer. If no such writer was set this value will be nil.
func (*Log) DateFormat ¶
func (*Log) Destroy ¶
Destroy destroys the child logger identified by `name` alongside any of its children.
func (*Log) Fatal ¶
func (l *Log) Fatal(v ...interface{})
Fatal works similarly to the Go standard library log.Fatal. Like Fatalf, it's treated as as an error condition and exits the application. It additionally logs the message as Fatal.
func (*Log) Fatalf ¶
Fatalf works identically to the Go standard library log.Fatalf, returning an error status and exiting the application. It additionally logs the message as Fatal.
func (*Log) Fatalln ¶
func (l *Log) Fatalln(v ...interface{})
Fatalln works similarly to the Go standard library log.Fatalln. Like Fatalf and Fatal, it's treated as an error condition and exits the application. It additionally logs the message as Fatal.
func (*Log) Get ¶
Get returns the child logger associated with this parent by its name `name`. If no such logger is configured it will be created.
func (*Log) Information ¶
func (l *Log) Information(v ...interface{})
Information is an alias for Info.
func (*Log) Informationf ¶
Informationf is an alias for Infof.
func (*Log) Inherit ¶
Inherit constructs a new logger from the parent instance and returns it. Inherited loggers retain all of their parent properties until they are manually changed and are configured with the special level value Inherit. Inherited loggers are registered globally with the parent's name as a dot-separated prefix (e.g. parent.child) and may be accessed via MustGet or by the parent logger via parent.Get.
Inherit will *always* overwrite an existing logger by the same name.
If a logger inheritance hierarchy declaration (e.g. a dot-separated name) is passed to this method, the last component will be used as the inherited logger name.
func (*Log) Iterate ¶
Iterate over the current logger's children, applying the function fn(). Callback functions receive the current logger as their sole argument.
Useful for modifying an entire logging tree.
func (*Log) IterateAll ¶
IterateAll attempts to iterate over *all* of the current logger's descendants.
func (*Log) Level ¶
GetLevel returns the level for the current logger or, if the level is set to the value Inherit, will return the level associated with the parent logger (if available).
If no suitable level is found, this will return Warning.
func (*Log) Newline ¶
Newline returns true if the logger appends a newline to the output, false otherwise.
This is used by formatters to decide whether they should attach a newline or not.
func (*Log) Notice ¶
func (l *Log) Notice(v ...interface{})
Notice logs a notice containing pertinent information. This does not indicate an error condition.
func (*Log) Noticef ¶
Noticef logs a notice containing pertinent information with formatting. This does not indicate an error condition.
func (*Log) Panic ¶
func (l *Log) Panic(v ...interface{})
Panic works similarly to the Go standard library log.Panic. Like Panicf, it's treated as as an error condition and panics. It additionally logs the message as fatal.
func (*Log) Panicf ¶
Panicf works identically to the Go standard library log.Panicf, printing the error and returning a panic. As with Fatalf, this logs the message as fatal.
This method will log the message twice if the output backend is STDOUT or STDERR and should typically be used only if it is expected that writing to the backend may fail (e.g. to a file or other output device; thus ensuring that whatever is connected to STDOUT or STDERR will still render the error message visible).
func (*Log) Panicln ¶
func (l *Log) Panicln(v ...interface{})
Panicln works similarly to the Go standard library log.Panicln. Like Panicf and Panic, it's treated as a fatal error and returns a panic.
func (*Log) Print ¶
func (l *Log) Print(v ...interface{})
Print works similarly to the Go standard library log.Print. Like Printf, it's treated as an informational message.
func (*Log) Printf ¶
Printf works similarly to the Go standard library log.Printf with the exception that it's treated as an informational message.
func (*Log) Println ¶
func (l *Log) Println(v ...interface{})
Println works similarly to the Go standard library log.Println. Like Printf and Print, it's treated as an informational message.
func (*Log) SetBackend ¶
SetBackend changes the default backend. This backend will be written to whenever any of the logging facility methods (Error, Critical, etc.) are called.
If you wish to override this backend for a specific logging level, use SetBackendForLevel.
Setting a backend with this function will wrap the given writer in a SyncWriter if it isn't already.
func (*Log) SetBackendForLevel ¶
SetBackendForLevel changes the backend to use for a specific level. Configuring this value will override the default backend for the specified level only.
For instance, creating the following:
buf := &bytes.Buffer{} logger := MustGetLogger("example") logger.SetBackendForLevel(Error, buf)
Will cause:
logger.Error("some error")
to save logging data to `buf`, while
logger.Warn("warning!") logger.Debug("some debugging information")
will both write to the default backend (os.Stdout).
To clear the backend for the specified level, reverting it back to using the default backend, call ClearBackend(level).
Setting a backend with this function will wrap the given writer in a SyncWriter if it isn't already.
func (*Log) SetDateFormat ¶
SetDateFormat changes the default date format for the current logger.
func (*Log) SetFormat ¶
SetFormat sets the logger format. Logger formats are typically formatter-specific and depend on the formatter that has been configured for a given logger. By default this is usually the "fast" formatter (NewFastFormatter). Be aware that configuring this value for the wrong formatter will produce unexpected output.
For built in templates, values are delinated by keys encapsulated in "{{" and "}}" and are comprised of the following values:
time - Timestamp. error - Error level text (one of FATAL, ERROR, WARN, NOTICE, INFO, DEBUG, INHERIT). ErrorLevel - Error level as represented by a positive integer. Message - Log message. ShortError - Truncated error level text containing exactly 4 characters (one of FATL, ERRO, WARN, NOTE, INFO, DEBUG, INHT).
For Golang-based templates the following fields are available:
.Time - Timestamp .Error - Error level text (one of FATAL, ERROR, WARN, NOTICE, INFO, DEBUG, INHERIT). .ErrorLevel - Error level (as a number between 0-7). .Message - Log message. .ShortError - Shortened error level text (one of FATL, ERRO, WARN, NOTE, INFO, DEBUG, INHT)
(The logging level "INHERIT" should ordinarily not be end-user visible and indicates that a logger inherits its parent's state. Visibility of this mode should be considered a bug and may be reported as such.)
The default format at configuration time is:
"[{{err}}] {{time}} - {{message}}"
(newlines are added automatically unless SetNewline is passed false.)
Most colorization libraries should be usable by setting the format string.
This will also update the internal formatter state and is analogous to calling SetFormatter(FormatterFactory("template")), e.g.:
logger.SetFormat("{{message}}")
is equivalent to:
logger.SetFormatter(logging.NewFastFormatter("{{message}}"))
func (*Log) SetFormatter ¶
func (l *Log) SetFormatter(formatter FormatterFunc) *Log
SetFormatter configures the backend formatter library. By default, this will be set to the formatter generated by NewFastFormatter. Values configured here must be of type FormatterFunc.
func (*Log) SetFormatterFunc ¶
func (l *Log) SetFormatterFunc(fn func(string) FormatterFunc) *Log
SetFormatterFunc configures a FormatterFunc factory function. This function must accept a single string (this is the format string configurable via SetFormat) and return a FormatterFunc.
func (*Log) SetLevel ¶
SetLevel changes the logger's level. Error messages that are at this level--or lower--will be logged; everything else will be ignored. Note that in this context "lower" means the literal integer value of the logger and not the relative importance of its data. For example, setting a logging level of Error will log anything at an Error or below (which includes Alert, Emergency, and Critical). Likewise, setting a logging level of Debug will log literally everything.
If you wish to control what the logger instance logs such as logging only Error-level messages, you'll need to manipulate the backends. This can be done by setting a backend for the Error level and clearing the default backend by setting it to nil.
func (*Log) SetNewline ¶
SetNewline configures whether the logger will automatically append a newline to each entry. True by default.
func (*Log) SetOnPanic ¶ added in v2.3.0
func (*Log) SetOption ¶
SetOption is the recommended method for setting metadata values in the logger. It's possible to set options by manipulating the Log.Options map directly but there is no stability guarantee provided for its continued export status.
func (*Log) SetRawBackend ¶
SetRawBackend behaves identically to SetBackend with the exception that it does not wrap the backend argument in a SyncWriter.
func (*Log) SetRawBackendForLevel ¶
SetRawBackendForLevel behaves identically to SetBackendForLevel with the exception that it does not wrap the backend argument in a SyncWriter.
func (*Log) SetTimezone ¶
SetTimezone sets the logger's timezone to the specified location. The logger uses time.UTC by default. Change this to time.Local to display the server's local time.
func (*Log) WithMeta ¶ added in v2.1.0
WithMeta returns a complete copy of the current logger, associated with the specified metadata. How this data is output will depend on the backend, template, and logger configuration.
Metadata is not printed by default. Bear in mind that calling WithMeta will greatly reduce the performance of your logger.
TODO: Return a *MetaLog that includes the above?
func (*Log) WithMetaOpts ¶ added in v2.1.0
func (l *Log) WithMetaOpts(meta map[string]interface{}, opts MetaOptions) *Log
WithMetaOpts is like WithMeta but allows callers to specify additional options. Presently, only the `lineno` option is available; if this is true, this will also include line number and file name logging.
type Message ¶
Message instance. This is used internally for the formatter template.
func (*Message) FormatTime ¶
FormatTime is the time formatting function. This is useful if client code wishes to use a Go template pipeline to change the format of the timestamp.
This is a convenience method and isn't required.
type MetaOptions ¶ added in v2.1.0
type MetaOptions struct { LineNo bool Caller WhichCaller }
type PkgLogger ¶
type PkgLogger interface { ImmutableLogger Attach(string, *Log) GetLogger(string) *Log Inherit(string) *Log Iterate(func(*Log)) IterateAll(func(*Log)) Chain(*Log) ClearBackend(Level) io.Writer DestroyLogger(string) SetBackend(io.Writer) *Log SetBackendForLevel(Level, io.Writer) *Log SetFormatter(FormatterFunc) *Log SetLevel(Level) *Log SetOption(string, interface{}) SetRawBackend(io.Writer) *Log SetRawBackendForLevel(Level, io.Writer) *Log SetTimezone(*time.Location) *Log Writer() io.Writer }
type StdLogger ¶
type StdLogger interface { Fatal(...interface{}) Fatalf(string, ...interface{}) Fatalln(...interface{}) Flags() int Output(int, string) error Panic(...interface{}) Panicf(string, ...interface{}) Panicln(...interface{}) Prefix() string Print(...interface{}) Printf(string, ...interface{}) Println(...interface{}) SetFlags(int) SetOutput(io.Writer) SetPrefix(string) Writer() io.Writer }
StdLogger defines an interface matching the logger from the Golang standard library logger.
func CoreLogger ¶
type SyncWriter ¶
SyncWriter provides an implementation of io.Writer that synchronizes logging messages such that interleaving output over a shared writer won't happen.
When using Logging's default settings, the internal reference to os.Stdout will be wrapped.
func (*SyncWriter) Wrapped ¶
func (w *SyncWriter) Wrapped() io.Writer
Wrapped returns the wrapped writer.
type WhichCaller ¶ added in v2.2.0
type WhichCaller int
const ( DefaultCaller WhichCaller = -1 PreviousCaller WhichCaller = iota )