syslog.go 1.3 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455
  1. // +build !windows,!nacl,!plan9
  2. package logrus_syslog
  3. import (
  4. "fmt"
  5. "github.com/Sirupsen/logrus"
  6. "log/syslog"
  7. "os"
  8. )
  9. // SyslogHook to send logs via syslog.
  10. type SyslogHook struct {
  11. Writer *syslog.Writer
  12. SyslogNetwork string
  13. SyslogRaddr string
  14. }
  15. // Creates a hook to be added to an instance of logger. This is called with
  16. // `hook, err := NewSyslogHook("udp", "localhost:514", syslog.LOG_DEBUG, "")`
  17. // `if err == nil { log.Hooks.Add(hook) }`
  18. func NewSyslogHook(network, raddr string, priority syslog.Priority, tag string) (*SyslogHook, error) {
  19. w, err := syslog.Dial(network, raddr, priority, tag)
  20. return &SyslogHook{w, network, raddr}, err
  21. }
  22. func (hook *SyslogHook) Fire(entry *logrus.Entry) error {
  23. line, err := entry.String()
  24. if err != nil {
  25. fmt.Fprintf(os.Stderr, "Unable to read entry, %v", err)
  26. return err
  27. }
  28. switch entry.Level {
  29. case logrus.PanicLevel:
  30. return hook.Writer.Crit(line)
  31. case logrus.FatalLevel:
  32. return hook.Writer.Crit(line)
  33. case logrus.ErrorLevel:
  34. return hook.Writer.Err(line)
  35. case logrus.WarnLevel:
  36. return hook.Writer.Warning(line)
  37. case logrus.InfoLevel:
  38. return hook.Writer.Info(line)
  39. case logrus.DebugLevel:
  40. return hook.Writer.Debug(line)
  41. default:
  42. return nil
  43. }
  44. }
  45. func (hook *SyslogHook) Levels() []logrus.Level {
  46. return logrus.AllLevels
  47. }