logging.go 1.8 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. package config
  2. import (
  3. "errors"
  4. "strings"
  5. "maunium.net/go/maulogger/v2"
  6. as "maunium.net/go/mautrix/appservice"
  7. )
  8. type logging as.LogConfig
  9. func (l *logging) validate() error {
  10. if l.Directory == "" {
  11. l.Directory = "./logs"
  12. }
  13. if l.FileNameFormat == "" {
  14. l.FileNameFormat = "{{.Date}}-{{.Index}}.log"
  15. }
  16. if l.FileDateFormat == "" {
  17. l.FileDateFormat = "2006-01-02"
  18. }
  19. if l.FileMode == 0 {
  20. l.FileMode = 384
  21. }
  22. if l.TimestampFormat == "" {
  23. l.TimestampFormat = "Jan _2, 2006 15:04:05"
  24. }
  25. if l.RawPrintLevel == "" {
  26. l.RawPrintLevel = "debug"
  27. } else {
  28. switch strings.ToUpper(l.RawPrintLevel) {
  29. case "TRACE":
  30. l.PrintLevel = -10
  31. case "DEBUG":
  32. l.PrintLevel = maulogger.LevelDebug.Severity
  33. case "INFO":
  34. l.PrintLevel = maulogger.LevelInfo.Severity
  35. case "WARN", "WARNING":
  36. l.PrintLevel = maulogger.LevelWarn.Severity
  37. case "ERR", "ERROR":
  38. l.PrintLevel = maulogger.LevelError.Severity
  39. case "FATAL":
  40. l.PrintLevel = maulogger.LevelFatal.Severity
  41. default:
  42. return errors.New("invalid print level " + l.RawPrintLevel)
  43. }
  44. }
  45. return nil
  46. }
  47. func (l *logging) UnmarshalYAML(unmarshal func(interface{}) error) error {
  48. type rawLogging logging
  49. raw := rawLogging{}
  50. if err := unmarshal(&raw); err != nil {
  51. return err
  52. }
  53. *l = logging(raw)
  54. return l.validate()
  55. }
  56. func (cfg *Config) CreateLogger() (maulogger.Logger, error) {
  57. logger := maulogger.Create()
  58. // create an as.LogConfig from our config so we can configure the logger
  59. realLogConfig := as.LogConfig(cfg.Logging)
  60. realLogConfig.Configure(logger)
  61. // Set the default logger.
  62. maulogger.DefaultLogger = logger.(*maulogger.BasicLogger)
  63. // If we were given a filename format attempt to open the file.
  64. if cfg.Logging.FileNameFormat != "" {
  65. if err := maulogger.OpenFile(); err != nil {
  66. return nil, err
  67. }
  68. }
  69. return logger, nil
  70. }