You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

55 lines
1.3 KiB

  1. // +build !windows,!nacl,!plan9
  2. package syslog
  3. import (
  4. "fmt"
  5. "log/syslog"
  6. "os"
  7. "github.com/sirupsen/logrus"
  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. }