Documentation ¶
Overview ¶
Package plog is used for logging and sending logs to a log server, where they'll be aggregated into log objects and kept safe even if the client program exists or crashes. Can also be used without the server in which case a fallback writer is used instead.
The LogMsg class of functions are the latest and most useful ones. You can either use the package level LogMsg with any key you wish or use e.g. plog.Info.LogMsg for a standard "INFO" key.
A Setup function is provided to apply this package to the standard log interface and also to the other sebase packages. It's recommended to call Setup if you use this package.
For advanced usage recursive plog contexts can be opened. They then log a JSON object once all the contexts under the root are closed. If plogd is running it will detect if a context was not closed properly and log an "@interrupted" key which might be useful to find which request caused an error.
Context based logging is done either via the package level Ctx function or Level.Ctx. Info logging is thus likely plog.Info.Ctx(ctx).LogMsg or plog.Info.CtxMsg as a shortcut. These apply filters that can be stored in the context via slog.ContextWithFilter.
You can also store a plog context or another logger function using plog.ContextWithLogger. Those can also be used to apply context to the logs. If a plog context is used it can be retrieved using CtxPlog.
Various compatibility and shortcut functions also exist, for example there are Print and Printf package level functions.
Index ¶
- Constants
- Variables
- func ContextWithLogger(ctx context.Context, l ContextLogger) context.Context
- func CtxMsg(ctx context.Context, key, msg string, kvs ...interface{})
- func FallbackFormatKey(key []FallbackKey) []string
- func FallbackFormatterJsonWrap(key []FallbackKey, value []byte) (n int, err error)
- func FallbackFormatterSimple(key []FallbackKey, value []byte) (n int, err error)
- func Log(key string, value interface{}) error
- func LogDict(key string, kvs ...interface{}) error
- func LogMsg(key, msg string, kvs ...interface{})
- func Print(value ...interface{})
- func Printf(fmt string, value ...interface{})
- func Setup(appname, lvl string)
- func Shutdown()
- type ContextLogger
- type ContextLoggerFunc
- type FallbackKey
- type Fields
- type Level
- func (l Level) Code() string
- func (l Level) Ctx(ctx context.Context) TypeLogger
- func (l Level) CtxMsg(ctx context.Context, msg string, kvs ...interface{})
- func (l Level) Fatal(v ...interface{})
- func (l Level) FatalMsg(msg string, v ...interface{})
- func (l Level) Fatalf(format string, v ...interface{})
- func (l Level) LogDict(kvs ...interface{}) error
- func (l Level) LogMsg(msg string, kvs ...interface{})
- func (l Level) Lower() string
- func (l Level) Msg(msg string)
- func (l Level) Msgf(format string, values ...interface{})
- func (l Level) Panic(v ...interface{})
- func (l Level) PanicMsg(msg string, v ...interface{})
- func (l Level) Panicf(format string, v ...interface{})
- func (l Level) Print(v ...interface{})
- func (l Level) Printf(format string, v ...interface{})
- func (l Level) String() string
- func (l Level) With(kvs ...interface{}) TypeLogger
- func (l Level) Write(w []byte) (n int, err error)
- type Logger
- type Plog
- func (plog *Plog) Alert(value ...interface{})
- func (plog *Plog) Alertf(format string, value ...interface{})
- func (ctx *Plog) Close() error
- func (plog *Plog) Critical(value ...interface{})
- func (plog *Plog) Criticalf(format string, value ...interface{})
- func (plog *Plog) Ctx(ctx context.Context) Logger
- func (plog *Plog) CtxMsg(ctx context.Context, key, msg string, kvs ...interface{})
- func (plog *Plog) Debug(value ...interface{})
- func (plog *Plog) Debugf(format string, value ...interface{})
- func (plog *Plog) Emergency(value ...interface{})
- func (plog *Plog) Emergencyf(format string, value ...interface{})
- func (plog *Plog) Error(value ...interface{})
- func (plog *Plog) Errorf(format string, value ...interface{})
- func (plog *Plog) Fatal(value ...interface{})
- func (plog *Plog) Fatalf(format string, value ...interface{})
- func (plog *Plog) Info(value ...interface{})
- func (plog *Plog) Infof(format string, value ...interface{})
- func (plog *Plog) LevelPrint(level Level, value ...interface{})
- func (plog *Plog) LevelPrintf(level Level, format string, value ...interface{})
- func (ctx *Plog) Log(key string, value interface{}) error
- func (ctx *Plog) LogAsString(key string, value []byte)
- func (ctx *Plog) LogDict(key string, kvs ...interface{}) error
- func (ctx *Plog) LogJSON(key string, value []byte)
- func (ctx *Plog) LogMsg(key, msg string, kvs ...interface{})
- func (plog *Plog) Notice(value ...interface{})
- func (plog *Plog) Noticef(format string, value ...interface{})
- func (ctx *Plog) OpenDict(key string) *Plog
- func (ctx *Plog) OpenList(key string) *Plog
- func (ctx *Plog) OpenListOfDicts(key string) *Plog
- func (plog *Plog) Panic(value ...interface{})
- func (plog *Plog) Panicf(format string, value ...interface{})
- func (plog *Plog) Type(key string) TypeLogger
- func (plog *Plog) Warning(value ...interface{})
- func (plog *Plog) Warningf(format string, value ...interface{})
- func (plog *Plog) With(kvs ...interface{}) Logger
- func (plog *Plog) WithFields(f Fields) Logger
- type TestMessage
- type TypeLogger
Constants ¶
const Crit = Critical
Crit is an alias for Critical.
Variables ¶
var FallbackFormatter func(key []FallbackKey, value []byte) (n int, err error) = FallbackFormatterJsonWrap
FallbackFormatter used for fallback writes. Can be overwritten to customize output. All values are json encoded. The key is constructed recursively with parent contexts prefixed, if any. Setup will change the default value to FallbackFormatterSimple if it detects that FallbackWriter is a tty when it's called. The default format might change without a major package version bump, set this manually if you depend on it.
var FallbackWriter io.Writer = os.Stderr
FallbackWriter is where logs go if we can't connect to plogd. Defaults to stderr.
var LevelAddMsg bool = false
LevelAddMsg if true, logs messages passed via Level.Write as a JSON dictionary with a "msg" key rather than directly as a string.
var LevelByName = map[string]Level{ "Emergency": Emergency, "EMERG": Emergency, "emerg": Emergency, "emergency": Emergency, "Alert": Alert, "ALERT": Alert, "alert": Alert, "Critical": Critical, "CRIT": Critical, "crit": Critical, "critical": Critical, "Error": Error, "ERR": Error, "err": Error, "error": Error, "Warning": Warning, "WARNING": Warning, "warning": Warning, "Notice": Notice, "NOTICE": Notice, "notice": Notice, "Info": Info, "INFO": Info, "info": Info, "Debug": Debug, "DEBUG": Debug, "debug": Debug, }
LevelByName is a reverse map from names to level constants. Typically accessed via the LogLevel function.
var LevelNames = map[Level]struct { Name, Code, Lower string }{ Emergency: {"Emergency", "EMERG", "emerg"}, Alert: {"Alert", "ALERT", "alert"}, Critical: {"Critical", "CRIT", "crit"}, Error: {"Error", "ERR", "err"}, Warning: {"Warning", "WARNING", "warning"}, Notice: {"Notice", "NOTICE", "notice"}, Info: {"Info", "INFO", "info"}, Debug: {"Debug", "DEBUG", "debug"}, }
LevelNames gives different names for the levels. It's meant to be read-only.
var SetupLevel = Info
SetupLevel is the threshold for logging, only this and higher prio levels will be logged. Modified by Setup.
Functions ¶
func ContextWithLogger ¶ added in v1.4.1
func ContextWithLogger(ctx context.Context, l ContextLogger) context.Context
ContextWithLogger stores l in ctx so that it can be used by the Ctx functions. If l is a *Plog it can also be retrieved with CtxPlog. Also consider using slog.ContextWithFilter as another way to modify logging via contexts.
func CtxMsg ¶ added in v1.4.1
CtxMsg logs a message together with a JSON dictionary from the variadic arguments, which are parsed by slog.CtxKVsMap. Logs to the logger stored in ctx, if any. Otherwise to Default or FallbackWriter if Default is nil. This function does not return errors. If json encoding fails it converts to a string and tries again, adding a "log-error" key.
func FallbackFormatKey ¶ added in v1.1.0
func FallbackFormatKey(key []FallbackKey) []string
FallbackFormatKey formats key in a standard way as a string slice. If the ctx id is <= 1 then that ctx id is skipped due to being reduntant and that key is used as-is. Otherwise each entry has the form key[ctxId].
func FallbackFormatterJsonWrap ¶ added in v1.1.0
func FallbackFormatterJsonWrap(key []FallbackKey, value []byte) (n int, err error)
FallbackFormatterJsonWrap creates logs that will be written as JSON objects with key, message and @timestamp fields. The last entry in key is logged as "type" instead.
func FallbackFormatterSimple ¶ added in v1.1.0
func FallbackFormatterSimple(key []FallbackKey, value []byte) (n int, err error)
FallbackFormatterSimple creates logs thath will be written prefixed with key and suffixed with a newline. After FallbackFormatKey the key is joined with dots (.). The key is then printed with a colon and the json encoded value after.
func Log ¶ added in v1.1.0
Log logs to Default if not nil, or to FallbackWriter if Default is nil. Might return errors from json.Marshal, if it fails to encode the value given. This is a low level function, you likely want to use Level.LogMsg instead, or the package level LogMsg if you wish to customize the key.
func LogDict ¶ added in v1.1.0
LogDict logs a JSON dictionary from the variadic arguments, which are parsed with slog.KVsMap. Logs to Default or to FallbackWriter if nil. Deprecated in favor of LogMsg.
func LogMsg ¶ added in v1.2.0
func LogMsg(key, msg string, kvs ...interface{})
LogMsg logs a message together with a JSON dictionary from the variadic arguments, which are parsed by slog.KVsMap. Logs to Default or to FallbackWriter if Default is nil. This function does not return errors. If json encoding fails it converts to a string and tries again, adding a "log-error" key.
func Printf ¶ added in v1.1.0
func Printf(fmt string, value ...interface{})
Printf is shorthand for Info.Printf
func Setup ¶
func Setup(appname, lvl string)
Setup initializes the default plog context and changes SetupLevel based on a string. Changes the functions used by the slog package to plog and also calls log.SetOutput(plog.Info) to redirect log.Printf output to this package, as well as log.SetFlags(0). Finally checks if FallbackWriter is a TTY. If so, changes FallbackFormatter to FallbackFormatterSimple.
Types ¶
type ContextLogger ¶ added in v1.4.1
ContextLogger is the interface used for values stored in ContextWithLogger. Typically a *Plog or other Logger value.
type ContextLoggerFunc ¶ added in v1.4.1
ContextLoggerFunc lets use use a function value as a ContextLogger.
func (ContextLoggerFunc) Log ¶ added in v1.4.1
func (f ContextLoggerFunc) Log(key string, value interface{}) error
Log calls f. It implements the ContextLogger interface.
type FallbackKey ¶ added in v1.1.0
FallbackKey used for key argument to the formatter. The slice passed to the functions has one element per nested context level, followed by the key passed to the log funtion.
type Fields ¶ added in v1.1.0
Fields is now just an alias for slog.KV. It's used to add key-value pairs to logs.
type Level ¶
type Level int
Level is a syslog like log level. The primary way to use it is via the predefined package Constants and the LogMsg functions. Level is also used as an argument for the LevelPrint and LevelPrintf functions on the Plog and Logger types.
Canonical level names.
func LogLevel ¶
LogLevel returns the Level mathcing lvl, if it's valid, otherwise returns def. Commonly used with the lower case codes, either shortened or full.
func (Level) Code ¶
Code returns the upper-case code for level, matching logs. Levels Emergency to Error are shortened, while Warning to Debug are full name upper-case.
func (Level) Ctx ¶ added in v1.4.1
func (l Level) Ctx(ctx context.Context) TypeLogger
Ctx returns a TypeLogger using the ContextLogger stored in ctx. If there's no ContextLogger stored, it returns a TypeLogger pointing to Default or the fallback logger. The returned TypeLogger will also pass the ctx parameter to slog.CtxKVsMap, applying any context kv filters. If the log level is disabled then a TypeLogger discarding logs is returned.
func (Level) CtxMsg ¶ added in v1.4.1
CtxMsg will call the package level CtxMsg if l is an enabled level. It will use l.Code() as the type key.
func (Level) Fatal ¶
func (l Level) Fatal(v ...interface{})
Fatal calls l.Write followed by os.Exit(1)
func (Level) LogDict ¶ added in v1.1.0
LogDict is a convience function that calls LogDict with l.Code() as key. This is deprecated in favor of LogMsg which enforces a human readable message. This function will be removed in version 2.0.
func (Level) LogMsg ¶ added in v1.2.0
LogMsg is a convience function that calls LogMsg with l.Code() as key. The msg parameter contains a human readable message, while the rest are passed to slog.KVsMap to convert to a dictionary. This is not a printf-like function, despite the signature.
func (Level) Lower ¶
Lower returns the lower-case code for level. Levels Emergency to Error are shortened, while Warning to Debug are full name lower-case.
func (Level) Msg ¶ added in v1.3.0
Msg is a convenience function that calls LogMsg with l.Code() as key and only a human readable message.
func (Level) Msgf ¶ added in v1.3.0
Msgf is a convenience message calling LogMsg with l.Code() as key and the printf formatted message as the msg parameter. a human readable message.
func (Level) Panic ¶ added in v1.1.0
func (l Level) Panic(v ...interface{})
Panic calls l.Write followed by panic.
func (Level) Print ¶
func (l Level) Print(v ...interface{})
Print calls l.Write via fmt.Fprint. Checks l against the SetupLevel first and thus is slightly more efficient than calling fmt.Fprint directly. While not deprecated it's recommended to use LogMsg instead for more structured logging.
func (Level) Printf ¶
Printf calls l.Write via fmt.Fprintf. Checks l against the SetupLevel first and thus is slightly more efficient than calling fmt.Fprintf directly. While not deprecated it's recommended to use LogMsg instead for more structured logging.
func (Level) With ¶ added in v1.3.0
func (l Level) With(kvs ...interface{}) TypeLogger
With creates a TypeLogger with the key-values. See the package level function for more information. TypeLogger is different from Logger in the key is fixed and not part of the function signatures. kvs is parsed via slog.KVsMap.
type Logger ¶ added in v1.1.0
type Logger interface { With(kvs ...interface{}) Logger Ctx(ctx context.Context) Logger Type(key string) TypeLogger Log(key string, value interface{}) error LogDict(key string, kvs ...interface{}) error LogMsg(key string, msg string, kvs ...interface{}) CtxMsg(ctx context.Context, key string, msg string, kvs ...interface{}) LevelPrint(lvl Level, value ...interface{}) LevelPrintf(lvl Level, format string, value ...interface{}) Emergency(value ...interface{}) Emergencyf(format string, value ...interface{}) Alert(value ...interface{}) Alertf(format string, value ...interface{}) Critical(value ...interface{}) Criticalf(format string, value ...interface{}) Error(value ...interface{}) Errorf(format string, value ...interface{}) Warning(value ...interface{}) Warningf(format string, value ...interface{}) Notice(value ...interface{}) Noticef(format string, value ...interface{}) Info(value ...interface{}) Infof(format string, value ...interface{}) Debug(value ...interface{}) Debugf(format string, value ...interface{}) }
Logger is an interface with functions for level based logging. Plog context conform to this interface, as well as the WithFields return value. See the Plog type for documentation about the functions in this interface.
Methods might be added to this interface without increasing the major version.
func Ctx ¶ added in v1.4.1
Ctx returns a Logger using the ContextLogger stored in ctx. If there's no ContextLogger stored, it returns a Logger pointing to Default or the fallback logger. The returned Logger will also pass the ctx parameter to slog.CtxKVsMap, applying any context kv filters.
func With ¶ added in v1.3.0
func With(kvs ...interface{}) Logger
With creates a Logger in a similar way as WithFields, but uses the alternating keys and values given by kvs instead. The full details of how kvs is parsed is described in the slog.KVsMap function, but the basic version is to alternate keys and values.
func WithFields ¶ added in v1.1.0
WithFields can be used to create Loggers with preset fields. If the Log function on the returned interface is used with a map[string]interface{} value then the fields are merged with that map, otherwise the logged value is put in the "msg" key in a dictionary with the fields. LogDict and LogMsg are wrappers for Log with a map[string]interface{}. The latter adds the msg argument with the "msg" key.
This function logs to Default if non-nil otherwise to FallbackWriter.
WithFields(...).Info(x) is equal to Info.LogMsg(x, ...) WithFields(...).Type("INFO").Msg(x) is also the same.
The fields map is stored by reference so don't modify it after this call. Each call to With and WithFields creates a new logger so don't call it more than necessary.
type Plog ¶
type Plog struct {
// contains filtered or unexported fields
}
Plog is a context object opened in the log server. The server will keep track of it and all its contents until it's closed (and beyond, in case of state contexts). If a program crashes/exits without closing the context the server will detect this and log an "@interrupted" key for easier debugging. Can also be used without the log server in which case it logs to the fallback writer.
var Default *Plog
Default plog context, opened by Setup.
func CtxPlog ¶ added in v1.4.1
CtxPlog returns the plog stored with ContextWithLogger, if the latest value stored was a *Plog, otherwise it returns Default.
func IfEnabled ¶
IfEnabled returns the default context if the level is enabled by the threshold given to setup, otherwise nil. It's safe to call functions on nil contexts.
func NewPlogCount ¶
NewPlogCount opens a new root count plog context. When integers are logged in this context, it's applied as a delta to the state. When the context is closed the integer values added are removed. Can be used to keep statistics such as number of open fds and aggregate them between multiple processes with the same name.
func NewPlogLog ¶
NewPlogLog opens a new root logging plog context. If you called Setup, then you should probably use Default instead of this.
func NewPlogState ¶
NewPlogState opens a new root state plog context. State is kept in plogd and only logged with a "state" key once all state contexts for the appname are closed. You can also query it over HTTP from plogd.
func NewTestLogContext ¶ added in v1.1.0
func NewTestLogContext(ctx context.Context, key ...string) (*Plog, <-chan TestMessage)
NewTestLogContext creates a custom root log context connected to the channel, for testing. Only messages are sent on the channel, not open or close. Close the context and then wait for the channel to close for proper cleanup.
func (*Plog) Alert ¶ added in v1.1.0
func (plog *Plog) Alert(value ...interface{})
Alert is shorthand for plog.LevelPrint(Alert, value).
func (*Plog) Close ¶
Close the context, marking it as properly closed in the server. For subcontext, this is what triggers it being sent to the parent context.
func (*Plog) Critical ¶ added in v1.1.0
func (plog *Plog) Critical(value ...interface{})
Critical is shorthand for plog.LevelPrint(Critical, value).
func (*Plog) Criticalf ¶ added in v1.1.0
Criticalf is shorthand for plog.LevelPrintf(Critical, value).
func (*Plog) Ctx ¶ added in v1.4.1
Ctx returns a Logger that will pass the ctx parameter to slog.CtxKVsMap.
func (*Plog) CtxMsg ¶ added in v1.4.1
CtxMsg logs a human readable message with a JSON dictionary from the variadic arguments, which are parsed with slog.CtxKVsMap. This function does not return errors. If json encoding fails it converts to a string and tries again, adding a "log-error" key.
func (*Plog) Debug ¶ added in v1.1.0
func (plog *Plog) Debug(value ...interface{})
Debug is shorthand for plog.LevelPrint(Debug, value).
func (*Plog) Emergency ¶ added in v1.1.0
func (plog *Plog) Emergency(value ...interface{})
Emergency is shorthand for plog.LevelPrint(Emergency, value).
func (*Plog) Emergencyf ¶ added in v1.1.0
Emergencyf is shorthand for plog.LevelPrintf(Emergency, value).
func (*Plog) Error ¶ added in v1.1.0
func (plog *Plog) Error(value ...interface{})
Error is shorthand for plog.LevelPrint(Error, value).
func (*Plog) Fatal ¶ added in v1.1.0
func (plog *Plog) Fatal(value ...interface{})
Fatal logs value with Critical level, then calls os.Exit(1).
func (*Plog) Fatalf ¶ added in v1.1.0
Fatalf logs arguments with Critical level, then calls os.Exit(1).
func (*Plog) Info ¶ added in v1.1.0
func (plog *Plog) Info(value ...interface{})
Info is shorthand for plog.LevelPrint(Info, value).
func (*Plog) LevelPrint ¶ added in v1.1.0
LevelPrint logs with a standard level key. Only logs if level is above the threshold given to Setup (defaults to Info). The value is formatted via fmt.Sprint. For JSON formatting use LogMsg.
func (*Plog) LevelPrintf ¶ added in v1.1.0
LevelPrintf logs with a standard level key. Only logs if level is above the threshold given to Setup (defaults to Info). The value is formatted via fmt.Sprintf. For JSON formatting use LogMsg.
func (*Plog) Log ¶
Log encodes value as JSON and logs it. Might return errors from json.Marshal, but that should only happen in very rare cases. For strings, ints and other basic types you can ignore the return value. This is a low-level function, consider using LogMsg instead.
func (*Plog) LogAsString ¶
LogAsString logs value as if it was a string.
func (*Plog) LogDict ¶
LogDict logs a JSON dictionary from the variadic arguments, which are parsed with slog.KVsMap. Note that the first argument is not part of the dictionary, it's the message key. Deprecated in favor of LogMsg. Might return errors from json.Marshal.
func (*Plog) LogJSON ¶
LogJSON logs raw JSON encoded data in value. You must make sure the JSON is valid, or the context will be aborted.
func (*Plog) LogMsg ¶ added in v1.2.0
LogMsg logs a human readable message with a JSON dictionary from the variadic arguments, which are parsed with slog.KVsMap. This function does not return errors. If json encoding fails it converts to a string and tries again, adding a "log-error" key.
func (*Plog) Notice ¶ added in v1.1.0
func (plog *Plog) Notice(value ...interface{})
Notice is shorthand for plog.LevelPrint(Notice, value).
func (*Plog) OpenDict ¶
OpenDict opens a sub-context dictionary. Once this and any sub-contexts to it are closed, a dictionary object will be logged in the parent plog.
func (*Plog) OpenList ¶
OpenList opens a sub-context list. Once this and any sub-contexts to it are closed, a list will be logged in the parent plog.
func (*Plog) OpenListOfDicts ¶ added in v1.4.1
OpenListOfDicts opens a sub-context list. Once this and any sub-contexts to it are closed, a list will be logged in the parent plog, where each element is a dictionary with a single element, the key value pair given to Log*. This context type is useful for putting logs in a sub-key but does drop the timestamps of the individual messages.
func (*Plog) Panic ¶ added in v1.1.0
func (plog *Plog) Panic(value ...interface{})
Panic logs value with Critical level, then calls panic.
func (*Plog) Type ¶ added in v1.3.0
func (plog *Plog) Type(key string) TypeLogger
Type create a TypeLogger for this context and key. Fields can then be added by the With function. See Level.With for more information.
func (*Plog) Warning ¶ added in v1.1.0
func (plog *Plog) Warning(value ...interface{})
Warning is shorthand for plog.LevelPrint(Warning, value).
func (*Plog) With ¶ added in v1.3.0
With creates a Logger with the key-values. See the package level function for more information. kvs is parsed via slog.KVsMap. Unlike the package level function, this one does not use the FallbackWriter but simply discards instead if plog is nil.
func (*Plog) WithFields ¶ added in v1.1.0
WithFields on a specific plog context. See top level WithFields for more info. Unlike the package level function, this one does not use the FallbackWriter but simply discards instead if plog is nil.
type TestMessage ¶ added in v1.1.0
TestMessage is used for messages sent to the channel created by NewTestLogContext. Value will be json encoded data.
type TypeLogger ¶ added in v1.3.0
type TypeLogger interface { With(kvs ...interface{}) TypeLogger Ctx(ctx context.Context) TypeLogger Msg(msg string) Msgf(format string, value ...interface{}) LogMsg(msg string, kvs ...interface{}) CtxMsg(ctx context.Context, msg string, kvs ...interface{}) Print(value ...interface{}) Printf(format string, value ...interface{}) Fatal(value ...interface{}) Fatalf(format string, value ...interface{}) Panic(value ...interface{}) Panicf(format string, value ...interface{}) }
TypeLogger can be used to log with preset fields. Additional Fields can also be added via the With method or passed together with a message to LogMsg.
The Level type in this package implements this interface. See that type for more documenation about the functions here.
Methods might be added to this interface without increasing the major version.