Documentation ¶
Overview ¶
Package log package provides convenient and flexible utilities for logging messages.
Overview ¶
Logging is done by calling functions in this package that correspond to the severity of the log message being output. At the package level, a minimum severity can be set. Messages less severe than this minimum logging level will not be output.
Color Expressions ¶
In addition to the standard printf-style formatting options (as defined in the standard fmt package), this package supports inline expressions that control the output of ANSI terminal escape sequences. These expressions allow for a simple mechanism to colorize log output, as well as applying graphical effects like bold, underline, and blinking text (for terminals that support it).
By default, color expressions will only be honored if os.Stdin is attached to a pseudoterminal. This is the case when the program is run on the command line and is not piped or redirected to another file. This default ensures that the colors are visible only in a visual context, but do not corrupt files or pipelines with ANSI escape sequences. Color sequences can be explicitly enabled or disabled by setting the EnableColorExpressions package variable.
Using color expressions in format strings is done by wrapping the expression in ${expr}. The general format for color expressions is:
foregroundColor[+attributes[:backgroundColor[+attributes]]]
Colors (foreground and background):
black red green yellow blue magenta cyan white [0-255]: numeric 8-bit color (for 256 color terminals) reset: Reset all color and graphics attributes to their defaults
Foreground Attributes:
b: bold text B: blinking text h: high-intensity (bright text) i: inverted/reverse colors s: strikethrough u: underline
Background Attributes:
h: high-intensity (bright text)
Examples ¶
Below are some examples showing various formatting options for logs.
log.Info("Hello, world!") // [11:22:33 0001] INFO Hello, world! log.Warningf("The %q operation could not be completed.", "add") // [11:22:33 0002] WARN The "add" operation could not be completed. log.Errorf("There was an ${red}error${reset} opening file ${blue+b:white}%s${reset}", filename) // [11:22:33 0003] ERRO There was an error opening file /tmp/file.txt // ^^^^^ ^^^^^^^^^^^^^ // red text blue text on white background
Log Interception ¶
It is sometimes useful to be able to act on logs as they are emitted, especially in cases where this package is used in other projects that are imported. Log Interceptors are called before each log line is emitted. The LogInterceptFunc is called with the level the message was emitted with, the message itself as a string, and a stack trace struct that defines exactly where the log was emitted from.
// print a complete stack trace before every debug-level message that is encountered log.AddLogIntercept(func(level log.Level, line string, stack log.StackItems){ if level == log.DEBUG { for _, item := range stack { fmt.Println(item.String()) } } })
Writable Logger ¶
The WritableLogger implements the io.Writer interface, acting as a bridge between byte streams from various sources and the log package. This is frequently useful in situations like parsing the output of other programs. A WritableLogger accepts a custom LogParseFunc that allows individual lines being written to the WritableLogger to be parsed, rewritten, and given a log severity level.
import ( "os/exec" "github.com/ghetzel/go-stockutil/log" ) wr := log.NewWritableLogger(log.INFO, `ls: `) wr.SetParserFunc(func(line string) (log.Level, string) { if strings.Contains(line, `root`) { // root-owned files show up as errors return log.ERROR, line } else if strings.Contains(line, os.Getenv(`USER`)) { // current user files are notices return log.NOTICE, line } else { // all other lines are not logged at all return log.DEBUG, `` } }) ls := exec.Command(`ls`, `-l`) ls.Stdout = wr ls.Run()
Index ¶
- Variables
- func AddLogIntercept(fn LogInterceptFunc) string
- func AppendError(base error, err error) error
- func CFPrintf(w io.Writer, format string, args ...interface{}) (int, error)
- func CSprintf(format string, args ...interface{}) string
- func CStripf(format string, args ...interface{}) string
- func Confirm(prompt string) bool
- func Confirmf(format string, args ...interface{}) bool
- func Critical(args ...interface{})
- func Criticalf(format string, args ...interface{})
- func Debug(args ...interface{})
- func DebugStack()
- func Debugf(format string, args ...interface{})
- func Debugging() bool
- func Dump(args ...interface{})
- func Dumpf(format string, args ...interface{})
- func ErrContains(err error, message interface{}) bool
- func ErrHasPrefix(err error, message interface{}) bool
- func ErrHasSuffix(err error, message interface{}) bool
- func Error(args ...interface{})
- func Errorf(format string, args ...interface{})
- func Fatal(args ...interface{})
- func FatalIf(err error)
- func Fatalf(format string, args ...interface{})
- func FatalfIf(format string, err error)
- func Info(args ...interface{})
- func Infof(format string, args ...interface{})
- func Log(level Level, args ...interface{})
- func Logf(level Level, format string, args ...interface{})
- func Logger() *logging.Logger
- func Notice(args ...interface{})
- func Noticef(format string, args ...interface{})
- func Panic(args ...interface{})
- func Panicf(format string, args ...interface{})
- func RemoveLogIntercept(id string)
- func SetLevel(level Level, modules ...string)
- func SetLevelString(level string, modules ...string)
- func SetOutput(w io.Writer)
- func TermSprintf(format string, args ...interface{}) string
- func Warning(args ...interface{})
- func Warningf(format string, args ...interface{})
- type FormattedLogFunc
- type Level
- type LogFunc
- type LogInterceptFunc
- type LogParseFunc
- type StackItem
- type StackItems
- type Timing
- type WritableLogger
Constants ¶
This section is empty.
Variables ¶
var DefaultInterceptStackDepth int = 5
var EnableColorExpressions = func() bool { if forceColor := os.Getenv(`FORCE_COLOR`); forceColor != `` { return typeutil.Bool(forceColor) } else { return isatty.IsTerminal(os.Stdout.Fd()) } }()
var MaxStackTraceDepth = 32
var ModuleName = ``
var SynchronousIntercepts = false
var TerminalEscapePrefix = `\[`
var TerminalEscapeSuffix = `\]`
Functions ¶
func AddLogIntercept ¶ added in v1.7.4
func AddLogIntercept(fn LogInterceptFunc) string
Append a function to be called (asynchronously in its own goroutine, or synchronously if SynchronousIntercepts is true) for every line logged. Returns a UUID that can be later used to deregister the intercept function.
func AppendError ¶
Appends one error to another, allowing for operations that return multiple errors to remain compatible within a single-valued context.
func Confirmf ¶
Present a confirmation prompt. The function returns true if the user interactively responds with "yes" or "y". Otherwise the function returns false.
func DebugStack ¶ added in v1.5.50
func DebugStack()
Logs the current stack trace as debug log output.
func ErrContains ¶ added in v1.7.46
Return whether the given error contains with the given message. Message can be a string or another error. If either is nil, this function returns false.
func ErrHasPrefix ¶ added in v1.7.46
Return whether the given error is prefixed with the given message. Message can be a string or another error. If either is nil, this function returns false.
func ErrHasSuffix ¶ added in v1.7.46
Return whether the given error is suffixed with the given message. Message can be a string or another error. If either is nil, this function returns false.
func FatalIf ¶ added in v1.7.53
func FatalIf(err error)
Invoke Fatal() if the given error is not nil.
func RemoveLogIntercept ¶ added in v1.7.4
func RemoveLogIntercept(id string)
Remove the previously-added log intercept function.
func SetLevelString ¶
func TermSprintf ¶ added in v1.7.21
Same as CSprintf, but wraps all replaced color sequences with terminal escape sequences as defined in TerminalEscapePrefix and TerminalEscapeSuffix
Types ¶
type FormattedLogFunc ¶
type FormattedLogFunc func(format string, args ...interface{})
type Level ¶
type Level int
type LogInterceptFunc ¶ added in v1.7.4
type LogInterceptFunc func(level Level, line string, stack StackItems)
type LogParseFunc ¶
type StackItems ¶ added in v1.5.50
type StackItems []StackItem
func StackTrace ¶ added in v1.5.50
func StackTrace(skip int) StackItems
Retrieves details about the call stack that led to this function call.
type WritableLogger ¶
type WritableLogger struct {
// contains filtered or unexported fields
}
func NewWritableLogger ¶
func NewWritableLogger(level Level, prefix ...string) *WritableLogger
func (*WritableLogger) SetParserFunc ¶
func (self *WritableLogger) SetParserFunc(fn LogParseFunc) *WritableLogger