nxlog4go Log Levels and Pattern Layout

时间:2023-03-09 06:47:06
nxlog4go Log Levels and Pattern Layout

Log levels

nxlog4go provides log levels as below:

type Level int

const (
FINEST Level = iota
FINE
DEBUG
TRACE
INFO
WARNING
ERROR
CRITICAL
_SILENT_ = 100
) // Strings
var (
levelStrings = [...]string{"FNST", "FINE", "DEBG", "TRAC", "INFO", "WARN", "EROR", "CRIT", "OFFL"}
)

DEBUG - WARNING, are more useful.

ERROR, may cause the program exited.

CRITICAL, may crash the program.

_SILENT_, used during configuration to turn in quiet mode. It is used in loglog (internal logger) and set as default.

Setting filter level

var log = l4g.New(l4g.DEBUG)

Setting the log level when build a logger.

log.SetLevel(l4g.WARNING)

Setting the output level for the logger. Any log's level which is lower then WARNING should be ignored.

SetXXX functions in nxlog4go always return a point, so it is chainable. For example:

var log = l4g.New(l4g.DEBUG).SetPrefix("example").SetPattern("[%T %D %Z] [%L] (%P:%s) %M\n")

Pattern layout

  • Pattern codes
// %N - Time (15:04:05.000000)
// %T - Time (15:04:05)
// %t - Time (15:04)
// %Z - Zone (-0700)
// %z - Zone (MST)
// %D - Date (2006/01/02)
// %Y - Date (2006-01-02)
// %d - Date (01/02/06)
// %L - Level (FNST, FINE, DEBG, TRAC, WARN, EROR, CRIT)
// %l - Level
// %P - Prefix
// %S - Source
// %s - Short Source
// %n - Line number
// %M - Message
// %R - Return (\n)
// Ignores unknown formats
  • Some default patterns
var (
PATTERN_DEFAULT = "[%D %T %z] [%L] (%s:%n) %M\n"
PATTERN_SHORT = "[%t %d] [%L] %M\n"
PATTERN_ABBREV = "[%L] %M\n"
PATTERN_JSON = "{\"Level\":%l,\"Created\":\"%YT%N%Z\",\"Prefix\":\"%P\",\"Source\":\"%S\",\"Line\":%n,\"Message\":\"%M\"}"
)
  • Setting pattern
log.SetPattern("[%T %D %Z] [%L] (%P:%s) %M\n")

"\n" is byte 0x13. "%R" is same and always used in configuration.

Or:

log.SetPattern(PATTERN_JSON)

PATTERN_JSON encode the log to JSON format. It is 2x faster than JSON encoder.

  • Output like
[22:48:35 2018/03/01 +08:00] [INFO] (example:example.go) The time is now: 22:48:35 CST 2018/03/01
[22:48:35.248443 2018/03/01 CST] [INFO] (prefix1:example.go) The time is now: 22:48:35 CST 2018/03/01
[14:48:35 2018/03/01 +08:00] [INFO] (example:example.go) Using UTC time stamp. Now: 22:48:35 CST 2018/03/01
[22:48:35 2018/03/01 +08:00] [INFO] (example:example.go) Using local time stamp. Now: 22:48:35 CST 2018/03/01
  • Setting UTC time zone
log.Layout().Set("utc", true)

Example

See also:

example.go