eventlog_formatter.go 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. // Copyright 2015 The Prometheus Authors
  2. // Licensed under the Apache License, Version 2.0 (the "License");
  3. // you may not use this file except in compliance with the License.
  4. // You may obtain a copy of the License at
  5. //
  6. // http://www.apache.org/licenses/LICENSE-2.0
  7. //
  8. // Unless required by applicable law or agreed to in writing, software
  9. // distributed under the License is distributed on an "AS IS" BASIS,
  10. // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  11. // See the License for the specific language governing permissions and
  12. // limitations under the License.
  13. // +build windows
  14. package log
  15. import (
  16. "fmt"
  17. "os"
  18. "golang.org/x/sys/windows/svc/eventlog"
  19. "github.com/sirupsen/logrus"
  20. )
  21. func init() {
  22. setEventlogFormatter = func(l logger, name string, debugAsInfo bool) error {
  23. if name == "" {
  24. return fmt.Errorf("missing name parameter")
  25. }
  26. fmter, err := newEventlogger(name, debugAsInfo, l.entry.Logger.Formatter)
  27. if err != nil {
  28. fmt.Fprintf(os.Stderr, "error creating eventlog formatter: %v\n", err)
  29. l.Errorf("can't connect logger to eventlog: %v", err)
  30. return err
  31. }
  32. l.entry.Logger.Formatter = fmter
  33. return nil
  34. }
  35. }
  36. type eventlogger struct {
  37. log *eventlog.Log
  38. debugAsInfo bool
  39. wrap logrus.Formatter
  40. }
  41. func newEventlogger(name string, debugAsInfo bool, fmter logrus.Formatter) (*eventlogger, error) {
  42. logHandle, err := eventlog.Open(name)
  43. if err != nil {
  44. return nil, err
  45. }
  46. return &eventlogger{log: logHandle, debugAsInfo: debugAsInfo, wrap: fmter}, nil
  47. }
  48. func (s *eventlogger) Format(e *logrus.Entry) ([]byte, error) {
  49. data, err := s.wrap.Format(e)
  50. if err != nil {
  51. fmt.Fprintf(os.Stderr, "eventlogger: can't format entry: %v\n", err)
  52. return data, err
  53. }
  54. switch e.Level {
  55. case logrus.PanicLevel:
  56. fallthrough
  57. case logrus.FatalLevel:
  58. fallthrough
  59. case logrus.ErrorLevel:
  60. err = s.log.Error(102, e.Message)
  61. case logrus.WarnLevel:
  62. err = s.log.Warning(101, e.Message)
  63. case logrus.InfoLevel:
  64. err = s.log.Info(100, e.Message)
  65. case logrus.DebugLevel:
  66. if s.debugAsInfo {
  67. err = s.log.Info(100, e.Message)
  68. }
  69. default:
  70. err = s.log.Info(100, e.Message)
  71. }
  72. if err != nil {
  73. fmt.Fprintf(os.Stderr, "eventlogger: can't send log to eventlog: %v\n", err)
  74. }
  75. return data, err
  76. }