log

package
v1.8.44 Latest Latest
Warning

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

Go to latest
Published: Jan 31, 2020 License: MIT Imports: 16 Imported by: 81

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

Constants

This section is empty.

Variables

View Source
var DefaultInterceptStackDepth int = 5
View Source
var EnableColorExpressions = func() bool {
	if forceColor := os.Getenv(`FORCE_COLOR`); forceColor != `` {
		return typeutil.Bool(forceColor)
	} else {
		return isatty.IsTerminal(os.Stdout.Fd())
	}
}()
View Source
var MaxStackTraceDepth = 32
View Source
var ModuleName = ``
View Source
var SynchronousIntercepts = false
View Source
var TerminalEscapePrefix = `\[`
View Source
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

func AppendError(base error, err error) error

Appends one error to another, allowing for operations that return multiple errors to remain compatible within a single-valued context.

func CFPrintf added in v1.7.18

func CFPrintf(w io.Writer, format string, args ...interface{}) (int, error)

func CSprintf added in v1.7.18

func CSprintf(format string, args ...interface{}) string

func CStripf added in v1.7.18

func CStripf(format string, args ...interface{}) string

func Confirm

func Confirm(prompt string) bool

func Confirmf

func Confirmf(format string, args ...interface{}) bool

Present a confirmation prompt. The function returns true if the user interactively responds with "yes" or "y". Otherwise the function returns false.

func Critical

func Critical(args ...interface{})

func Criticalf

func Criticalf(format string, args ...interface{})

func Debug

func Debug(args ...interface{})

func DebugStack added in v1.5.50

func DebugStack()

Logs the current stack trace as debug log output.

func Debugf

func Debugf(format string, args ...interface{})

func Debugging

func Debugging() bool

func Dump

func Dump(args ...interface{})

func Dumpf

func Dumpf(format string, args ...interface{})

func ErrContains added in v1.7.46

func ErrContains(err error, message interface{}) bool

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

func ErrHasPrefix(err error, message interface{}) bool

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

func ErrHasSuffix(err error, message interface{}) bool

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 Error

func Error(args ...interface{})

func Errorf

func Errorf(format string, args ...interface{})

func Fatal

func Fatal(args ...interface{})

func FatalIf added in v1.7.53

func FatalIf(err error)

Invoke Fatal() if the given error is not nil.

func Fatalf

func Fatalf(format string, args ...interface{})

func FatalfIf added in v1.7.53

func FatalfIf(format string, err error)

Invoke Fatalf() if the given error is not nil.

func Info

func Info(args ...interface{})

func Infof

func Infof(format string, args ...interface{})

func Log

func Log(level Level, args ...interface{})

func Logf

func Logf(level Level, format string, args ...interface{})

func Logger

func Logger() *logging.Logger

func Notice

func Notice(args ...interface{})

func Noticef

func Noticef(format string, args ...interface{})

func Panic

func Panic(args ...interface{})

func Panicf

func Panicf(format string, args ...interface{})

func RemoveLogIntercept added in v1.7.4

func RemoveLogIntercept(id string)

Remove the previously-added log intercept function.

func SetLevel

func SetLevel(level Level, modules ...string)

func SetLevelString

func SetLevelString(level string, modules ...string)

func SetOutput

func SetOutput(w io.Writer)

Set the destination Writer where logs will henceforth be written.

func TermSprintf added in v1.7.21

func TermSprintf(format string, args ...interface{}) string

Same as CSprintf, but wraps all replaced color sequences with terminal escape sequences as defined in TerminalEscapePrefix and TerminalEscapeSuffix

func Warning

func Warning(args ...interface{})

func Warningf

func Warningf(format string, args ...interface{})

Types

type FormattedLogFunc

type FormattedLogFunc func(format string, args ...interface{})

type Level

type Level int
const (
	PANIC Level = iota
	FATAL
	CRITICAL
	ERROR
	WARNING
	NOTICE
	INFO
	DEBUG
)
var LogLevel Level = func() Level {
	if v := os.Getenv(`LOGLEVEL`); v != `` {
		return GetLevel(v)
	} else {
		return INFO
	}
}()

The LOGLEVEL environment variable has final say over the effective log level for all users of this package.

func GetLevel

func GetLevel(level string) Level

func (Level) String

func (self Level) String() string

type LogFunc

type LogFunc func(args ...interface{})

type LogInterceptFunc added in v1.7.4

type LogInterceptFunc func(level Level, line string, stack StackItems)

type LogParseFunc

type LogParseFunc func(line string) (Level, string)

type StackItem added in v1.5.50

type StackItem struct {
	ProgramCounter uintptr
	Filename       string
	Line           int
	Function       string
}

func (StackItem) String added in v1.5.50

func (self StackItem) String() string

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 Timing added in v1.7.43

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

func Time added in v1.7.43

func Time(name string) *Timing

func TimeFunc added in v1.7.43

func TimeFunc(name string, fn func()) *Timing

func (*Timing) Done added in v1.7.43

func (self *Timing) Done() time.Duration

func (*Timing) Reset added in v1.7.43

func (self *Timing) Reset()

func (*Timing) Then added in v1.7.43

func (self *Timing) Then(name string) *Timing

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

func (*WritableLogger) Write

func (self *WritableLogger) Write(p []byte) (int, error)

Jump to

Keyboard shortcuts

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