syslog.go 1.6 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465
  1. // Copyright (C) 2014 Space Monkey, Inc.
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License");
  4. // you may not use this file except in compliance with the License.
  5. // You may obtain a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS,
  11. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. // See the License for the specific language governing permissions and
  13. // limitations under the License.
  14. // +build !windows
  15. package spacelog
  16. import (
  17. "bytes"
  18. "log/syslog"
  19. )
  20. type SyslogPriority syslog.Priority
  21. // SyslogOutput is a syslog client that matches the TextOutput interface
  22. type SyslogOutput struct {
  23. w *syslog.Writer
  24. }
  25. // NewSyslogOutput returns a TextOutput object that writes to syslog using
  26. // the given facility and tag. The log level will be determined by the log
  27. // event.
  28. func NewSyslogOutput(facility SyslogPriority, tag string) (
  29. TextOutput, error) {
  30. w, err := syslog.New(syslog.Priority(facility), tag)
  31. if err != nil {
  32. return nil, err
  33. }
  34. return &SyslogOutput{w: w}, nil
  35. }
  36. func (o *SyslogOutput) Output(level LogLevel, message []byte) {
  37. level = level.Match()
  38. for _, msg := range bytes.Split(message, []byte{'\n'}) {
  39. switch level {
  40. case Critical:
  41. o.w.Crit(string(msg))
  42. case Error:
  43. o.w.Err(string(msg))
  44. case Warning:
  45. o.w.Warning(string(msg))
  46. case Notice:
  47. o.w.Notice(string(msg))
  48. case Info:
  49. o.w.Info(string(msg))
  50. case Debug:
  51. fallthrough
  52. case Trace:
  53. fallthrough
  54. default:
  55. o.w.Debug(string(msg))
  56. }
  57. }
  58. }