]> git.giacomolli.uk - onechat/blobdiff - daemon_log.go
Order model and chat declarations
[onechat] / daemon_log.go
index 15426bcafda9319f05a8284d732413df7fb59828..f1e4b0bf4ad0c4c111a9f1f4d3b63c71b99f00bf 100644 (file)
@@ -5,8 +5,10 @@ import (
        "fmt"
        "io"
        "log/slog"
+       "os"
        "strings"
        "sync"
+       "time"
 )
 
 // DaemonLogHandler writes short event lines with ordered attributes. Copies
@@ -102,6 +104,18 @@ func (h *DaemonLogHandler) WithGroup(name string) slog.Handler {
        return &clone
 }
 
+// daemonLogger returns a logger for one daemon part. JOURNAL_STREAM selects
+// syslog priorities without a time stamp. Other output carries the standard
+// time stamp and level.
+func daemonLogger(out io.Writer, prefix string) *slog.Logger {
+       return slog.New(&DaemonLogHandler{
+               out:     out,
+               prefix:  prefix,
+               journal: os.Getenv("JOURNAL_STREAM") != "",
+               mutex:   &sync.Mutex{},
+       })
+}
+
 // daemonLogAttr resolves and writes one attribute, or keeps its cause for the
 // end of the line. Groups flatten into dotted keys and empty attributes produce
 // no text.
@@ -141,3 +155,13 @@ func daemonLogAttr(line *strings.Builder, group string, attr slog.Attr, cause *s
                fmt.Fprint(line, attr.Value.Any())
        }
 }
+
+// durationText returns d for a log line: rounded to the second, or to the
+// millisecond when it is shorter than a second.
+func durationText(d time.Duration) string {
+       if d < time.Second {
+               return d.Round(time.Millisecond).String()
+       }
+
+       return d.Round(time.Second).String()
+}