line.go 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  1. // Copyright (C) 2025 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package slogutil
  7. import (
  8. "bytes"
  9. "encoding/json"
  10. "fmt"
  11. "io"
  12. "log/slog"
  13. "time"
  14. )
  15. // A Line is our internal representation of a formatted log line. This is
  16. // what we present in the API and what we buffer internally.
  17. type Line struct {
  18. When time.Time `json:"when"`
  19. Message string `json:"message"`
  20. Level slog.Level `json:"level"`
  21. }
  22. func (l *Line) WriteTo(w io.Writer, f LineFormat) (int64, error) {
  23. buf := new(bytes.Buffer)
  24. if f.LevelSyslog {
  25. _, _ = fmt.Fprintf(buf, "<%d>", l.syslogPriority())
  26. }
  27. if f.TimestampFormat != "" {
  28. buf.WriteString(l.When.Format(f.TimestampFormat))
  29. buf.WriteRune(' ')
  30. }
  31. if f.LevelString {
  32. buf.WriteString(l.levelStr())
  33. buf.WriteRune(' ')
  34. }
  35. buf.WriteString(l.Message)
  36. buf.WriteRune('\n')
  37. return buf.WriteTo(w)
  38. }
  39. func (l *Line) levelStr() string {
  40. str := func(base string, val slog.Level) string {
  41. if val == 0 {
  42. return base
  43. }
  44. return fmt.Sprintf("%s%+d", base, val)
  45. }
  46. switch {
  47. case l.Level < slog.LevelInfo:
  48. return str("DBG", l.Level-slog.LevelDebug)
  49. case l.Level < slog.LevelWarn:
  50. return str("INF", l.Level-slog.LevelInfo)
  51. case l.Level < slog.LevelError:
  52. return str("WRN", l.Level-slog.LevelWarn)
  53. default:
  54. return str("ERR", l.Level-slog.LevelError)
  55. }
  56. }
  57. func (l *Line) syslogPriority() int {
  58. switch {
  59. case l.Level < slog.LevelInfo:
  60. return 7
  61. case l.Level < slog.LevelWarn:
  62. return 6
  63. case l.Level < slog.LevelError:
  64. return 4
  65. default:
  66. return 3
  67. }
  68. }
  69. func (l *Line) MarshalJSON() ([]byte, error) {
  70. // Custom marshal to get short level strings instead of default JSON serialisation
  71. return json.Marshal(map[string]any{
  72. "when": l.When,
  73. "message": l.Message,
  74. "level": l.levelStr(),
  75. })
  76. }