feat(logging): optional rotating log file

Under systemd, journald held the only copy of archied's output, and
running it by hand left no record at all -- so "where are the logs?" had
no good answer, and the dashboard had no history to show from before it
connected. [log] adds a file destination alongside stderr, with
size-based rotation and retention done in-package rather than pulling in
a dependency for a few hundred lines.

A file that cannot be opened is reported and the daemon continues on
stderr: losing the durable copy is not worth refusing to start over.

reader.go owns the on-disk format so nothing else has to parse it, and
bounds every read -- tailing keeps the newest entries within a fixed
scan window, so pointing it at a large file cannot exhaust memory.
This commit is contained in:
sam committed 2026-08-04 01:44:56 +10:00
1 parent cbe02c1e6b
commit 449c925f29
6 files changed
+797

No files matched your search

+21
View File
@@ -38,6 +38,7 @@ import (
"github.com/samcharles93/archie-core/internal/infrastructure/configuration"
"github.com/samcharles93/archie-core/internal/infrastructure/eventbus/nats"
"github.com/samcharles93/archie-core/internal/infrastructure/modelcatalog"
"github.com/samcharles93/archie-core/internal/logging"
"github.com/samcharles93/archie-core/internal/memory"
"github.com/samcharles93/archie-core/internal/memory/builtin"
"github.com/samcharles93/archie-core/internal/nell"
@@ -224,6 +225,26 @@ func run() int {
}
cfg := doc.Config
// Re-create the logger now the config is known. Everything above this
// point logs to stderr only, which is unavoidable: the log destination is
// itself configuration. A file that cannot be opened is reported and the
// daemon continues on stderr -- losing the durable copy must not take the
// daemon down with it.
fileLog, logCloser, logErr := logging.New(logging.Options{
File: cfg.Log.File,
MaxSizeMB: cfg.Log.MaxSizeMB,
Keep: cfg.Log.Keep,
Level: cfg.Log.Level,
Stderr: !cfg.Log.Quiet,
})
log = fileLog
defer func() { _ = logCloser.Close() }()
if logErr != nil {
log.Error("file logging disabled", "err", logErr)
} else if cfg.Log.File != "" {
log.Info("logging to file", "path", cfg.Log.File)
}
secrets, err := configuredSecretRegistry(&cfg, log)
if err != nil {
log.Error("configure secrets", "err", err)
+24
View File
@@ -338,6 +338,7 @@ type Config struct {
Budgets Budgets `toml:"budgets" yaml:"budgets"`
Web Web `toml:"web" yaml:"web"`
Log Log `toml:"log" yaml:"log"`
Notify Notify `toml:"notify" yaml:"notify"`
NATS NATSConfig `toml:"nats" yaml:"nats"`
Containers ContainerConfig `toml:"containers" yaml:"containers"`
@@ -484,6 +485,29 @@ type ContainerConfig struct {
Network string `toml:"network" yaml:"network"`
}
// Log configures where archied writes its logs.
//
// Without File set, output goes only to stderr -- which under systemd means
// journald holds the sole copy, and running by hand leaves no record at all.
// A file gives a durable copy independent of the supervisor, and is what lets
// the dashboard show history from before it connected.
type Log struct {
// File is the log file path. Empty disables file logging. The parent
// directory is created if missing.
File string `toml:"file" yaml:"file"`
// MaxSizeMB rotates the file once it exceeds this size. Zero uses the
// package default.
MaxSizeMB int `toml:"max_size_mb" yaml:"max_size_mb"`
// Keep is how many rotated files to retain. Zero uses the package
// default.
Keep int `toml:"keep" yaml:"keep"`
// Level is "debug", "info", "warn" or "error". Empty means info.
Level string `toml:"level" yaml:"level"`
// Quiet suppresses stderr output when a file is configured. Off by
// default so journald and an interactive terminal still see logs.
Quiet bool `toml:"quiet" yaml:"quiet"`
}
// ChatConfig configures conversational front-ends (multi-agent
// collaboration PRD, phase C -- docs/prds/multi-agent-collaboration.md).
// Empty (Telegram.Token.Key == "") disables chat entirely.
+172
View File
@@ -0,0 +1,172 @@
// Package logging builds archied's logger.
//
// archied previously wrote only to stderr, so under systemd journald held the
// sole copy and running by hand left nothing at all. A file sink gives a
// durable record independent of the supervisor, and is what lets the dashboard
// show anything from before it connected.
package logging
import (
"fmt"
"io"
"log/slog"
"os"
"path/filepath"
"strings"
"sync"
)
// Options configures the logger. The zero value is a stderr-only JSON logger
// at info level, which is what archied did before file logging existed.
type Options struct {
// File is the log file path. Empty disables file logging.
File string
// MaxSizeMB rotates the file once it exceeds this size. Zero selects
// DefaultMaxSizeMB.
MaxSizeMB int
// Keep is how many rotated files to retain. Zero selects DefaultKeep.
Keep int
// Level is "debug", "info", "warn" or "error". Empty selects info.
Level string
// Stderr also writes to stderr. Kept on by default so journald and an
// interactive terminal still see output when a file is configured.
Stderr bool
}
// Rotation defaults. Sized so a busy daemon keeps roughly a week of history
// without an unbounded file.
const (
DefaultMaxSizeMB = 20
DefaultKeep = 5
)
// New builds a logger and returns it with a closer for any file sink. The
// closer is a no-op when only stderr is in use.
//
// A file that cannot be opened is reported but never fatal: losing the
// durable copy is worse than losing the daemon, but not by enough to refuse
// to start.
func New(opts Options) (*slog.Logger, io.Closer, error) {
level := parseLevel(opts.Level)
handlerOpts := &slog.HandlerOptions{Level: level}
if opts.File == "" {
return slog.New(slog.NewJSONHandler(os.Stderr, handlerOpts)), noopCloser{}, nil
}
w, err := newRotatingFile(opts.File, opts.MaxSizeMB, opts.Keep)
if err != nil {
return slog.New(slog.NewJSONHandler(os.Stderr, handlerOpts)), noopCloser{},
fmt.Errorf("logging: open %s: %w", opts.File, err)
}
var sink io.Writer = w
if opts.Stderr {
sink = io.MultiWriter(os.Stderr, w)
}
return slog.New(slog.NewJSONHandler(sink, handlerOpts)), w, nil
}
func parseLevel(s string) slog.Level {
switch strings.ToLower(strings.TrimSpace(s)) {
case "debug":
return slog.LevelDebug
case "warn", "warning":
return slog.LevelWarn
case "error":
return slog.LevelError
default:
return slog.LevelInfo
}
}
// rotatingFile is a size-rotating io.WriteCloser.
//
// Deliberately hand-rolled rather than pulling in a rotation dependency: the
// requirement is one file, a size cap and a retention count, and that is
// materially less code than auditing and tracking a third-party module.
type rotatingFile struct {
path string
maxSize int64
keep int
mu sync.Mutex
f *os.File
size int64
}
func newRotatingFile(path string, maxSizeMB, keep int) (*rotatingFile, error) {
if maxSizeMB <= 0 {
maxSizeMB = DefaultMaxSizeMB
}
if keep <= 0 {
keep = DefaultKeep
}
if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
return nil, err
}
r := &rotatingFile{
path: path,
maxSize: int64(maxSizeMB) * 1024 * 1024,
keep: keep,
}
if err := r.open(); err != nil {
return nil, err
}
return r, nil
}
func (r *rotatingFile) open() error {
f, err := os.OpenFile(r.path, os.O_CREATE|os.O_WRONLY|os.O_APPEND, 0o640)
if err != nil {
return err
}
info, err := f.Stat()
if err != nil {
return err
}
r.f, r.size = f, info.Size()
return nil
}
func (r *rotatingFile) Write(p []byte) (int, error) {
r.mu.Lock()
defer r.mu.Unlock()
if r.size+int64(len(p)) > r.maxSize {
// A failed rotation must not lose the line: fall through and keep
// writing to the current file rather than dropping it.
_ = r.rotate()
}
n, err := r.f.Write(p)
r.size += int64(n)
return n, err
}
// rotate renames the live file to .1, shifting existing generations down and
// discarding anything past keep.
func (r *rotatingFile) rotate() error {
if err := r.f.Close(); err != nil {
return err
}
// Oldest first, so each rename lands on a free slot.
_ = os.Remove(fmt.Sprintf("%s.%d", r.path, r.keep))
for i := r.keep - 1; i >= 1; i-- {
_ = os.Rename(fmt.Sprintf("%s.%d", r.path, i), fmt.Sprintf("%s.%d", r.path, i+1))
}
_ = os.Rename(r.path, r.path+".1")
return r.open()
}
func (r *rotatingFile) Close() error {
r.mu.Lock()
defer r.mu.Unlock()
if r.f == nil {
return nil
}
return r.f.Close()
}
type noopCloser struct{}
func (noopCloser) Close() error { return nil }
+173
View File
@@ -0,0 +1,173 @@
package logging
import (
"encoding/json"
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func TestNewWritesToFile(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "archied.log")
log, closer, err := New(Options{File: path})
if err != nil {
t.Fatalf("New: %v", err)
}
log.Info("hello", "task", 42)
if err := closer.Close(); err != nil {
t.Fatalf("Close: %v", err)
}
body, err := os.ReadFile(path)
if err != nil {
t.Fatalf("read log: %v", err)
}
var entry map[string]any
if err := json.Unmarshal([]byte(strings.TrimSpace(string(body))), &entry); err != nil {
t.Fatalf("log line is not JSON: %v (%q)", err, body)
}
if entry["msg"] != "hello" {
t.Errorf("msg = %v, want hello", entry["msg"])
}
}
func TestNewCreatesParentDirectory(t *testing.T) {
path := filepath.Join(t.TempDir(), "nested", "deeper", "archied.log")
_, closer, err := New(Options{File: path})
if err != nil {
t.Fatalf("New: %v", err)
}
t.Cleanup(func() { _ = closer.Close() })
if _, err := os.Stat(path); err != nil {
t.Errorf("log file not created: %v", err)
}
}
// TestNewFallsBackWhenFileUnavailable pins that an unopenable log file
// degrades to stderr with an error, rather than leaving the daemon without a
// logger or refusing to start. Losing the durable copy must not take the
// daemon down with it.
func TestNewFallsBackWhenFileUnavailable(t *testing.T) {
// A path whose parent is a regular file cannot be created.
blocker := filepath.Join(t.TempDir(), "not-a-dir")
if err := os.WriteFile(blocker, []byte("x"), 0o600); err != nil {
t.Fatal(err)
}
log, closer, err := New(Options{File: filepath.Join(blocker, "archied.log")})
if err == nil {
t.Error("New returned nil error for an unusable path, want one reported")
}
if log == nil {
t.Fatal("New returned a nil logger; a usable logger is required even on failure")
}
log.Info("still works")
if closer == nil {
t.Fatal("New returned a nil closer")
}
if err := closer.Close(); err != nil {
t.Errorf("Close on the fallback closer: %v", err)
}
}
func TestLevelFiltering(t *testing.T) {
tests := []struct {
name string
level string
wantDebug bool
wantInfo bool
}{
{"default is info", "", false, true},
{"debug shows everything", "debug", true, true},
{"warn hides info", "warn", false, false},
{"error hides info", "error", false, false},
{"unrecognised falls back to info", "chatty", false, true},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
path := filepath.Join(t.TempDir(), "archied.log")
log, closer, err := New(Options{File: path, Level: tc.level})
if err != nil {
t.Fatalf("New: %v", err)
}
log.Debug("a-debug-line")
log.Info("an-info-line")
if err := closer.Close(); err != nil {
t.Fatal(err)
}
body, err := os.ReadFile(path)
if err != nil {
t.Fatal(err)
}
got := string(body)
if strings.Contains(got, "a-debug-line") != tc.wantDebug {
t.Errorf("debug present = %v, want %v", !tc.wantDebug, tc.wantDebug)
}
if strings.Contains(got, "an-info-line") != tc.wantInfo {
t.Errorf("info present = %v, want %v", !tc.wantInfo, tc.wantInfo)
}
})
}
}
// TestRotation pins that the file is capped and old generations are kept in
// order, so a resident daemon cannot fill the disk.
func TestRotation(t *testing.T) {
dir := t.TempDir()
path := filepath.Join(dir, "archied.log")
// 1MB cap, keep 2. Rotation is size-driven, so write past it.
w, err := newRotatingFile(path, 1, 2)
if err != nil {
t.Fatalf("newRotatingFile: %v", err)
}
line := strings.Repeat("x", 64*1024) + "\n"
for range 40 {
if _, err := w.Write([]byte(line)); err != nil {
t.Fatalf("Write: %v", err)
}
}
if err := w.Close(); err != nil {
t.Fatal(err)
}
info, err := os.Stat(path)
if err != nil {
t.Fatalf("live log missing: %v", err)
}
if info.Size() > 2*1024*1024 {
t.Errorf("live log is %d bytes, want it capped near 1MB", info.Size())
}
for i := 1; i <= 2; i++ {
if _, err := os.Stat(fmt.Sprintf("%s.%d", path, i)); err != nil {
t.Errorf("rotated file .%d missing: %v", i, err)
}
}
// Retention is honoured: nothing beyond keep survives.
if _, err := os.Stat(path + ".3"); err == nil {
t.Error("archied.log.3 exists, want retention capped at 2")
}
}
func TestRotationDefaults(t *testing.T) {
path := filepath.Join(t.TempDir(), "archied.log")
w, err := newRotatingFile(path, 0, 0)
if err != nil {
t.Fatalf("newRotatingFile: %v", err)
}
t.Cleanup(func() { _ = w.Close() })
if w.maxSize != int64(DefaultMaxSizeMB)*1024*1024 {
t.Errorf("maxSize = %d, want the %dMB default", w.maxSize, DefaultMaxSizeMB)
}
if w.keep != DefaultKeep {
t.Errorf("keep = %d, want the default %d", w.keep, DefaultKeep)
}
}
+210
View File
@@ -0,0 +1,210 @@
package logging
import (
"bufio"
"encoding/json"
"fmt"
"os"
"slices"
"strings"
"time"
)
// Entry is one decoded log line.
//
// Reading lives here rather than in the dashboard because this package owns
// the on-disk format. If the handler shape or field names change, the reader
// changes with them in the same file, and no consumer has to know slog wrote
// JSON with a "msg" key.
type Entry struct {
Time time.Time `json:"time"`
Level string `json:"level"`
Message string `json:"msg"`
// Fields carries every remaining key so structured context survives the
// round trip -- component, task id, error and anything else a call site
// attached.
Fields map[string]any `json:"fields,omitempty"`
}
// Query filters a read. The zero value returns the most recent DefaultTailLines
// entries unfiltered.
type Query struct {
// Levels restricts results to these levels (case-insensitive). Empty
// means all levels.
Levels []string
// Component matches the "component" field exactly. Empty means any.
Component string
// Contains matches the message or any field value, case-insensitively.
Contains string
// Limit caps returned entries. Zero selects DefaultTailLines; values
// above MaxTailLines are clamped.
Limit int
}
// Read bounds. A log file is unbounded input, so a request must not be able to
// pull an arbitrary amount of it into memory.
const (
DefaultTailLines = 200
MaxTailLines = 2000
// maxScanBytes caps how much of the tail is examined. Beyond this the
// result is reported as truncated rather than silently partial.
maxScanBytes = 8 << 20
)
// Result is a page of log entries, newest last.
type Result struct {
Entries []Entry `json:"entries"`
// Truncated reports that the scan hit maxScanBytes before satisfying the
// query, so older matching entries exist that were not examined.
Truncated bool `json:"truncated"`
// File is the path read, for the UI to show where this came from.
File string `json:"file"`
}
// Tail returns the most recent entries in path matching q.
//
// Entries are returned oldest-first so the UI can append newer ones from the
// live stream without reordering. A missing file is not an error: file logging
// is optional, and an empty result with a clear File value lets the caller say
// so rather than showing a failure.
func Tail(path string, q Query) (Result, error) {
res := Result{Entries: []Entry{}, File: path}
if strings.TrimSpace(path) == "" {
return res, nil
}
limit := q.Limit
if limit <= 0 {
limit = DefaultTailLines
}
limit = min(limit, MaxTailLines)
f, err := os.Open(path)
if err != nil {
if os.IsNotExist(err) {
return res, nil
}
return res, fmt.Errorf("logging: open %s: %w", path, err)
}
defer func() { _ = f.Close() }()
info, err := f.Stat()
if err != nil {
return res, fmt.Errorf("logging: stat %s: %w", path, err)
}
// Read only the tail: a long-lived daemon's log is far larger than any
// page of it, and seeking past the head keeps memory bounded.
if info.Size() > maxScanBytes {
if _, err := f.Seek(info.Size()-maxScanBytes, 0); err != nil {
return res, fmt.Errorf("logging: seek %s: %w", path, err)
}
res.Truncated = true
}
scanner := bufio.NewScanner(f)
scanner.Buffer(make([]byte, 0, 64*1024), 1024*1024)
if res.Truncated {
scanner.Scan() // discard the partial first line after seeking
}
// Ring buffer: keep only the newest `limit` matches without holding the
// whole file.
matches := make([]Entry, 0, limit)
for scanner.Scan() {
entry, ok := decode(scanner.Bytes())
if !ok || !q.matches(entry) {
continue
}
if len(matches) == limit {
matches = append(matches[:0], matches[1:]...)
res.Truncated = true
}
matches = append(matches, entry)
}
if err := scanner.Err(); err != nil {
return res, fmt.Errorf("logging: read %s: %w", path, err)
}
res.Entries = matches
return res, nil
}
// decode parses one slog JSON line, lifting the known keys out and keeping the
// rest as structured fields. A line that is not JSON is skipped: a log file may
// contain output from a subprocess that does not share our format.
func decode(line []byte) (Entry, bool) {
var raw map[string]any
if err := json.Unmarshal(line, &raw); err != nil {
return Entry{}, false
}
entry := Entry{Fields: map[string]any{}}
for k, v := range raw {
switch k {
case "time":
if s, ok := v.(string); ok {
entry.Time, _ = time.Parse(time.RFC3339Nano, s)
}
case "level":
entry.Level, _ = v.(string)
case "msg":
entry.Message, _ = v.(string)
default:
entry.Fields[k] = v
}
}
if len(entry.Fields) == 0 {
entry.Fields = nil
}
return entry, true
}
func (q Query) matches(e Entry) bool {
if len(q.Levels) > 0 && !slices.ContainsFunc(q.Levels, func(l string) bool {
return strings.EqualFold(l, e.Level)
}) {
return false
}
if q.Component != "" {
got, _ := e.Fields["component"].(string)
if !strings.EqualFold(got, q.Component) {
return false
}
}
if q.Contains != "" {
needle := strings.ToLower(q.Contains)
if strings.Contains(strings.ToLower(e.Message), needle) {
return true
}
for _, v := range e.Fields {
if strings.Contains(strings.ToLower(fmt.Sprint(v)), needle) {
return true
}
}
return false
}
return true
}
// Components returns the distinct "component" values present in the tail, so
// the UI can offer a filter built from what is actually there rather than a
// hardcoded list that drifts.
func Components(path string) ([]string, error) {
res, err := Tail(path, Query{Limit: MaxTailLines})
if err != nil {
return nil, err
}
seen := map[string]struct{}{}
out := []string{}
for _, e := range res.Entries {
if c, ok := e.Fields["component"].(string); ok && c != "" {
if _, dup := seen[c]; !dup {
seen[c] = struct{}{}
out = append(out, c)
}
}
}
slices.Sort(out)
return out, nil
}
+197
View File
@@ -0,0 +1,197 @@
package logging
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
)
func writeLog(t *testing.T, lines ...string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "archied.log")
if err := os.WriteFile(path, []byte(strings.Join(lines, "\n")+"\n"), 0o600); err != nil {
t.Fatal(err)
}
return path
}
func line(level, msg string, extra ...string) string {
var s strings.Builder
fmt.Fprintf(&s, `{"time":"2026-08-04T01:00:00Z","level":%q,"msg":%q`, level, msg)
for _, e := range extra {
s.WriteString("," + e)
}
return s.String() + "}"
}
func TestTailFilters(t *testing.T) {
path := writeLog(t,
line("INFO", "started", `"component":"daemon"`),
line("WARN", "telegram rate limited", `"component":"gateway-telegram"`),
line("ERROR", "pull failed", `"component":"container"`),
line("DEBUG", "noisy detail", `"component":"daemon"`),
)
tests := []struct {
name string
query Query
want []string
}{
{"no filter returns everything", Query{}, []string{"started", "telegram rate limited", "pull failed", "noisy detail"}},
{"single level", Query{Levels: []string{"ERROR"}}, []string{"pull failed"}},
{"several levels", Query{Levels: []string{"WARN", "ERROR"}}, []string{"telegram rate limited", "pull failed"}},
{"level match is case-insensitive", Query{Levels: []string{"error"}}, []string{"pull failed"}},
{"component", Query{Component: "daemon"}, []string{"started", "noisy detail"}},
{"text matches the message", Query{Contains: "rate"}, []string{"telegram rate limited"}},
{"text matches a field value", Query{Contains: "container"}, []string{"pull failed"}},
{"text is case-insensitive", Query{Contains: "TELEGRAM"}, []string{"telegram rate limited"}},
{"filters combine", Query{Levels: []string{"DEBUG"}, Component: "daemon"}, []string{"noisy detail"}},
{"no match is empty, not an error", Query{Contains: "nothing here"}, nil},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
res, err := Tail(path, tc.query)
if err != nil {
t.Fatalf("Tail: %v", err)
}
got := make([]string, 0, len(res.Entries))
for _, e := range res.Entries {
got = append(got, e.Message)
}
if len(got) != len(tc.want) {
t.Fatalf("got %v, want %v", got, tc.want)
}
for i := range got {
if got[i] != tc.want[i] {
t.Errorf("got %v, want %v", got, tc.want)
break
}
}
})
}
}
// TestTailOrderIsOldestFirst pins the ordering the UI depends on: history is
// rendered then live lines are appended, so history must not arrive reversed.
func TestTailOrderIsOldestFirst(t *testing.T) {
path := writeLog(t, line("INFO", "first"), line("INFO", "second"), line("INFO", "third"))
res, err := Tail(path, Query{})
if err != nil {
t.Fatal(err)
}
want := []string{"first", "second", "third"}
for i, e := range res.Entries {
if e.Message != want[i] {
t.Fatalf("entry %d = %q, want %q", i, e.Message, want[i])
}
}
}
// TestTailKeepsNewestWhenLimited pins that the limit drops the OLDEST entries.
// Truncating from the other end would show a stale window and hide whatever
// just went wrong, which is the reason anyone opens this view.
func TestTailKeepsNewestWhenLimited(t *testing.T) {
lines := make([]string, 0, 10)
for i := range 10 {
lines = append(lines, line("INFO", fmt.Sprintf("m%d", i)))
}
res, err := Tail(writeLog(t, lines...), Query{Limit: 3})
if err != nil {
t.Fatal(err)
}
if len(res.Entries) != 3 {
t.Fatalf("got %d entries, want 3", len(res.Entries))
}
for i, want := range []string{"m7", "m8", "m9"} {
if res.Entries[i].Message != want {
t.Errorf("entry %d = %q, want %q", i, res.Entries[i].Message, want)
}
}
if !res.Truncated {
t.Error("Truncated = false, want true when older entries were dropped")
}
}
func TestTailLimitIsClamped(t *testing.T) {
res, err := Tail(writeLog(t, line("INFO", "one")), Query{Limit: MaxTailLines * 10})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(res.Entries) != 1 {
t.Errorf("got %d entries, want 1", len(res.Entries))
}
}
// TestTailTolerates pins that non-JSON lines and a missing file are survivable:
// a log may carry subprocess output, and file logging is optional.
func TestTailTolerates(t *testing.T) {
t.Run("non-JSON lines are skipped", func(t *testing.T) {
path := writeLog(t, "not json at all", line("INFO", "real entry"), "}{")
res, err := Tail(path, Query{})
if err != nil {
t.Fatalf("Tail: %v", err)
}
if len(res.Entries) != 1 || res.Entries[0].Message != "real entry" {
t.Errorf("got %+v, want just the parseable entry", res.Entries)
}
})
t.Run("missing file is empty, not an error", func(t *testing.T) {
res, err := Tail(filepath.Join(t.TempDir(), "absent.log"), Query{})
if err != nil {
t.Errorf("Tail on a missing file: %v, want nil", err)
}
if len(res.Entries) != 0 {
t.Errorf("got %d entries, want 0", len(res.Entries))
}
})
t.Run("empty path is empty, not an error", func(t *testing.T) {
if _, err := Tail("", Query{}); err != nil {
t.Errorf("Tail(\"\"): %v, want nil", err)
}
})
}
func TestDecodeKeepsStructuredFields(t *testing.T) {
path := writeLog(t, line("ERROR", "pull failed", `"component":"container"`, `"err":"unauthorized"`))
res, err := Tail(path, Query{})
if err != nil {
t.Fatal(err)
}
e := res.Entries[0]
if e.Level != "ERROR" || e.Message != "pull failed" {
t.Fatalf("got level=%q msg=%q", e.Level, e.Message)
}
if e.Fields["component"] != "container" || e.Fields["err"] != "unauthorized" {
t.Errorf("fields = %v, want component and err preserved", e.Fields)
}
if e.Time.IsZero() {
t.Error("Time is zero; the timestamp was not parsed")
}
}
func TestComponents(t *testing.T) {
path := writeLog(t,
line("INFO", "a", `"component":"daemon"`),
line("INFO", "b", `"component":"gateway-telegram"`),
line("INFO", "c", `"component":"daemon"`),
line("INFO", "d"),
)
got, err := Components(path)
if err != nil {
t.Fatal(err)
}
want := []string{"daemon", "gateway-telegram"}
if len(got) != len(want) {
t.Fatalf("got %v, want %v", got, want)
}
for i := range got {
if got[i] != want[i] {
t.Errorf("got %v, want %v (sorted, deduplicated)", got, want)
}
}
}