log

package
v1.9.5 Latest Latest
Warning

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

Go to latest
Published: Aug 26, 2023 License: MIT Imports: 17 Imported by: 26

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/PerformLine/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

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

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

func CSprintf

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

func CStripf

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

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{})

Pretty-print the given arguments to the log at debug-level.

func DumpJSON

func DumpJSON(args ...interface{})

Marshal the arguments as indented JSON and log them at debug-level.

func Dumpf

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

Same as Dump, but accepts a format string.

func ErrContains

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

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

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

func FatalIf(err error)

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

func Fatalf

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

func FatalfIf

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

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

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 VeryDebugging

func VeryDebugging(features ...string) bool

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

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

type LogParseFunc

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

type StackItem

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

func (StackItem) String

func (self StackItem) String() string

type StackItems

type StackItems []StackItem

func StackTrace

func StackTrace(skip int) StackItems

Retrieves details about the call stack that led to this function call.

type Timing

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

func Time

func Time(name string) *Timing

func TimeFunc

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

func (*Timing) Done

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

func (*Timing) Reset

func (self *Timing) Reset()

func (*Timing) Then

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