Örjan Persson | 11cedc2 | 2014-08-25 18:39:54 | [diff] [blame] | 1 | package main |
| 2 | |
| 3 | import ( |
| 4 | "os" |
| 5 | |
| 6 | "github.com/op/go-logging" |
| 7 | ) |
| 8 | |
| 9 | var 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 Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 14 | var format = logging.MustStringFormatter( |
Örjan Persson | a800d53 | 2015-11-24 22:07:55 | [diff] [blame] | 15 | `%{color}%{time:15:04:05.000} %{shortfunc} ▶ %{level:.4s} %{id:03x}%{color:reset} %{message}`, |
Örjan Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 16 | ) |
Örjan Persson | 11cedc2 | 2014-08-25 18:39:54 | [diff] [blame] | 17 | |
| 18 | // Password is just an example type implementing the Redactor interface. Any |
| 19 | // time this is logged, the Redacted() function will be called. |
| 20 | type Password string |
| 21 | |
| 22 | func (p Password) Redacted() interface{} { |
| 23 | return logging.Redact(string(p)) |
| 24 | } |
| 25 | |
| 26 | func main() { |
Örjan Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 27 | // For demo purposes, create two backend for os.Stderr. |
Örjan Persson | 3aac294 | 2014-11-07 14:57:03 | [diff] [blame] | 28 | backend1 := logging.NewLogBackend(os.Stderr, "", 0) |
| 29 | backend2 := logging.NewLogBackend(os.Stderr, "", 0) |
Örjan Persson | 11cedc2 | 2014-08-25 18:39:54 | [diff] [blame] | 30 | |
Örjan Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 31 | // 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 Persson | 11cedc2 | 2014-08-25 18:39:54 | [diff] [blame] | 35 | |
Örjan Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 36 | // 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 Persson | 11c955a | 2015-11-24 21:24:33 | [diff] [blame] | 43 | log.Debugf("debug %s", Password("secret")) |
Örjan Persson | ece3c24 | 2014-11-07 14:51:38 | [diff] [blame] | 44 | log.Info("info") |
| 45 | log.Notice("notice") |
| 46 | log.Warning("warning") |
| 47 | log.Error("err") |
| 48 | log.Critical("crit") |
Örjan Persson | 11cedc2 | 2014-08-25 18:39:54 | [diff] [blame] | 49 | } |