{"modulePath":"github.com/zencoder/kit","version":"v0.4.0","isLatest":true,"isStandardLibrary":false,"goos":"all","goarch":"all","docs":"# package log\n\nPackage log provides a structured logger.\n\nStructured logging produces logs easily consumed later by humans or machines. Humans might be interested in debugging errors, or tracing specific requests. Machines might be interested in counting interesting events, or aggregating information for off-line processing. In both cases, it is important that the log messages are structured and actionable. Package log is designed to encourage both of these best practices.\n\n### Basic Usage {#hdr-Basic_Usage}\n\nThe fundamental interface is Logger. Loggers create log events from key/value data. The Logger interface has a single method, Log, which accepts a sequence of alternating key/value pairs, which this package names keyvals.\n\n\ttype Logger interface {\n\t    Log(keyvals ...interface{}) error\n\t}\n\nHere is an example of a function using a Logger to create log events.\n\n\tfunc RunTask(task Task, logger log.Logger) string {\n\t    logger.Log(\"taskID\", task.ID, \"event\", \"starting task\")\n\t    ...\n\t    logger.Log(\"taskID\", task.ID, \"event\", \"task complete\")\n\t}\n\nThe keys in the above example are \"taskID\" and \"event\". The values are task.ID, \"starting task\", and \"task complete\". Every key is followed immediately by its value.\n\nKeys are usually plain strings. Values may be any type that has a sensible encoding in the chosen log format. With structured logging it is a good idea to log simple values without formatting them. This practice allows the chosen logger to encode values in the most appropriate way.\n\n### Contextual Loggers {#hdr-Contextual_Loggers}\n\nA contextual logger stores keyvals that it includes in all log events. Building appropriate contextual loggers reduces repetition and aids consistency in the resulting log output. With and WithPrefix add context to a logger. We can use With to improve the RunTask example.\n\n\tfunc RunTask(task Task, logger log.Logger) string {\n\t    logger = log.With(logger, \"taskID\", task.ID)\n\t    logger.Log(\"event\", \"starting task\")\n\t    ...\n\t    taskHelper(task.Cmd, logger)\n\t    ...\n\t    logger.Log(\"event\", \"task complete\")\n\t}\n\nThe improved version emits the same log events as the original for the first and last calls to Log. Passing the contextual logger to taskHelper enables each log event created by taskHelper to include the task.ID even though taskHelper does not have access to that value. Using contextual loggers this way simplifies producing log output that enables tracing the life cycle of individual tasks. (See the Contextual example for the full code of the above snippet.)\n\n### Dynamic Contextual Values {#hdr-Dynamic_Contextual_Values}\n\nA Valuer function stored in a contextual logger generates a new value each time an event is logged. The Valuer example demonstrates how this feature works.\n\nValuers provide the basis for consistently logging timestamps and source code location. The log package defines several valuers for that purpose. See Timestamp, DefaultTimestamp, DefaultTimestampUTC, Caller, and DefaultCaller. A common logger initialization sequence that ensures all log entries contain a timestamp and source location looks like this:\n\n\tlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))\n\tlogger = log.With(logger, \"ts\", log.DefaultTimestampUTC, \"caller\", log.DefaultCaller)\n\n### Concurrent Safety {#hdr-Concurrent_Safety}\n\nApplications with multiple goroutines want each log event written to the same logger to remain separate from other log events. Package log provides two simple solutions for concurrent safe logging.\n\nNewSyncWriter wraps an io.Writer and serializes each call to its Write method. Using a SyncWriter has the benefit that the smallest practical portion of the logging logic is performed within a mutex, but it requires the formatting Logger to make only one call to Write per log event.\n\nNewSyncLogger wraps any Logger and serializes each call to its Log method. Using a SyncLogger has the benefit that it guarantees each log event is handled atomically within the wrapped logger, but it typically serializes both the formatting and output logic. Use a SyncLogger if the formatting logger may perform multiple writes per log event.\n\n### Error Handling {#hdr-Error_Handling}\n\nThis package relies on the practice of wrapping or decorating loggers with other loggers to provide composable pieces of functionality. It also means that Logger.Log must return an error because some implementations—especially those that output log data to an io.Writer—may encounter errors that cannot be handled locally. This in turn means that Loggers that wrap other loggers should return errors from the wrapped logger up the stack.\n\nFortunately, the decorator pattern also provides a way to avoid the necessity to check for errors every time an application calls Logger.Log. An application required to panic whenever its Logger encounters an error could initialize its logger as follows.\n\n\tfmtlogger := log.NewLogfmtLogger(log.NewSyncWriter(os.Stdout))\n\tlogger := log.LoggerFunc(func(keyvals ...interface{}) error {\n\t    if err := fmtlogger.Log(keyvals...); err != nil {\n\t        panic(err)\n\t    }\n\t    return nil\n\t})\n\n## Variables\n\n```go\nvar (\n\t// DefaultTimestamp is a Valuer that returns the current wallclock time,\n\t// respecting time zones, when bound.\n\tDefaultTimestamp = Valuer(func() interface{} {\n\t\treturn time.Now().Format(time.RFC3339Nano)\n\t})\n\n\t// DefaultTimestampUTC is a Valuer that returns the current time in UTC\n\t// when bound.\n\tDefaultTimestampUTC = Valuer(func() interface{} {\n\t\treturn time.Now().UTC().Format(time.RFC3339Nano)\n\t})\n\n\t// DefaultCaller is a Valuer that returns the file and line where the Log\n\t// method was invoked. It can only be used with log.With.\n\tDefaultCaller = Caller(3)\n)\n```\n\n```go\nvar ErrMissingValue = errors.New(\"(MISSING)\")\n```\nErrMissingValue is appended to keyvals slices with odd length to substitute the missing value.\n\n## Functions\n\n```go\nfunc NewStdlibAdapter(logger Logger, options ...StdlibAdapterOption) io.Writer\n```\nNewStdlibAdapter returns a new StdlibAdapter wrapper around the passed logger. It's designed to be passed to log.SetOutput.\n\n## Types\n\n```go\ntype Logger interface {\n\tLog(keyvals ...interface{}) error\n}\n```\nLogger is the fundamental interface for all log operations. Log creates a log event from keyvals, a variadic sequence of alternating keys and values. Implementations must be safe for concurrent use by multiple goroutines. In particular, any implementation of Logger that appends to keyvals or modifies or retains any of its elements must make a copy first.\n\n```go\nfunc NewJSONLogger(w io.Writer) Logger\n```\nNewJSONLogger returns a Logger that encodes keyvals to the Writer as a single JSON object. Each log event produces no more than one call to w.Write. The passed Writer must be safe for concurrent use by multiple goroutines if the returned Logger will be used concurrently.\n\n```go\nfunc NewLogfmtLogger(w io.Writer) Logger\n```\nNewLogfmtLogger returns a logger that encodes keyvals to the Writer in logfmt format. Each log event produces no more than one call to w.Write. The passed Writer must be safe for concurrent use by multiple goroutines if the returned Logger will be used concurrently.\n\n```go\nfunc NewNopLogger() Logger\n```\nNewNopLogger returns a logger that doesn't do anything.\n\n```go\nfunc NewSyncLogger(logger Logger) Logger\n```\nNewSyncLogger returns a logger that synchronizes concurrent use of the wrapped logger. When multiple goroutines use the SyncLogger concurrently only one goroutine will be allowed to log to the wrapped logger at a time. The other goroutines will block until the logger is available.\n\n```go\nfunc With(logger Logger, keyvals ...interface{}) Logger\n```\nWith returns a new contextual logger with keyvals prepended to those passed to calls to Log. If logger is also a contextual logger created by With or WithPrefix, keyvals is appended to the existing context.\n\nThe returned Logger replaces all value elements (odd indexes) containing a Valuer with their generated value for each call to its Log method.\n\n```go\nfunc WithPrefix(logger Logger, keyvals ...interface{}) Logger\n```\nWithPrefix returns a new contextual logger with keyvals prepended to those passed to calls to Log. If logger is also a contextual logger created by With or WithPrefix, keyvals is prepended to the existing context.\n\nThe returned Logger replaces all value elements (odd indexes) containing a Valuer with their generated value for each call to its Log method.\n\n```go\ntype LoggerFunc func(...interface{}) error\n```\nLoggerFunc is an adapter to allow use of ordinary functions as Loggers. If f is a function with the appropriate signature, LoggerFunc(f) is a Logger object that calls f.\n\n```go\nfunc (f LoggerFunc) Log(keyvals ...interface{}) error\n```\nLog implements Logger by calling f(keyvals...).\n\n```go\ntype StdlibAdapter struct {\n\tLogger\n\t// contains filtered or unexported fields\n}\n```\nStdlibAdapter wraps a Logger and allows it to be passed to the stdlib logger's SetOutput. It will extract date/timestamps, filenames, and messages, and place them under relevant keys.\n\n```go\nfunc (a StdlibAdapter) Write(p []byte) (int, error)\n```\n\n```go\ntype StdlibAdapterOption func(*StdlibAdapter)\n```\nStdlibAdapterOption sets a parameter for the StdlibAdapter.\n\n```go\nfunc FileKey(key string) StdlibAdapterOption\n```\nFileKey sets the key for the file and line field. By default, it's \"caller\".\n\n```go\nfunc MessageKey(key string) StdlibAdapterOption\n```\nMessageKey sets the key for the actual log message. By default, it's \"msg\".\n\n```go\nfunc TimestampKey(key string) StdlibAdapterOption\n```\nTimestampKey sets the key for the timestamp field. By default, it's \"ts\".\n\n```go\ntype StdlibWriter struct{}\n```\nStdlibWriter implements io.Writer by invoking the stdlib log.Print. It's designed to be passed to a Go kit logger as the writer, for cases where it's necessary to redirect all Go kit log output to the stdlib logger.\n\nIf you have any choice in the matter, you shouldn't use this. Prefer to redirect the stdlib log to the Go kit logger via NewStdlibAdapter.\n\n```go\nfunc (w StdlibWriter) Write(p []byte) (int, error)\n```\nWrite implements io.Writer.\n\n```go\ntype SwapLogger struct {\n\t// contains filtered or unexported fields\n}\n```\nSwapLogger wraps another logger that may be safely replaced while other goroutines use the SwapLogger concurrently. The zero value for a SwapLogger will discard all log events without error.\n\nSwapLogger serves well as a package global logger that can be changed by importers.\n\n```go\nfunc (l *SwapLogger) Log(keyvals ...interface{}) error\n```\nLog implements the Logger interface by forwarding keyvals to the currently wrapped logger. It does not log anything if the wrapped logger is nil.\n\n```go\nfunc (l *SwapLogger) Swap(logger Logger)\n```\nSwap replaces the currently wrapped logger with logger. Swap may be called concurrently with calls to Log from other goroutines.\n\n```go\ntype SyncWriter struct {\n\t// contains filtered or unexported fields\n}\n```\nSyncWriter synchronizes concurrent writes to an io.Writer.\n\n```go\nfunc NewSyncWriter(w io.Writer) *SyncWriter\n```\nNewSyncWriter returns a new SyncWriter. The returned writer is safe for concurrent use by multiple goroutines.\n\n```go\nfunc (w *SyncWriter) Write(p []byte) (n int, err error)\n```\nWrite writes p to the underlying io.Writer. If another write is already in progress, the calling goroutine blocks until the SyncWriter is available.\n\n```go\ntype Valuer func() interface{}\n```\nA Valuer generates a log value. When passed to With or WithPrefix in a value element (odd indexes), it represents a dynamic value which is re- evaluated with each log event.\n\n```go\nfunc Caller(depth int) Valuer\n```\nCaller returns a Valuer that returns a file and line from a specified depth in the callstack. Users will probably want to use DefaultCaller.\n\n```go\nfunc Timestamp(t func() time.Time) Valuer\n```\nTimestamp returns a Valuer that invokes the underlying function when bound, returning a time.Time. Users will probably want to use DefaultTimestamp or DefaultTimestampUTC.\n\n","path":"github.com/zencoder/kit/log","name":"log","synopsis":"Package log provides a structured logger.","isRedistributable":true}
