hclog

package module
v1.6.3 Latest Latest
Warning

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

Go to latest
Published: Apr 1, 2024 License: MIT Imports: 23 Imported by: 7,533

README

go-hclog

Go Documentation

go-hclog is a package for Go that provides a simple key/value logging interface for use in development and production environments.

It provides logging levels that provide decreased output based upon the desired amount of output, unlike the standard library log package.

It provides Printf style logging of values via hclog.Fmt().

It provides a human readable output mode for use in development as well as JSON output mode for production.

Stability Note

This library has reached 1.0 stability. Its API can be considered solidified and promised through future versions.

Installation and Docs

Install using go get github.com/hashicorp/go-hclog.

Full documentation is available at http://godoc.org/github.com/hashicorp/go-hclog

Usage

Use the global logger
hclog.Default().Info("hello world")
2017-07-05T16:15:55.167-0700 [INFO ] hello world

(Note timestamps are removed in future examples for brevity.)

Create a new logger
appLogger := hclog.New(&hclog.LoggerOptions{
	Name:  "my-app",
	Level: hclog.LevelFromString("DEBUG"),
})
Emit an Info level message with 2 key/value pairs
input := "5.5"
_, err := strconv.ParseInt(input, 10, 32)
if err != nil {
	appLogger.Info("Invalid input for ParseInt", "input", input, "error", err)
}
... [INFO ] my-app: Invalid input for ParseInt: input=5.5 error="strconv.ParseInt: parsing "5.5": invalid syntax"
Create a new Logger for a major subsystem
subsystemLogger := appLogger.Named("transport")
subsystemLogger.Info("we are transporting something")
... [INFO ] my-app.transport: we are transporting something

Notice that logs emitted by subsystemLogger contain my-app.transport, reflecting both the application and subsystem names.

Create a new Logger with fixed key/value pairs

Using With() will include a specific key-value pair in all messages emitted by that logger.

requestID := "5fb446b6-6eba-821d-df1b-cd7501b6a363"
requestLogger := subsystemLogger.With("request", requestID)
requestLogger.Info("we are transporting a request")
... [INFO ] my-app.transport: we are transporting a request: request=5fb446b6-6eba-821d-df1b-cd7501b6a363

This allows sub Loggers to be context specific without having to thread that into all the callers.

Using hclog.Fmt()
totalBandwidth := 200
appLogger.Info("total bandwidth exceeded", "bandwidth", hclog.Fmt("%d GB/s", totalBandwidth))
... [INFO ] my-app: total bandwidth exceeded: bandwidth="200 GB/s"
Use this with code that uses the standard library logger

If you want to use the standard library's log.Logger interface you can wrap hclog.Logger by calling the StandardLogger() method. This allows you to use it with the familiar Println(), Printf(), etc. For example:

stdLogger := appLogger.StandardLogger(&hclog.StandardLoggerOptions{
	InferLevels: true,
})
// Printf() is provided by stdlib log.Logger interface, not hclog.Logger
stdLogger.Printf("[DEBUG] %+v", stdLogger)
... [DEBUG] my-app: &{mu:{state:0 sema:0} prefix: flag:0 out:0xc42000a0a0 buf:[]}

Alternatively, you may configure the system-wide logger:

// log the standard logger from 'import "log"'
log.SetOutput(appLogger.StandardWriter(&hclog.StandardLoggerOptions{InferLevels: true}))
log.SetPrefix("")
log.SetFlags(0)

log.Printf("[DEBUG] %d", 42)
... [DEBUG] my-app: 42

Notice that if appLogger is initialized with the INFO log level, and you specify InferLevels: true, you will not see any output here. You must change appLogger to DEBUG to see output. See the docs for more information.

If the log lines start with a timestamp you can use the InferLevelsWithTimestamp option to try and ignore them. Please note that in order for InferLevelsWithTimestamp to be relevant, InferLevels must be set to true.

Documentation

Index

Constants

View Source
const MissingKey = "EXTRA_VALUE_AT_END"
View Source
const TimeFormat = "2006-01-02T15:04:05.000Z0700"

TimeFormat is the time format to use for plain (non-JSON) output. This is a version of RFC3339 that contains millisecond precision.

View Source
const TimeFormatJSON = "2006-01-02T15:04:05.000000Z07:00"

TimeFormatJSON is the time format to use for JSON output. This is a version of RFC3339 that contains microsecond precision.

Variables

