logger.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546
  1. // Copyright 2018-present the CoreDHCP Authors. All rights reserved
  2. // This source code is licensed under the MIT license found in the
  3. // LICENSE file in the root directory of this source tree.
  4. package logger
  5. import (
  6. "io"
  7. "sync"
  8. log_prefixed "github.com/chappjc/logrus-prefix"
  9. "github.com/rifflock/lfshook"
  10. "github.com/sirupsen/logrus"
  11. )
  12. var (
  13. globalLogger *logrus.Logger
  14. getLoggerMutex sync.Mutex
  15. )
  16. // GetLogger returns a configured logger instance
  17. func GetLogger(prefix string) *logrus.Entry {
  18. if prefix == "" {
  19. prefix = "<no prefix>"
  20. }
  21. if globalLogger == nil {
  22. getLoggerMutex.Lock()
  23. defer getLoggerMutex.Unlock()
  24. logger := logrus.New()
  25. logger.SetFormatter(&log_prefixed.TextFormatter{
  26. FullTimestamp: true,
  27. })
  28. globalLogger = logger
  29. }
  30. return globalLogger.WithField("prefix", prefix)
  31. }
  32. // WithFile logs to the specified file in addition to the existing output.
  33. func WithFile(log *logrus.Entry, logfile string) {
  34. log.Logger.AddHook(lfshook.NewHook(logfile, &logrus.TextFormatter{}))
  35. }
  36. // WithNoStdOutErr disables logging to stdout/stderr.
  37. func WithNoStdOutErr(log *logrus.Entry) {
  38. log.Logger.SetOutput(io.Discard)
  39. }