Categorygithub.com/varnson/go-hclog
modulepackage
0.15.8
Repository: https://github.com/varnson/go-hclog.git
Documentation: pkg.go.dev

# 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

While this library is fully open source and HashiCorp will be maintaining it (since we are and will be making extensive use of it), the API and output format is subject to minor changes as we fully bake and vet it in our projects. This notice will be removed once it's fully integrated into our major projects and no further changes are anticipated.

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()

var int 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.

# Packages

No description provided by the author

# Functions

Default returns a globally held logger.
Fmt returns a Format type.
FromContext returns a logger from the context.
Takes a standard library logger and returns a Logger that will write to it.
L is a short alias for Default().
LevelFromString returns a Level type for the named log level, or "NoLevel" if the level string is invalid.
New returns a configured logger.
No description provided by the author
NewLeveledWriter returns an initialized LeveledWriter.
NewNullLogger instantiates a Logger for which all calls will succeed without doing anything.
NewSinkAdapter returns a SinkAdapter with configured settings defined by LoggerOptions.
SetDefault changes the logger to be returned by Default()and L() to the one given.
Stacktrace captures a stacktrace of the current goroutine and returns it to be passed to a logging function.
WithContext inserts a logger into the context and is retrievable with FromContext.

# Constants

AutoColor checks if the io.Writer is a tty, and if so enables coloring.
ColorOff is the default coloration, and does not inject color codes into the io.Writer.
Debug information for programmer lowlevel analysis.
Error information about unrecoverable events.
ForceColor will enable coloring, regardless of whether the io.Writer is a tty or not.
Info information about steady state operations.
No description provided by the author
NoLevel is a special level used to indicate that no level has been set and allow for a default to be used.
Off disables all logging output.
TimeFormat to use for logging.
Trace is the most verbose level.
Warn information about rare but handled events.

# Variables

DefaultLevel is used as the default log level.
DefaultOptions is used to create the Default logger.
DefaultOutput is used as the default log output.

# Structs

ExcludeByMessage provides a simple way to build a list of log messages that can be queried and matched.
ExcludeByRegexp takes a regexp and uses it to match a log message string.
LeveledWriter writes all log messages to the standard writer, except for log levels that are defined in the overrides map.
LoggerOptions can be used to configure a new logger.
NoopLocker implements locker but does nothing.
StandardLoggerOptions can be used to configure a new standard logger.

# Interfaces

Flushable represents a method for flushing an output buffer.
InterceptLogger describes the interface for using a logger that can register different output sinks.
LevelWriter is the interface that wraps the LevelWrite method.
Locker is used for locking output.
Logger describes the interface that must be implemeted by all loggers.
OutputResettable provides ways to swap the output in use at runtime.
SinkAdapter describes the interface that must be implemented in order to Register a new sink to an InterceptLogger.

# Type aliases

A simple shortcut to format numbers in binary when displayed with the normal text output.
CapturedStacktrace represents a stacktrace captured by a previous call to log.Stacktrace.
ColorOption expresses how the output should be colored, if at all.
ExcludeByPrefix is a simple type to match a message string that has a common prefix.
ExcludeFuncs is a slice of functions that will called to see if a log entry should be filtered or not.
Format is a simple convience type for when formatting is required.
A simple shortcut to format numbers in hex when displayed with the normal text output.
Level represents a log level.
A simple shortcut to format numbers in octal when displayed with the normal text output.