View Source
var (
	// DefaultOutput is used as the default log output.
	DefaultOutput io.Writer = os.Stderr

	// DefaultLevel is used as the default log level.
	DefaultLevel = Info
)
View Source
var (

	// DefaultOptions is used to create the Default logger. These are read
	// only when the Default logger is created, so set them as soon as the
	// process starts.
	DefaultOptions = &LoggerOptions{
		Level:  DefaultLevel,
		Output: DefaultOutput,
		TimeFn: time.Now,
	}
)

Functions

func WithContext added in v0.9.1

func WithContext(ctx context.Context, logger Logger, args ...interface{}) context.Context

WithContext inserts a logger into the context and is retrievable with FromContext. The optional args can be set with the same syntax as Logger.With to set fields on the inserted logger. This will not modify the logger argument in-place.

Types

type Binary added in v0.14.0

type Binary int

A simple shortcut to format numbers in binary when displayed with the normal text output. For example: L.Info("bits", Binary(17))

type CapturedStacktrace

type CapturedStacktrace string

CapturedStacktrace represents a stacktrace captured by a previous call to log.Stacktrace. If passed to a logging function, the stacktrace will be appended.

func Stacktrace

func Stacktrace() CapturedStacktrace

Stacktrace captures a stacktrace of the current goroutine and returns it to be passed to a logging function.

type ColorOption added in v0.10.0

type ColorOption uint8

ColorOption expresses how the output should be colored, if at all.

const (
	// ColorOff is the default coloration, and does not
	// inject color codes into the io.Writer.
	ColorOff ColorOption = iota
	// AutoColor checks if the io.Writer is a tty,
	// and if so enables coloring.
	AutoColor
	// ForceColor will enable coloring, regardless of whether
	// the io.Writer is a tty or not.
	ForceColor
)

type ExcludeByMessage added in v0.13.0

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

ExcludeByMessage provides a simple way to build a list of log messages that can be queried and matched. This is meant to be used with the Exclude option on Options to suppress log messages. This does not hold any mutexs within itself, so normal usage would be to Add entries at setup and none after Exclude is going to be called. Exclude is called with a mutex held within the Logger, so that doesn't need to use a mutex. Example usage:

f := new(ExcludeByMessage)
f.Add("Noisy log message text")
appLogger.Exclude = f.Exclude

func (*ExcludeByMessage) Add added in v0.13.0

func (f *ExcludeByMessage) Add(msg string)

Add a message to be filtered. Do not call this after Exclude is to be called due to concurrency issues.

func (*ExcludeByMessage) Exclude added in v0.13.0

func (f *ExcludeByMessage) Exclude(level Level, msg string, args ...interface{}) bool

Return true if the given message should be included

type ExcludeByPrefix added in v0.13.0

type ExcludeByPrefix string

ExcludeByPrefix is a simple type to match a message string that has a common prefix.

func (ExcludeByPrefix) Exclude added in v0.13.0

func (p ExcludeByPrefix) Exclude(level Level, msg string, args ...interface{}) bool

Matches an message that starts with the prefix.

type ExcludeByRegexp added in v0.13.0

type ExcludeByRegexp struct {
	Regexp *regexp.Regexp
}

ExcludeByRegexp takes a regexp and uses it to match a log message string. If it matches the log entry is excluded.

func (ExcludeByRegexp) Exclude added in v0.13.0

func (e ExcludeByRegexp) Exclude(level Level, msg string, args ...interface{}) bool

Exclude the log message if the message string matches the regexp

type ExcludeFuncs added in v0.13.0

type ExcludeFuncs []func(level Level, msg string, args ...interface{}) bool

ExcludeFuncs is a slice of functions that will called to see if a log entry should be filtered or not. It stops calling functions once at least one returns true.

func (ExcludeFuncs) Exclude added in v0.13.0

func (ff ExcludeFuncs) Exclude(level Level, msg string, args ...interface{}) bool

Calls each function until one of them returns true

type Flushable added in v0.12.0

type Flushable interface {
	Flush() error
}

Flushable represents a method for flushing an output buffer. It can be used if Resetting the log to use a new output, in order to flush the writes to the existing output beforehand.

type Format

type Format []interface{}

Format is a simple convenience type for when formatting is required. When processing a value of this type, the logger automatically treats the first argument as a Printf formatting string and passes the rest as the values to be formatted. For example: L.Info(Fmt{"%d beans/day", beans}).

func Fmt

func Fmt(str string, args ...interface{}) Format

Fmt returns a Format type. This is a convenience function for creating a Format type.

type Hex added in v0.14.0

type Hex int

A simple shortcut to format numbers in hex when displayed with the normal text output. For example: L.Info("header value", Hex(17))

type InterceptLogger added in v0.10.0

