Terminal logging is now coloured only on an interactive terminal

The terminal logger always coloured its text, so output piped or
redirected to a file, and the systemd journal, got escape codes. It
now colours only an interactive terminal.

The service's logs can therefore go to the journal: logging.file is
now optional for it, and the unit's comments and the README say so.
This commit is contained in:
bwilliams committed 2026-10-21 15:39:36 +01:00
1 parent 2aeb2993b0
commit 71eca2f194
4 files changed
+45 -9

No files matched your search

+30
View File
@@ -171,6 +171,36 @@ func TestLogToTerminal(t *testing.T) {
}
}
// The text is coloured on an interactive terminal only.
func TestLogToTerminalColour(t *testing.T) {
for _, interactive := range []bool{true, false} {
saveGlobals(t)
out, err := os.CreateTemp(t.TempDir(), "stdout")
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
out.Close()
})
terminal = out
isTerminal = func(*os.File) bool {
return interactive
}
LogToTerminal()
slog.Warn("hello", "key", "value")
written, err := os.ReadFile(out.Name())
if err != nil {
t.Fatal(err)
}
coloured := strings.Contains(string(written), "\x1b[")
if coloured != interactive || !strings.Contains(string(written), "hello") {
t.Errorf("interactive %v: wrote %q", interactive, written)
}
}
}
// On an interactive terminal the handler, and loggers derived from it, report
// that they write to the terminal; when stdout is a file or pipe they don't.
func TestWritesToTerminal(t *testing.T) {