| 1 | # Syslog Hooks for Logrus <img src="http://i.imgur.com/hTeVwmJ.png" width="40" height="40" alt=":walrus:" class="emoji" title=":walrus:"/> |
| 2 | |
| 3 | ## Usage |
| 4 | |
| 5 | ```go |
| 6 | import ( |
| 7 | "log/syslog" |
| 8 | "github.com/sirupsen/logrus" |
| 9 | lSyslog "github.com/sirupsen/logrus/hooks/syslog" |
| 10 | ) |
| 11 | |
| 12 | func main() { |
| 13 | log := logrus.New() |
| 14 | hook, err := lSyslog.NewSyslogHook("udp", "localhost:514", syslog.LOG_INFO, "") |
| 15 | |
| 16 | if err == nil { |
| 17 | log.Hooks.Add(hook) |
| 18 | } |
| 19 | } |
| 20 | ``` |
| 21 | |
| 22 | If you want to connect to local syslog (Ex. "/dev/log" or "/var/run/syslog" or "/var/run/log"). Just assign empty string to the first two parameters of `NewSyslogHook`. It should look like the following. |
| 23 | |
| 24 | ```go |
| 25 | import ( |
| 26 | "log/syslog" |
| 27 | "github.com/sirupsen/logrus" |
| 28 | lSyslog "github.com/sirupsen/logrus/hooks/syslog" |
| 29 | ) |
| 30 | |
| 31 | func main() { |
| 32 | log := logrus.New() |
| 33 | hook, err := lSyslog.NewSyslogHook("", "", syslog.LOG_INFO, "") |
| 34 | |
| 35 | if err == nil { |
| 36 | log.Hooks.Add(hook) |
| 37 | } |
| 38 | } |
| 39 | ``` |
| 40 | |
| 41 | ### Different log levels for local and remote logging |
| 42 | |
| 43 | By default `NewSyslogHook()` sends logs through the hook for all log levels. If you want to have |
| 44 | different log levels between local logging and syslog logging (i.e. respect the `priority` argument |
| 45 | passed to `NewSyslogHook()`), you need to implement the `logrus_syslog.SyslogHook` interface |
| 46 | overriding `Levels()` to return only the log levels you're interested on. |
| 47 | |
| 48 | The following example shows how to log at **DEBUG** level for local logging and **WARN** level for |
| 49 | syslog logging: |
| 50 | |
| 51 | ```go |
| 52 | package main |
| 53 | |
| 54 | import ( |
| 55 | "log/syslog" |
| 56 | |
| 57 | log "github.com/sirupsen/logrus" |
| 58 | logrus_syslog "github.com/sirupsen/logrus/hooks/syslog" |
| 59 | ) |
| 60 | |
| 61 | type customHook struct { |
| 62 | *logrus_syslog.SyslogHook |
| 63 | } |
| 64 | |
| 65 | func (h *customHook) Levels() []log.Level { |
| 66 | return []log.Level{log.WarnLevel} |
| 67 | } |
| 68 | |
| 69 | func main() { |
| 70 | log.SetLevel(log.DebugLevel) |
| 71 | |
| 72 | hook, err := logrus_syslog.NewSyslogHook("tcp", "localhost:5140", syslog.LOG_WARNING, "myTag") |
| 73 | if err != nil { |
| 74 | panic(err) |
| 75 | } |
| 76 | |
| 77 | log.AddHook(&customHook{hook}) |
| 78 | |
| 79 | //... |
| 80 | } |
| 81 | ``` |