]> git.giacomolli.uk - onechat/blobdiff - daemon_log.go
Submit root events through the local socket
[onechat] / daemon_log.go
index 15426bcafda9319f05a8284d732413df7fb59828..1ff6aa4efb5a87c6e0b5c66bc83fc5e9bba94cbe 100644 (file)
@@ -5,8 +5,10 @@ import (
        "fmt"
        "io"
        "log/slog"
        "fmt"
        "io"
        "log/slog"
+       "os"
        "strings"
        "sync"
        "strings"
        "sync"
+       "time"
 )
 
 // DaemonLogHandler writes short event lines with ordered attributes. Copies
 )
 
 // DaemonLogHandler writes short event lines with ordered attributes. Copies
@@ -136,8 +138,30 @@ func daemonLogAttr(line *strings.Builder, group string, attr slog.Attr, cause *s
        line.WriteByte('=')
 
        if attr.Value.Kind() == slog.KindDuration {
        line.WriteByte('=')
 
        if attr.Value.Kind() == slog.KindDuration {
-               line.WriteString(durationText(attr.Value.Duration()))
+               line.WriteString(daemonLogDuration(attr.Value.Duration()))
        } else {
                fmt.Fprint(line, attr.Value.Any())
        }
 }
        } else {
                fmt.Fprint(line, attr.Value.Any())
        }
 }
+
+// daemonLogDuration returns d for a log line: rounded to the second, or to the
+// millisecond when it is shorter than a second.
+func daemonLogDuration(d time.Duration) string {
+       if d < time.Second {
+               return d.Round(time.Millisecond).String()
+       }
+
+       return d.Round(time.Second).String()
+}
+
+// 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{},
+       })
+}