blob: 9f4ddee276f3b4fb0eb01ab231c450cb1bca99e7 [file] [log] [blame]
Örjan Persson11cedc22014-08-25 18:39:541package main
2
3import (
4 "os"
5
6 "github.com/op/go-logging"
7)
8
9var log = logging.MustGetLogger("example")
10
11// Example format string. Everything except the message has a custom color
12// which is dependent on the log level. Many fields have a custom output
13// formatting too, eg. the time returns the hour down to the milli second.
Örjan Perssonece3c242014-11-07 14:51:3814var format = logging.MustStringFormatter(
Örjan Perssona800d532015-11-24 22:07:5515 `%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`,
Örjan Perssonece3c242014-11-07 14:51:3816)
Örjan Persson11cedc22014-08-25 18:39:5417
18// Password is just an example type implementing the Redactor interface. Any
19// time this is logged, the Redacted() function will be called.
20type Password string
21
22func (p Password) Redacted() interface{} {
23 return logging.Redact(string(p))
24}
25
26func main() {
Örjan Perssonece3c242014-11-07 14:51:3827 // For demo purposes, create two backend for os.Stderr.
Örjan Persson3aac2942014-11-07 14:57:0328 backend1 := logging.NewLogBackend(os.Stderr, "", 0)
29 backend2 := logging.NewLogBackend(os.Stderr, "", 0)
Örjan Persson11cedc22014-08-25 18:39:5430
Örjan Perssonece3c242014-11-07 14:51:3831 // For messages written to backend2 we want to add some additional
32 // information to the output, including the used log level and the name of
33 // the function.
34 backend2Formatter := logging.NewBackendFormatter(backend2, format)
Örjan Persson11cedc22014-08-25 18:39:5435
Örjan Perssonece3c242014-11-07 14:51:3836 // Only errors and more severe messages should be sent to backend1
37 backend1Leveled := logging.AddModuleLevel(backend1)
38 backend1Leveled.SetLevel(logging.ERROR, "")
39
40 // Set the backends to be used.
41 logging.SetBackend(backend1Leveled, backend2Formatter)
42
Örjan Persson11c955a2015-11-24 21:24:3343 log.Debugf("debug %s", Password("secret"))
Örjan Perssonece3c242014-11-07 14:51:3844 log.Info("info")
45 log.Notice("notice")
46 log.Warning("warning")
47 log.Error("err")
48 log.Critical("crit")
Örjan Persson11cedc22014-08-25 18:39:5449}