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
So far it's a "global" logger as in you just use the functions in the package directly (e.g log.S()) and the configuration is global for the process.
Index ¶
- Variables
- func ColorLevelToStr(lvl Level) string
- func ColorMode() bool
- func ConsoleLogging() bool
- func Critf(format string, rest ...interface{})
- func Debugf(format string, rest ...interface{})
- func EnvHelp(w io.Writer)
- func Errf(format string, rest ...interface{})
- func FErrf(format string, rest ...interface{}) int
- func Fatalf(format string, rest ...interface{})
- func Infof(format string, rest ...interface{})
- func InterceptStandardLogger(level Level)
- func Log(lvl Level) bool
- func LogAndCall(msg string, handlerFunc http.HandlerFunc, extraAttributes ...KeyVal) http.HandlerFunc
- func LogDebug() bool
- func LogRequest(r *http.Request, msg string, extraAttributes ...KeyVal)
- func LogResponse[T *ResponseRecorder | *http.Response](r T, msg string, extraAttributes ...KeyVal)
- func LogVerbose() bool
- func LogVf(format string, rest ...interface{})
- func Logf(lvl Level, format string, rest ...interface{})
- func LoggerStaticFlagSetup(names ...string)
- func NewStdLogger(source string, level Level) *log.Logger
- func Printf(format string, rest ...interface{})
- func S(lvl Level, msg string, attrs ...KeyVal)
- func SetColorMode()
- func SetDefaultsForClientTools()
- func SetFlags(f int)
- func SetLogLevelStr(str string) error
- func SetOutput(w io.Writer)
- func TLSInfo(r *http.Request) string
- func TimeToTS(t time.Time) float64
- func Warnf(format string, rest ...interface{})
- type JSONEntry
- type KeyVal
- func AddIfNotEmpty(attrs []KeyVal, key, value string) []KeyVal
- func Any[T ValueTypes](key string, value T) KeyVal
- func AppendTLSInfoAttrs(attrs []KeyVal, r *http.Request) []KeyVal
- func Attr[T ValueTypes](key string, value T) KeyVal
- func Bool(key string, value bool) KeyVal
- func Float64(key string, value float64) KeyVal
- func Int(key string, value int) KeyVal
- func Int64(key string, value int64) KeyVal
- func Rune(key string, value rune) KeyVal
- func Str(key, value string) KeyVal
- func String(key, value string) KeyVal
- type Level
- type LogConfig
- type LoggerI
- type ResponseRecorder
- type ValueType
- type ValueTypes
Constants ¶
This section is empty.
Variables ¶
var ( // ANSI color codes. // This isn't meant to be used directly and is here only to document the names of the struct. // Use the Colors variable instead. ANSIColors = color{ Reset: "\033[0m", Red: "\033[31m", Green: "\033[32m", Yellow: "\033[33m", Blue: "\033[34m", Purple: "\033[35m", Cyan: "\033[36m", Gray: "\033[37m", White: "\033[97m", BrightRed: "\033[91m", DarkGray: "\033[90m", } // ANSI color codes or empty depending on ColorMode. // These will be reset to empty string if color is disabled (see ColorMode() and SetColorMode()). // Start with actual colors, will be reset to empty if color is disabled. Colors = ANSIColors // Mapping of log levels to color. LevelToColor = []string{ Colors.Gray, Colors.Cyan, Colors.Green, Colors.Yellow, Colors.Red, Colors.Purple, Colors.BrightRed, Colors.Green, } // Used for color version of console logging. LevelToText = []string{ "DBG", "VRB", "INF", "WRN", "ERR", "CRI", "FTL", "", } // Cached flag for whether to use color output or not. Color = false )
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\"", "\"info\"", } // Reverse mapping of level string used in JSON to Level. Used by https://github.com/fortio/logc // to interpret and colorize pre existing JSON logs. JSONStringLevelToLevel map[string]Level )
Functions ¶
func ColorLevelToStr ¶ added in v1.9.2
Longer version when colorizing on console of the level text.
func ColorMode ¶ added in v1.6.0
func ColorMode() bool
ColorMode returns true if we should be using color text mode, which is either because it's forced or because we are in a console and the config allows it. Should not be called often, instead read/update the Color variable when needed.
func ConsoleLogging ¶ added in v1.6.0
func ConsoleLogging() bool
ConsoleLogging is a utility to check if the current logger output is a console (terminal).
func EnvHelp ¶ added in v1.12.0
EnvHelp shows the current config as environment variables.
LOGGER_LOG_PREFIX, LOGGER_LOG_FILE_AND_LINE, LOGGER_FATAL_PANICS, LOGGER_JSON, LOGGER_NO_TIMESTAMP, LOGGER_CONSOLE_COLOR, LOGGER_CONSOLE_COLOR LOGGER_FORCE_COLOR, LOGGER_GOROUTINE_ID, LOGGER_COMBINE_REQUEST_AND_RESPONSE, LOGGER_LEVEL.
func FErrf ¶
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 InterceptStandardLogger ¶ added in v1.10.0
func InterceptStandardLogger(level Level)
InterceptStandardLogger changes the output of the standard logger to use ours, at the given level, with the source "std", as a catchall.
func LogAndCall ¶ added in v1.12.0
func LogAndCall(msg string, handlerFunc http.HandlerFunc, extraAttributes ...KeyVal) http.HandlerFunc
LogAndCall logs the incoming request and the response code, byte size and duration of the request.
If Config.CombineRequestAndResponse or the LOGGER_COMBINE_REQUEST_AND_RESPONSE environment variable is true, then a single log entry is done combining request and response information, including catching for panic.
Additional key:value pairs can be passed as extraAttributes.
func LogRequest ¶ added in v1.1.0
LogRequest logs the incoming request, TLSInfo, including headers when loglevel is verbose. additional key:value pairs can be passed as extraAttributes.
func LogResponse ¶ added in v1.12.0
func LogResponse[T *ResponseRecorder | *http.Response](r T, msg string, extraAttributes ...KeyVal)
LogResponse logs the response code, byte size and duration of the request. additional key:value pairs can be passed as extraAttributes.
func Logf ¶
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.go.dev/fortio.org/dflag/dynloglevel#LoggerFlagSetup for a dynamic flag instead.
func NewStdLogger ¶ added in v1.10.0
Returns a Std logger that will log to the given level with the given source attribute. Can be passed for instance to net/http/httputil.ReverseProxy.ErrorLog.
func Printf ¶
func Printf(format string, rest ...interface{})
Printf forwards to the underlying go logger to print (with only timestamp prefixing).
func SetColorMode ¶ added in v1.6.0
func SetColorMode()
SetColorMode computes whether we currently should be using color text mode or not. Need to be reset if config changes (but is already automatically re evaluated when calling SetOutput()). It will reset the Colors variable to either be the actual escape sequences or empty strings (when color is disabled).
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. Will be ignored if the environment config has been set to ignore this.
func SetLogLevelStr ¶
Sets level from string (called by dflags). Use https://pkg.go.dev/fortio.org/dflag/dynloglevel#LoggerFlagSetup to set up `-loglevel` as a dynamic flag (or an example of how this function is used).
func TLSInfo ¶ added in v1.1.0
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.
Types ¶
type JSONEntry ¶ added in v1.4.0
type JSONEntry struct { TS float64 // In seconds since epoch (unix micros resolution), see TimeToTS(). R int64 // Goroutine ID (if enabled) 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.
type KeyVal ¶ added in v1.4.0
func AddIfNotEmpty ¶ added in v1.12.0
func Any ¶ added in v1.11.0
func Any[T ValueTypes](key string, value T) KeyVal
func AppendTLSInfoAttrs ¶ added in v1.4.0
func Attr ¶ added in v1.4.0
func Attr[T ValueTypes](key string, value T) KeyVal
Our original name, now switched to slog style Any.
func String ¶ added in v1.11.0
String() is the slog compatible name for Str. Ends up calling Any() anyway.
func (*KeyVal) StringValue ¶ added in v1.11.0
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 NoLevel // Prefix for all config from environment, // e.g NoTimestamp becomes LOGGER_NO_TIMESTAMP. EnvPrefix = "LOGGER_" )
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 SetLogLevel ¶
SetLogLevel sets the log level and returns the previous one.
func SetLogLevelQuiet ¶
SetLogLevelQuiet sets the log level and returns the previous one but does not log the change of level itself.
func ValidateLevel ¶
ValidateLevel returns error if the level string is not valid.
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) `env:"-"` // Function to call upon log.Fatalf. e.g. os.Exit. JSON bool // If true, log in structured JSON format instead of text (but see ConsoleColor). NoTimestamp bool // If true, don't log timestamp in json. ConsoleColor bool // If true and we detect console output (not redirected), use text+color mode. // Force color mode even if logger output is not console (useful for CI that recognize ansi colors). // SetColorMode() must be called if this or ConsoleColor are changed. ForceColor bool // If true, log the goroutine ID (gid) in json. GoroutineID bool // If true, single combined log for LogAndCall CombineRequestAndResponse bool // String version of the log level, used for setting from environment. Level string // If true, ignore SetDefaultsForClientTools() calls even if set. Allows full line/file debug and basically // imply configuration from the environment variables. IgnoreCliMode bool }
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. It's JSON structured by default, unless console is detected. Use SetDefaultsForClientTools for CLIs.
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()]. See also [NewStdLogger()] for intercepting with same type / when an interface can't be used.
type ResponseRecorder ¶ added in v1.12.0
type ResponseRecorder struct { StatusCode int ContentLength int64 // contains filtered or unexported fields }
Can be used (and is used by LogAndCall()) to wrap a http.ResponseWriter to record status code and size.
func (*ResponseRecorder) Flush ¶ added in v1.12.0
func (rr *ResponseRecorder) Flush()
Implement http.Flusher interface.
func (*ResponseRecorder) Header ¶ added in v1.12.0
func (rr *ResponseRecorder) Header() http.Header
func (*ResponseRecorder) Write ¶ added in v1.12.0
func (rr *ResponseRecorder) Write(p []byte) (int, error)
func (*ResponseRecorder) WriteHeader ¶ added in v1.12.0
func (rr *ResponseRecorder) WriteHeader(code int)
type ValueType ¶ added in v1.4.0
type ValueType[T ValueTypes] struct { Val T }
type ValueTypes ¶ added in v1.4.0
type ValueTypes interface{ any }
Directories ¶
Path | Synopsis |
---|---|
Initially from https://github.com/fortio/logc/blob/v1.1.0/levelsDemo/levels.go
|
Initially from https://github.com/fortio/logc/blob/v1.1.0/levelsDemo/levels.go |