syslog.go 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  1. // +build !windows,!plan9
  2. package log
  3. import (
  4. "log/syslog"
  5. "strings"
  6. )
  7. // SyslogHandler opens a connection to the system syslog daemon by calling
  8. // syslog.New and writes all records to it.
  9. func SyslogHandler(priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
  10. wr, err := syslog.New(priority, tag)
  11. return sharedSyslog(fmtr, wr, err)
  12. }
  13. // SyslogNetHandler opens a connection to a log daemon over the network and writes
  14. // all log records to it.
  15. func SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) (Handler, error) {
  16. wr, err := syslog.Dial(net, addr, priority, tag)
  17. return sharedSyslog(fmtr, wr, err)
  18. }
  19. func sharedSyslog(fmtr Format, sysWr *syslog.Writer, err error) (Handler, error) {
  20. if err != nil {
  21. return nil, err
  22. }
  23. h := FuncHandler(func(r *Record) error {
  24. var syslogFn = sysWr.Info
  25. switch r.Lvl {
  26. case LvlCrit:
  27. syslogFn = sysWr.Crit
  28. case LvlError:
  29. syslogFn = sysWr.Err
  30. case LvlWarn:
  31. syslogFn = sysWr.Warning
  32. case LvlInfo:
  33. syslogFn = sysWr.Info
  34. case LvlDebug:
  35. syslogFn = sysWr.Debug
  36. case LvlTrace:
  37. syslogFn = func(m string) error { return nil } // There's no syslog level for trace
  38. }
  39. s := strings.TrimSpace(string(fmtr.Format(r)))
  40. return syslogFn(s)
  41. })
  42. return LazyHandler(&closingHandler{sysWr, h}), nil
  43. }
  44. func (m muster) SyslogHandler(priority syslog.Priority, tag string, fmtr Format) Handler {
  45. return must(SyslogHandler(priority, tag, fmtr))
  46. }
  47. func (m muster) SyslogNetHandler(net, addr string, priority syslog.Priority, tag string, fmtr Format) Handler {
  48. return must(SyslogNetHandler(net, addr, priority, tag, fmtr))
  49. }