showuserlog.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. package log
  2. import (
  3. "fmt"
  4. "log/syslog"
  5. "os"
  6. "github.com/Sirupsen/logrus"
  7. logrus_syslog "github.com/Sirupsen/logrus/hooks/syslog"
  8. )
  9. // ShowuserlogHook stores all levels of logrus entries in memory until its told the RancherOS logging system is ready
  10. // then it replays them to be logged
  11. type ShowuserlogHook struct {
  12. Level logrus.Level
  13. syslogHook *logrus_syslog.SyslogHook
  14. storedEntries []*logrus.Entry
  15. appName string
  16. }
  17. // NewShowuserlogHook creates a new hook for use
  18. func NewShowuserlogHook(l logrus.Level, app string) (*ShowuserlogHook, error) {
  19. return &ShowuserlogHook{l, nil, []*logrus.Entry{}, app}, nil
  20. }
  21. // Fire is called by logrus when the Hook is active
  22. func (hook *ShowuserlogHook) Fire(entry *logrus.Entry) error {
  23. if entry.Level <= hook.Level {
  24. //if f, err := os.OpenFile("/dev/kmsg", os.O_WRONLY, 0644); err != nil {
  25. // fmt.Fprintf(f, "%s:%s: %s\n", hook.appName, entry.Level, entry.Message)
  26. // f.Close()
  27. //} else {
  28. fmt.Printf("[ ] %s:%s: %s\n", hook.appName, entry.Level, entry.Message)
  29. //}
  30. }
  31. if hook.syslogHook == nil {
  32. hook.storedEntries = append(hook.storedEntries, entry)
  33. } else {
  34. err := hook.syslogHook.Fire(entry)
  35. if err != nil {
  36. fmt.Fprintf(os.Stderr, "LOGERR: Unable to syslog.Fire %v, %v", entry, err)
  37. return err
  38. }
  39. }
  40. return nil
  41. }
  42. // Levels returns all log levels, so we can process them ourselves
  43. func (hook *ShowuserlogHook) Levels() []logrus.Level {
  44. return []logrus.Level{
  45. logrus.DebugLevel,
  46. logrus.InfoLevel,
  47. logrus.WarnLevel,
  48. logrus.ErrorLevel,
  49. logrus.FatalLevel,
  50. logrus.PanicLevel,
  51. }
  52. }
  53. // NotUsedYetLogSystemReady Set up Syslog Hook, and replay any stored entries.
  54. func (hook *ShowuserlogHook) NotUsedYetLogSystemReady() error {
  55. if hook.syslogHook == nil {
  56. h, err := logrus_syslog.NewSyslogHook("", "", syslog.LOG_INFO, "")
  57. if err != nil {
  58. logrus.Debugf("error creating SyslogHook: %v", err)
  59. return err
  60. }
  61. hook.syslogHook = h
  62. for _, entry := range hook.storedEntries {
  63. line, _ := entry.String()
  64. fmt.Printf("---- CATCHUP %s\n", line)
  65. hook.syslogHook.Fire(entry)
  66. }
  67. }
  68. return nil
  69. }