line.go 1.5 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  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. "encoding/json"
  9. "fmt"
  10. "io"
  11. "log/slog"
  12. "time"
  13. )
  14. // A Line is our internal representation of a formatted log line. This is
  15. // what we present in the API and what we buffer internally.
  16. type Line struct {
  17. When time.Time `json:"when"`
  18. Message string `json:"message"`
  19. Level slog.Level `json:"level"`
  20. }
  21. func (l *Line) WriteTo(w io.Writer) (int64, error) {
  22. n, err := fmt.Fprintf(w, "%s %s %s\n", l.timeStr(), l.levelStr(), l.Message)
  23. return int64(n), err
  24. }
  25. func (l *Line) timeStr() string {
  26. return l.When.Format("2006-01-02 15:04:05")
  27. }
  28. func (l *Line) levelStr() string {
  29. str := func(base string, val slog.Level) string {
  30. if val == 0 {
  31. return base
  32. }
  33. return fmt.Sprintf("%s%+d", base, val)
  34. }
  35. switch {
  36. case l.Level < slog.LevelInfo:
  37. return str("DBG", l.Level-slog.LevelDebug)
  38. case l.Level < slog.LevelWarn:
  39. return str("INF", l.Level-slog.LevelInfo)
  40. case l.Level < slog.LevelError:
  41. return str("WRN", l.Level-slog.LevelWarn)
  42. default:
  43. return str("ERR", l.Level-slog.LevelError)
  44. }
  45. }
  46. func (l *Line) MarshalJSON() ([]byte, error) {
  47. // Custom marshal to get short level strings instead of default JSON serialisation
  48. return json.Marshal(map[string]any{
  49. "when": l.When,
  50. "message": l.Message,
  51. "level": l.levelStr(),
  52. })
  53. }