log

package module
v1.4.1 Latest Latest
Warning

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

Go to latest
Published: Jun 20, 2023 License: Apache-2.0 Imports: 12 Imported by: 54

README

codecov

Log

Fortio's log is simple logger built on top of go's default one with additional opinionated levels similar to glog but simpler to use and configure.

It's been used for many years for Fortio's org Fortio project and more (under fortio.org/fortio/log package) but split out recently for standalone use, with the "flag polution" limited (as a library it doesn't include the flags, you configure it using apis).

// On a cli tool (avoids file name and line numbers, stack traces on log.Fatalf etc)
log.SetDefaultsForClientTools()
log.LoggerStaticFlagSetup() // adds -loglevel flag to configure
// Or on a server type, import fortio.org/dflag, then:
dflag.LoggerFlagSetup()

// Then, printf style leveled logging:
log.Debugf(...) // Debug level
log.LogVf(...)  // Verbose level
log.Infof(...)  // Info/default level
log.Warnf(...)  // Warning level
log.Errf(...)   // Error level
log.Critf(...)  // Critical level (always logged even if level is set to max)
log.Fatalf(...) // Fatal level - program will panic/exit

// for http servers there is also
// access log type including user-agent, forwarded ip/proto (behind load balancer case),
// TLS crypto used and CN of peer certificate if any.
log.LogRequest(r, "some info")

// Structured logging with attributes
log.S(log.Info, "msg", log.Attr("key1", value1)...)

See the Config object for options like whether to include line number and file name of caller or not etc

New since 1.4 server logging (as used in fortio.org/scli for instance) is now structured (json), client logging (as setup by fortio.org/cli remains as before.

One can also revert server to not be JSON through config.

In JSON mode the output looks like this

{"ts":1683504169239557,"level":"info","file":"logger.go","line":221,"msg":"Log level is now 1 Verbose (was 2 Info"}

Which can be converted to JSONEntry but is also a fixed, optimized format (ie ts is always first etc)

The timestamp ts is in microseconds since epoch (golang UnixMicro())

Optional additional KeyValue pairs can be added to the base structure using the new log.S or passed to log.LogRequest using log.Attr and log.Str.

JSON formatted logs can be converted back to text and colorized using fortio.org/logc

Example console color output

Documentation

Overview

Fortio's log is simple logger built on top of go's default one with additional opinionated levels similar to glog but simpler to use and configure.

See Config object for options like whether to include line number and file name of caller or not etc

Index

Constants

This section is empty.

Variables

View Source
var (
	Config = DefaultConfig()
	// Used for dynamic flag setting as strings and validation.
	LevelToStrA = []string{
		"Debug",
		"Verbose",
		"Info",
		"Warning",
		"Error",
		"Critical",
		"Fatal",
	}

	// Used for JSON logging.
	LevelToJSON = []string{

		"\"dbug\"",
		"\"trace\"",
		"\"info\"",
		"\"warn\"",
		"\"err\"",
		"\"crit\"",
		"\"fatal\"",
	}
)

Functions

func Critf

func Critf(format string, rest ...interface{})

Critf logs if Warning level is on.

func Debugf

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

Debugf logs if Debug level is on.

func Errf

func Errf(format string, rest ...interface{})

Errf logs if Warning level is on.

func FErrf

func FErrf(format string, rest ...interface{}) int

FErrF logs a fatal error and returns 1. meant for cli main functions written like:

func main() { os.Exit(Main()) }

and in Main() they can do:

if err != nil {
	return log.FErrf("error: %v", err)
}

so they can be tested with testscript. See https://github.com/fortio/delta/ for an example.

func Fatalf

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

Fatalf logs if Warning level is on and panics or exits.

func Infof

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

Infof logs if Info level is on.

func Log

func Log(lvl Level) bool

Log returns true if a given level is currently logged.

func LogDebug

func LogDebug() bool

LogDebug shortcut for fortio.Log(fortio.Debug).

func LogRequest added in v1.1.0

func LogRequest(r *http.Request, msg string, extraAttributes ...KeyVal)

LogRequest logs the incoming request, TLSInfo, including headers when loglevel is verbose. additional key:value pairs can be passed as extraAttributes.

func LogVerbose

func LogVerbose() bool

LogVerbose shortcut for fortio.Log(fortio.Verbose).

func LogVf

func LogVf(format string, rest ...interface{})

LogVf logs if Verbose level is on.

func Logf

func Logf(lvl Level, format string, rest ...interface{})

Logf logs with format at the given level. 2 level of calls so it's always same depth for extracting caller file/line. Note that log.Logf(Fatal, "...") will not panic or exit, only log.Fatalf() does.

func LoggerStaticFlagSetup added in v1.2.0

func LoggerStaticFlagSetup(names ...string)

LoggerStaticFlagSetup call to setup a static flag under the passed name or `-loglevel` by default, to set the log level. Use https://pkg.golang.ir/fortio.org/dflag/dynloglevel#LoggerFlagSetup for a dynamic flag instead.

func Printf

func Printf(format string, rest ...interface{})

Printf forwards to the underlying go logger to print (with only timestamp prefixing).

func S added in v1.4.0

func S(lvl Level, msg string, attrs ...KeyVal)

func SetDefaultsForClientTools

func SetDefaultsForClientTools()

SetDefaultsForClientTools changes the default value of LogPrefix and LogFileAndLine to make output without caller and prefix, a default more suitable for command line tools (like dnsping). Needs to be called before flag.Parse(). Caller could also use log.Printf instead of changing this if not wanting to use levels. Also makes log.Fatalf just exit instead of panic.

func SetFlags

func SetFlags(f int)

SetFlags forwards flags to the system logger.

func SetLogLevelStr

func SetLogLevelStr(str string) error

Sets level from string (called by dflags). Use https://pkg.golang.ir/fortio.org/dflag/dynloglevel#LoggerFlagSetup to set up `-loglevel` as a dynamic flag (or an example of how this function is used).

func SetOutput

func SetOutput(w io.Writer)

SetOutput sets the output to a different writer (forwards to system logger).

func TLSInfo added in v1.1.0

func TLSInfo(r *http.Request) string

TLSInfo returns ' https <cipher suite> "<peer CN>"' if the request is using TLS (and ' "<peer CN>"' part if mtls / a peer certificate is present) or "" otherwise. Use AppendTLSInfoAttrs unless you do want to just output text.

func TimeToTS added in v1.4.0

func TimeToTS(t time.Time) int64

func Warnf

func Warnf(format string, rest ...interface{})

Warnf logs if Warning level is on.

Types

type JSONEntry added in v1.4.0

type JSONEntry struct {
	TS    int64 // in microseconds since epoch (unix micros)
	Level string
	File  string
	Line  int
	Msg   string
}

JSONEntry is the logical format of the JSON [Config.JSON] output mode. While that serialization of is custom in order to be cheap, it maps to the following structure.

func (*JSONEntry) Time added in v1.4.0

func (l *JSONEntry) Time() time.Time

LogEntry Ts to time.Time conversion. The returned time is set UTC to avoid TZ mismatch.

type KeyVal added in v1.4.0

type KeyVal struct {
	Key   string
	Value fmt.Stringer
}

func AppendTLSInfoAttrs added in v1.4.0

func AppendTLSInfoAttrs(attrs []KeyVal, r *http.Request) []KeyVal

func Attr added in v1.4.0

func Attr[T ValueTypes](key string, value T) KeyVal

func Str added in v1.4.0

func Str(key, value string) KeyVal

type Level

type Level int32

Level is the level of logging (0 Debug -> 6 Fatal).

const (
	Debug Level = iota
	Verbose
	Info
	Warning
	Error
	Critical
	Fatal
)

Log levels. Go can't have variable and function of the same name so we keep medium length (Dbg,Info,Warn,Err,Crit,Fatal) names for the functions.

func GetLogLevel

func GetLogLevel() Level

GetLogLevel returns the currently configured LogLevel.

func LevelByName

func LevelByName(str string) Level

LevelByName returns the LogLevel by its name.

func SetLogLevel

func SetLogLevel(lvl Level) Level

SetLogLevel sets the log level and returns the previous one.

func SetLogLevelQuiet

func SetLogLevelQuiet(lvl Level) Level

SetLogLevelQuiet sets the log level and returns the previous one but does not log the change of level itself.

func ValidateLevel

func ValidateLevel(str string) (Level, error)

ValidateLevel returns error if the level string is not valid.

func (Level) String

func (l Level) String() string

String returns the string representation of the level.

type LogConfig

type LogConfig struct {
	LogPrefix      string    // "Prefix to log lines before logged messages
	LogFileAndLine bool      // Logs filename and line number of callers to log.
	FatalPanics    bool      // If true, log.Fatalf will panic (stack trace) instead of just exit 1
	FatalExit      func(int) // Function to call upon log.Fatalf. e.g. os.Exit.
	JSON           bool      // If true, log in structured JSON format instead of text.
	NoTimestamp    bool      // If true, don't log timestamp in json.
}

func DefaultConfig

func DefaultConfig() *LogConfig

DefaultConfig() returns the default initial configuration for the logger, best suited for servers. It will log caller file and line number, use a prefix to split line info from the message and panic (+exit) on Fatal.

type LoggerI

type LoggerI interface {
	Printf(format string, rest ...interface{})
}

LoggerI defines a log.Logger like interface to pass to packages for simple logging. See [Logger()].

func Logger

func Logger() LoggerI

Logger returns a LoggerI (standard logger compatible) that can be used for simple logging.

type StringValue added in v1.4.0

type StringValue string

func (StringValue) String added in v1.4.0

func (s StringValue) String() string

type ValueType added in v1.4.0

type ValueType[T ValueTypes] struct {
	Val T
}

func (*ValueType[T]) String added in v1.4.0

func (v *ValueType[T]) String() string

type ValueTypes added in v1.4.0

type ValueTypes interface{ any }

Jump to

Keyboard shortcuts

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