type InterceptLogger interface {
	// Logger is the root logger for an InterceptLogger
	Logger

	// RegisterSink adds a SinkAdapter to the InterceptLogger
	RegisterSink(sink SinkAdapter)

	// DeregisterSink removes a SinkAdapter from the InterceptLogger
	DeregisterSink(sink SinkAdapter)

	// Create a interceptlogger that will prepend the name string on the front of all messages.
	// If the logger already has a name, the new value will be appended to the current
	// name. That way, a major subsystem can use this to decorate all it's own logs
	// without losing context.
	NamedIntercept(name string) InterceptLogger

	// Create a interceptlogger that will prepend the name string on the front of all messages.
	// This sets the name of the logger to the value directly, unlike Named which honor
	// the current name as well.
	ResetNamedIntercept(name string) InterceptLogger

	// Deprecated: use StandardLogger
	StandardLoggerIntercept(opts *StandardLoggerOptions) *log.Logger

	// Deprecated: use StandardWriter
	StandardWriterIntercept(opts *StandardLoggerOptions) io.Writer
}

InterceptLogger describes the interface for using a logger that can register different output sinks. This is useful for sending lower level log messages to a different output while keeping the root logger at a higher one.

func NewInterceptLogger added in v0.10.0

func NewInterceptLogger(opts *LoggerOptions) InterceptLogger

type Level

type Level int32

Level represents a log level.

const (
	// NoLevel is a special level used to indicate that no level has been
	// set and allow for a default to be used.
	NoLevel Level = 0

	// Trace is the most verbose level. Intended to be used for the tracing
	// of actions in code, such as function enters/exits, etc.
	Trace Level = 1

	// Debug information for programmer low-level analysis.
	Debug Level = 2

	// Info information about steady state operations.
	Info Level = 3

	// Warn information about rare but handled events.
	Warn Level = 4

	// Error information about unrecoverable events.
	Error Level = 5

	// Off disables all logging output.
	Off Level = 6
)

func LevelFromString

func LevelFromString(levelStr string) Level

LevelFromString returns a Level type for the named log level, or "NoLevel" if the level string is invalid. This facilitates setting the log level via config or environment variable by name in a predictable way.

func (Level) String added in v0.12.1

func (l Level) String() string

type LevelWriter added in v0.8.0

type LevelWriter interface {
	LevelWrite(level Level, p []byte) (n int, err error)
}

LevelWriter is the interface that wraps the LevelWrite method.

type LeveledWriter added in v0.8.0

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

LeveledWriter writes all log messages to the standard writer, except for log levels that are defined in the overrides map.

func NewLeveledWriter added in v0.8.0

func NewLeveledWriter(standard io.Writer, overrides map[Level]io.Writer) *LeveledWriter

NewLeveledWriter returns an initialized LeveledWriter.

standard will be used as the default writer for all log levels, except for log levels that are defined in the overrides map.

func (*LeveledWriter) LevelWrite added in v0.8.0

func (lw *LeveledWriter) LevelWrite(level Level, p []byte) (int, error)

LevelWrite implements LevelWriter.

func (*LeveledWriter) Write added in v0.8.0

func (lw *LeveledWriter) Write(p []byte) (int, error)

Write implements io.Writer.

type Locker added in v0.12.2

type Locker interface {
	// Lock is called when the output is going to be changed or written to
	Lock()

	// Unlock is called when the operation that called Lock() completes
	Unlock()
}

Locker is used for locking output. If not set when creating a logger, a sync.Mutex will be used internally.

type Logger

type Logger interface {
	// Args are alternating key, val pairs
	// keys must be strings
	// vals can be any type, but display is implementation specific
	// Emit a message and key/value pairs at a provided log level
	Log(level Level, msg string, args ...interface{})

	// Emit a message and key/value pairs at the TRACE level
	Trace(msg string, args ...interface{})

	// Emit a message and key/value pairs at the DEBUG level
	Debug(msg string, args ...interface{})

	// Emit a message and key/value pairs at the INFO level
	Info(msg string, args ...interface{})

	// Emit a message and key/value pairs at the WARN level
	Warn(msg string, args ...interface{})

	// Emit a message and key/value pairs at the ERROR level
	Error(msg string, args ...interface{})

	// Indicate if TRACE logs would be emitted. This and the other Is* guards
	// are used to elide expensive logging code based on the current level.
	IsTrace() bool

	// Indicate if DEBUG logs would be emitted. This and the other Is* guards
	IsDebug() bool

	// Indicate if INFO logs would be emitted. This and the other Is* guards
	IsInfo() bool

	// Indicate if WARN logs would be emitted. This and the other Is* guards
	IsWarn() bool

	// Indicate if ERROR logs would be emitted. This and the other Is* guards
	IsError() bool

	// ImpliedArgs returns With key/value pairs
	ImpliedArgs() []interface{}

	// Creates a sublogger that will always have the given key/value pairs
	With(args ...interface{}) Logger

	// Returns the Name of the logger
	Name() string

	// Create a logger that will prepend the name string on the front of all messages.
	// If the logger already has a name, the new value will be appended to the current
	// name. That way, a major subsystem can use this to decorate all it's own logs
	// without losing context.
	Named(name string) Logger

	// Create a logger that will prepend the name string on the front of all messages.
	// This sets the name of the logger to the value directly, unlike Named which honor
	// the current name as well.
	ResetNamed(name string) Logger

	// Updates the level. This should affect all related loggers as well,
	// unless they were created with IndependentLevels. If an
	// implementation cannot update the level on the fly, it should no-op.
	SetLevel(level Level)

	// Returns the current level
	GetLevel() Level

	// Return a value that conforms to the stdlib log.Logger interface
	StandardLogger(opts *StandardLoggerOptions) *log.Logger

	// Return a value that conforms to io.Writer, which can be passed into log.SetOutput()
	StandardWriter(opts *StandardLoggerOptions) io.Writer
}

Logger describes the interface that must be implemented by all loggers.

func Default

func Default() Logger

Default returns a globally held logger. This can be a good starting place, and then you can use .With() and .Named() to create sub-loggers to be used in more specific contexts. The value of the Default logger can be set via SetDefault() or by changing the options in DefaultOptions.

This method is goroutine safe, returning a global from memory, but care should be used if SetDefault() is called it random times in the program as that may result in race conditions and an unexpected Logger being returned.

func FromContext added in v0.9.1

func FromContext(ctx context.Context) Logger

FromContext returns a logger from the context. This will return L() (the default logger) if no logger is found in the context. Therefore, this will never return a nil value.

func FromStandardLogger added in v0.14.0

func FromStandardLogger(l *log.Logger, opts *LoggerOptions) Logger

Takes a standard library logger and returns a Logger that will write to it

func L

func L() Logger

L is a short alias for Default().

func New

func New(opts *LoggerOptions) Logger

New returns a configured logger.

func NewNullLogger

func NewNullLogger() Logger

NewNullLogger instantiates a Logger for which all calls will succeed without doing anything. Useful for testing purposes.

func SetDefault added in v0.9.2

func SetDefault(log Logger) Logger

SetDefault changes the logger to be returned by Default()and L() to the one given. This allows packages to use the default logger and have higher level packages change it to match the execution environment. It returns any old default if there is one.

NOTE: This is expected to be called early in the program to setup a default logger. As such, it does not attempt to make itself not racy with regard to the value of the default logger. Ergo if it is called in goroutines, you may experience race conditions with other goroutines retrieving the default logger. Basically, don't do that.

type LoggerOptions

type LoggerOptions struct {
	// Name of the subsystem to prefix logs with
	Name string

	// The threshold for the logger. Anything less severe is suppressed
	Level Level

	// Where to write the logs to. Defaults to os.Stderr if nil
	Output io.Writer

	// An optional Locker in case Output is shared. This can be a sync.Mutex or
	// a NoopLocker if the caller wants control over output, e.g. for batching
	// log lines.
	Mutex Locker

	// Control if the output should be in JSON.
	JSONFormat bool

	// Control the escape switch of json.Encoder
	JSONEscapeDisabled bool

	// Include file and line information in each log line
	IncludeLocation bool

	// AdditionalLocationOffset is the number of additional stack levels to skip
	// when finding the file and line information for the log line
	AdditionalLocationOffset int

	// The time format to use instead of the default
	TimeFormat string

	// A function which is called to get the time object that is formatted using `TimeFormat`
	TimeFn TimeFunction

	// Control whether or not to display the time at all. This is required
	// because setting TimeFormat to empty assumes the default format.
	DisableTime bool

	// Color the output. On Windows, colored logs are only available for io.Writers that
	// are concretely instances of *os.File.
	Color ColorOption

	// Only color the header, not the body. This can help with readability of long messages.
	ColorHeaderOnly bool

	// Color the header and message body fields. This can help with readability
	// of long messages with multiple fields.
	ColorHeaderAndFields bool

	// A function which is called with the log information and if it returns true the value
	// should not be logged.
	// This is useful when interacting with a system that you wish to suppress the log
	// message for (because it's too noisy, etc)
	Exclude func(level Level, msg string, args ...interface{}) bool

	// IndependentLevels causes subloggers to be created with an independent
	// copy of this logger's level. This means that using SetLevel on this
	// logger will not affect any subloggers, and SetLevel on any subloggers
	// will not affect the parent or sibling loggers.
	IndependentLevels bool

	// When set, changing the level of a logger effects only it's direct sub-loggers
	// rather than all sub-loggers. For example:
	// a := logger.Named("a")
	// a.SetLevel(Error)
	// b := a.Named("b")
	// c := a.Named("c")
	// b.GetLevel() => Error
	// c.GetLevel() => Error
	// b.SetLevel(Info)
	// a.GetLevel() => Error
	// b.GetLevel() => Info
	// c.GetLevel() => Error
	// a.SetLevel(Warn)
	// a.GetLevel() => Warn
	// b.GetLevel() => Warn
	// c.GetLevel() => Warn
	SyncParentLevel bool

	// SubloggerHook registers a function that is called when a sublogger via
	// Named, With, or ResetNamed is created. If defined, the function is passed
	// the newly created Logger and the returned Logger is returned from the
	// original function. This option allows customization via interception and
	// wrapping of Logger instances.
	SubloggerHook func(sub Logger) Logger
}

LoggerOptions can be used to configure a new logger.

type NoopLocker added in v0.12.2

type NoopLocker struct{}

NoopLocker implements locker but does nothing. This is useful if the client wants tight control over locking, in order to provide grouping of log entries or other functionality.

func (NoopLocker) Lock added in v0.12.2

func (n NoopLocker) Lock()

Lock does nothing

func (NoopLocker) Unlock added in v0.12.2

func (n NoopLocker) Unlock()

Unlock does nothing

type Octal added in v0.14.0

type Octal int

A simple shortcut to format numbers in octal when displayed with the normal text output. For example: L.Info("perms", Octal(17))

type OutputResettable added in v0.12.0

type OutputResettable interface {
	// ResetOutput swaps the current output writer with the one given in the
	// opts. Color options given in opts will be used for the new output.
	ResetOutput(opts *LoggerOptions) error

	// ResetOutputWithFlush swaps the current output writer with the one given
	// in the opts, first calling Flush on the given Flushable. Color options
	// given in opts will be used for the new output.
	ResetOutputWithFlush(opts *LoggerOptions, flushable Flushable) error
}

OutputResettable provides ways to swap the output in use at runtime

type Quote added in v0.16.2

type Quote string

A simple shortcut to format strings with Go quoting. Control and non-printable characters will be escaped with their backslash equivalents in output. Intended for untrusted or multiline strings which should be logged as concisely as possible.

type SinkAdapter added in v0.10.0

type SinkAdapter interface {
	Accept(name string, level Level, msg string, args ...interface{})
}

SinkAdapter describes the interface that must be implemented in order to Register a new sink to an InterceptLogger

func NewSinkAdapter added in v0.10.0

func NewSinkAdapter(opts *LoggerOptions) SinkAdapter

NewSinkAdapter returns a SinkAdapter with configured settings defined by LoggerOptions

type StandardLoggerOptions

type StandardLoggerOptions struct {
	// Indicate that some minimal parsing should be done on strings to try
	// and detect their level and re-emit them.
	// This supports the strings like [ERROR], [ERR] [TRACE], [WARN], [INFO],
	// [DEBUG] and strip it off before reapplying it.
	InferLevels bool

	// Indicate that some minimal parsing should be done on strings to try
	// and detect their level and re-emit them while ignoring possible
	// timestamp values in the beginning of the string.
	// This supports the strings like [ERROR], [ERR] [TRACE], [WARN], [INFO],
	// [DEBUG] and strip it off before reapplying it.
	// The timestamp detection may result in false positives and incomplete
	// string outputs.
	// InferLevelsWithTimestamp is only relevant if InferLevels is true.
	InferLevelsWithTimestamp bool

	// ForceLevel is used to force all output from the standard logger to be at
	// the specified level. Similar to InferLevels, this will strip any level
	// prefix contained in the logged string before applying the forced level.
	// If set, this override InferLevels.
	ForceLevel Level
}

StandardLoggerOptions can be used to configure a new standard logger.

type SupportsColor added in v1.5.0

type SupportsColor interface {
	SupportsColor() bool
}

SupportsColor is an optional interface that can be implemented by the output value. If implemented and SupportsColor() returns true, then AutoColor will enable colorization.

type TimeFunction added in v1.1.0

type TimeFunction = func() time.Time

Directories

Path Synopsis
hclogvet module

Jump to

Keyboard shortcuts

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