logging

package
v0.8.0-alpha Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 16, 2026 License: AGPL-3.0 Imports: 36 Imported by: 0

Documentation

Overview

Package logging is the server's log: structured records in categories with their own levels, kept in memory for the viewer and written to daily files in a folder the owner chooses. See docs/LOGGING.md for how every part should use it.

Logging never takes the server down or slows it. A record is built on the caller's goroutine, put in a memory ring and a bounded queue, and written by one goroutine: when the disk is slow, full or gone the queue drops with a count instead of making anyone wait. Secrets are removed before a record is stored anywhere.

Log files stay on the server's disk. Nothing is ever uploaded; they are only seen by someone the owner sends them to.

Index

Constants

View Source
const (
	PartFlight     = "flight.log"
	PartGoroutines = "goroutines.txt"
	PartTrace      = "trace"
)

Evidence parts beside a report, by the end of their names.

View Source
const (
	StopTrayQuit       = "tray-quit"       // Quit in the tray or menu-bar icon
	StopTrayStop       = "tray-stop"       // Stop server in that menu
	StopTrayRestart    = "tray-restart"    // Restart server in that menu
	StopTrayClosed     = "tray-closed"     // the desktop closed the tray app, without a shutdown
	StopTrayGone       = "tray-gone"       // the tray app ended without saying why (it was ended, or crashed)
	StopService        = "service-stop"    // the Windows service, systemd, launchd or rc.d was told to stop
	StopShutdown       = "os-shutdown"     // the computer is shutting down or restarting
	StopLogoff         = "os-logoff"       // the person signed out
	StopInstaller      = "installer"       // an installer asked it to close
	StopUpdate         = "update"          // this server's own updater, restarting into the new version
	StopRestartSetting = "restart-setting" // a reset, restore or repair that needs a restart
	StopTimeZone       = "time-zone"       // a new time zone, which the server only takes on at start
	StopSignal         = "signal"          // SIGINT or SIGTERM: Ctrl+C, kill
	StopConsoleClosed  = "console-closed"  // its console window was closed
	StopAPI            = "api"             // an admin pressed Restart in Settings
	StopFatal          = "fatal-error"     // it couldn't carry on
)

Why a server stops, from a fixed list, so that a person reading the log, or the page that reads it for them, can always tell which it was.

View Source
const AuditKey = "audit"

AuditKey marks a record that must be kept whatever the levels and the flood limit say: a manual override of a module, a device revoked. The file and the viewer show it as the attribute audit=yes.

View Source
const CatDefault = "server"

CatDefault is the category of a message that doesn't name one.

View Source
const LevelCrash = slog.Level(12)

LevelCrash marks a recovered panic: written whatever the levels say.

View Source
const LevelOff = slog.Level(100)

LevelOff silences a category, except for crashes.

View Source
const TraceWindow = 15 * time.Second

TraceWindow is how much of the execution trace is kept, at least.

Variables

View Source
var Categories = []Category{
	{"playback", "Playback", "What is played and how: direct play or transcoding, codecs, resolution, the chosen audio and subtitle tracks. Includes titles of what you watch.", "warn"},
	{"transcode", "Transcoding", "FFmpeg: what it was asked to do, including file paths, and what it said when it stopped.", "info"},
	{"discs", "Discs", "Every step the DVD and Blu-ray navigators take: menus, buttons pressed, program chains and cells. Useful when a disc misbehaves.", "warn"},
	{"games", "Games", "Game sessions: the runner, emulator cores, controllers and the stream to the browser. Includes game titles.", "info"},
	{"tv", "Live TV", "Tuners, channels, the guide and recordings.", "info"},
	{"library", "Library scans", "Scans, metadata lookups and how files were matched. At the most detailed level, each file and folder name.", "info"},
	{"modules", "Modules", "Module helpers starting and stopping, checks for module updates and installing them.", "info"},
	{"update", "Server updates", "Checks for a new version, downloading and installing it.", "info"},
	{"remote", "Remote access", "HTTPS certificates, your router's port mapping, finding the server on the network.", "info"},
	{"auth", "Sign-ins", "Each sign-in and failed sign-in: account name, address and whether it came from home or away. Lock-outs are always recorded.", "warn"},
	{"clients", "App errors", "Errors in the web app and the apps on your devices, sent to this server: crashes, failed requests, and player and game stream errors.", "warn"},
	{"http", "Web requests", "Each request to the server: address, page, result and time taken. Sign-in tokens are removed. Failed requests are always recorded.", "warn"},
	{"sdui", "Pages and themes", "Server-driven pages: publishing and rolling back in the page editor, pages a client could not show, themes and layouts, and each profile's own changes.", "info"},
	{"modules-store", "Module store", "Installing, updating and removing modules from the store or a file, and every manual override, which is always recorded with who made it.", "info"},
	{"emulators", "Emulators", "WittyPlay's emulators: installing and checking them, the sandbox, Docker or native host, screen capture and its stream, input and settings written, BIOS and keys present, crashes with the emulator's last words, and macOS permissions.", "info"},
	{"p2p", "Peer to peer", "Direct connections between your devices and this server: the node starting and stopping, how it is reached (NAT type, port mapping, relays), devices enrolled or revoked, path changes and connection tests. Keys and invites are never written.", "info"},
	{"remotectl", "Remote control and watch parties", "Devices taking control of a player, the commands they send, watch-party rooms, how far apart the players drift and waits that timed out.", "info"},
	{"profiles", "Profiles and parental controls", "Switching profiles, what parental controls refused, screen time used and extra time given. Includes profile names.", "warn"},
	{"extras", "Karaoke, canvases and intros", "Jobs that separate vocals for karaoke, make canvases and find intros: when each starts, finishes or fails, and why.", "info"},
	{"storage", "Storage", "WittyDiagnoser's storage checks and problems reading or writing folders.", "info"},
	{"server", "Everything else", "Starting and stopping, the database, settings and anything without an area of its own.", "info"},
}

Categories, in the order the settings page shows them. Warnings and errors of every category are written unless the owner lowers it; the ones that name what you watch or who signs in say so, and stay quiet until asked.

View Source
var ErrBusy = errors.New("another search of the log files is running")

ErrBusy: someone else is searching the files. On a small machine one at a time is plenty.

View Source
var FreeSpace func(dir string) int64

FreeSpace, set by whoever can ask the system (see package sysinfo): lets a nearly full disk make logging quiet instead of making things worse.

View Source
var SessionKinds = []SessionKind{
	{"game", "A game", "game", []string{"games", "emulators"}},
	{"party", "A watch party", "party", nil},
	{"rc", "A remote-control command", "rc", nil},
	{"p2p", "A peer-to-peer connection", "p2p", []string{"p2p"}},
	{"sep", "A karaoke separation", "sep", []string{"extras"}},
	{"audit", "Audit records", "", nil},
}

SessionKinds are what the viewer's "Follow" offers.

Functions

func AddSecret

func AddSecret(v string)

AddSecret makes sure this exact value never appears in the log, wherever it turns up: an API key, a setup code. Short values are ignored, as they would blot out ordinary words, and so are repeats.

func Audit

func Audit(ctx context.Context, log *slog.Logger, msg string, args ...any)

Audit writes a record that is never silenced: not by an area set to Off, not by a module's own level, not by the flood limit. Use it for what an owner may later need to prove happened, and who did it ("by"). Secrets are still redacted.

func Begin

func Begin(kind, what string) (end func())

Begin notes that something slow has started: an outgoing call, a child process. The function it returns says it's over. Cheap, and safe to call from anywhere.

func Calls

func Calls(next http.RoundTripper, cat, source string) http.RoundTripper

Calls wraps a client's transport (nil for the default) so that every call through it is logged under cat with source saying whose it is ("lyrics", "game metadata").

func CaptureStderr

func CaptureStderr(crashDir string) string

CaptureStderr sends this process's standard error to the crash folder when nothing else keeps it. It says where it went, or "" when it was left alone. Call it before the log is set up, and give the log io.Discard rather than os.Stderr when it returns a path: the log has its own files.

func ChildExit

func ChildExit(log *slog.Logger, what string, err error, intended bool, stderr *Tail, started time.Time, attrs ...any)

ChildExit logs how a child ended, with what it said and how long it ran. The logger brings the category and session. intended means the server stopped it on purpose, which is worth only a debug line.

func CopyRedacted

func CopyRedacted(w io.Writer, p string) error

CopyRedacted writes a log file with secrets taken out again, as a bundle does.

func ExitReason

func ExitReason(err error) string

ExitReason says in words why a child stopped: its exit code, the signal that ended it, or why it couldn't start.

func Go

func Go(where string, fn func(), attrs ...any)

Go runs fn on a goroutine of its own, recovering any panic.

func InFlight

func InFlight() string

InFlight lists what's being waited for, longest first.

func IsCrashID

func IsCrashID(id string) bool

IsCrashID accepts only our own report names (never a path).

func IsLogName

func IsLogName(name string) bool

IsLogName accepts only our own file names (never a path).

func IsPart

func IsPart(part string) bool

IsPart accepts only the names of evidence parts.

func KeepSecret

func KeepSecret(v string)

KeepSecret is AddSecret for a value that lives as long as the server: its own peer-to-peer key. AddSecret keeps the newest 64, and a busy day of invites would push the oldest out.

func LevelName

func LevelName(lv slog.Level) string

LevelName is ParseLevel backwards.

func Loop

func Loop(where string, fn func(), attrs ...any)

Loop is Go for something that must keep running, such as a sweeper: after a panic it starts again, a little later each time.

func NewID

func NewID(prefix string) string

NewID makes a short ID with a prefix saying what it is for: "scan", "rec", "diag". Short enough to read, and cheap enough for every web request.

func NormalizeCat

func NormalizeCat(id string) string

NormalizeCat turns any name into a known category.

func NoteStop

func NoteStop(reason, detail, by string) bool

NoteStop says why the server is about to stop. The first reason given is the one kept: whatever asked first is what started it. It returns false if a reason was already kept.

func NoteStopIfNothingElse

func NoteStopIfNothingElse(reason, detail string) bool

NoteStopIfNothingElse is for a reason that's only a guess, such as the tray app's pipe closing: anything more exact that follows replaces it.

func NoteStopping

func NoteStopping()

NoteStopping is called as the server begins to stop. A stop while it isn't answering, or soon after, is very likely someone giving up on it: what it was doing is kept, as the watchdog may not have had the chance.

func ParseLevel

func ParseLevel(v string) (slog.Level, bool)

ParseLevel reads a level's name.

func Recover

func Recover(where string, attrs ...any)

Recover is for a defer at the top of a goroutine: a panic becomes a record with its stack and a crash report, and that goroutine ends instead of the whole server. attrs are added to the record ("session", id, "cat", "games").

defer logging.Recover("hls sweep", "cat", "transcode")

func Redact

func Redact(s string) string

Redact removes secrets from free text (URLs, command lines, headers, errors).

func ReportPanic

func ReportPanic(where string, value any, attrs ...any)

ReportPanic records a panic already recovered by the caller.

func RequestFrom

func RequestFrom(ctx context.Context) string

RequestFrom is the web request in a context, if any.

func RunningServer

func RunningServer(crashDir string) (pid int, ok bool)

RunningServer says whether a server is running on this data folder, by the marker each run leaves in its crash folder and whether that process is still alive. A marker whose process has gone is what a crash leaves, and isn't a running server.

func SanitizeLog

func SanitizeLog(w io.Writer, r io.Reader, k Known) (map[string]int, error)

SanitizeLog copies any text log, sanitized: a line of ours is handled field by field, and any other line as free text.

func ServerRunning

func ServerRunning(crashDir string) (pid int, running bool)

ServerRunning says whether another process is running as a server on the folder that holds these crash reports, for tools that mustn't change its files underneath it.

func SessionFrom

func SessionFrom(ctx context.Context) string

SessionFrom is the session in a context, if any.

func StartCrashGuard

func StartCrashGuard(dir, logDir, version string) (*CrashGuard, []Crash, error)

StartCrashGuard turns what the last run left behind into reports and arms the capture for this run. logDir is read for the last lines before a crash. It returns the reports made now; failures are logged, and never stop the server.

func StartTraceRecorder

func StartTraceRecorder() error

StartTraceRecorder starts keeping the execution trace of the last seconds. It costs a little of every goroutine switch, so it's a setting of its own.

func StartWatchdog

func StartWatchdog(ctx context.Context, log *slog.Logger, checks ...Check)

StartWatchdog watches until ctx ends. The checks are the server's own: its web address, its database. A heartbeat of the watchdog's own is added, for a process so busy that nothing gets to run.

func StopTraceRecorder

func StopTraceRecorder()

StopTraceRecorder stops it, and forgets what it held.

func TraceRecorderOn

func TraceRecorderOn() bool

TraceRecorderOn says whether the execution trace is being kept.

func Uptime

func Uptime(d time.Duration) string

Uptime is a duration as people say it: 2h38m, 4d3h, 12s.

func ValidSession

func ValidSession(id string) string

ValidSession cleans an ID that came from outside (a client's report): IDs are only ever letters, digits and a little punctuation, and not very long.

func WithRequest

func WithRequest(ctx context.Context, id string) context.Context

WithRequest ties what is logged with this context to one web request.

func WithSession

func WithSession(ctx context.Context, id string) context.Context

WithSession ties what is logged with this context to one playback, game, scan or job.

func WriteBundleDir

func WriteBundleDir(w io.Writer, dir string, g *CrashGuard, o BundleOptions) error

WriteBundleDir is WriteBundle for a folder of logs, with no server running.

func WriteTrace

func WriteTrace(w io.Writer) (int64, error)

WriteTrace writes the execution trace of the last seconds, for `go tool trace`.

Types

type Activity

type Activity struct{ Lines, Warnings, Errors int }

Activity is how much a module has logged lately.

type Attr

type Attr struct {
	K string `json:"k"`
	V string `json:"v"`
}

Attr is one key and value of a record, already cleaned.

type BundleFile

type BundleFile struct {
	Name        string
	Description string
	Data        []byte
	// Plain names the JSON keys whose text is the program's own words (a finding's title,
	// a module's name): sanitized as free text, so paths, addresses and titles inside are
	// still hidden, but the sentence stays readable. Any other key is judged by its name.
	Plain []string
}

BundleFile is something more to include.

type BundleOptions

type BundleOptions struct {
	Days     int      // how far back; 0 = 3
	Sanitize bool     // replace names, addresses, titles and paths with placeholders
	Redact   bool     // the earlier name for Sanitize; either turns it on
	MaxLogs  int64    // bytes of log text at most; 0 = 64 MB
	Known    Known    // what the server can name exactly
	Roots    []string // library folders, added to Known.Folders
	Extra    []BundleFile
	// Earlier are logs and crash reports set aside by a reset, newest first. Those from
	// within Days go in beside today's, under their copy's name.
	Earlier []Earlier
}

BundleOptions say what goes in.

type BundlePart

type BundlePart struct {
	Name        string `json:"name"`
	Description string `json:"description"`
	Size        int64  `json:"size"`
}

BundlePart is one file in the preview.

type BundlePreview

type BundlePreview struct {
	Parts    []BundlePart   `json:"parts"`
	Total    int64          `json:"total"`
	Sample   []string       `json:"sample"` // a few lines as they would appear
	Redact   bool           `json:"redact"` // the earlier name for Sanitized
	Sanitize bool           `json:"sanitize"`
	Days     int            `json:"days"`
	Scanned  int            `json:"scanned"`            // how many lines the counts come from
	Replaced map[string]int `json:"replaced,omitempty"` // how many places were changed, by kind
	Changed  []ChangedLine  `json:"changed,omitempty"`  // a few lines, before and after
}

BundlePreview is what would be in a bundle, before making it.

func PreviewDir

func PreviewDir(dir string, g *CrashGuard, o BundleOptions) BundlePreview

PreviewDir is Preview for a folder of logs, with no server running.

type Category

type Category struct {
	ID          string `json:"id"`
	Label       string `json:"label"`
	Description string `json:"description"`
	Default     string `json:"default"` // the level it starts at
}

Category is one area of the server, with its own level.

type ChangedLine

type ChangedLine struct {
	Before string `json:"before"`
	After  string `json:"after"`
}

ChangedLine shows what sanitizing does to one line.

type Check

type Check struct {
	Name string
	Run  func(ctx context.Context) error
	// Patience is how many times hangAfter it may fail before that's a hang: a database
	// busy with a long scan is slow, not stuck. 0 is once.
	Patience int
}

Check is one question the watchdog asks: nil means fine. It's given a time limit, and one that doesn't come back is a failure too.

type Crash

type Crash struct {
	ID      string    `json:"id"`
	Kind    string    `json:"kind"` // fatal, panic, unclean, hang, saved
	Time    time.Time `json:"time"`
	Summary string    `json:"summary"`
	Version string    `json:"version,omitempty"`
	Size    int64     `json:"size"`
	Seen    bool      `json:"seen"`
	// Parts are the files kept beside the report: PartFlight, PartGoroutines, PartTrace.
	Parts []string `json:"parts,omitempty"`
}

Crash describes one report.

func SaveEvidence

func SaveEvidence(kind, summary, details string) (Crash, error)

SaveEvidence writes a report of the given kind ("hang", "saved") with everything the server can say about this moment: every goroutine's stack, the flight recorder's last minutes and the execution trace, each as a file beside the report.

type CrashGuard

type CrashGuard struct {
	// contains filtered or unexported fields
}

CrashGuard is one run of the server, watched.

func OpenCrashReports

func OpenCrashReports(dir string) *CrashGuard

OpenCrashReports reads the reports in a folder without arming anything or changing any of them, for a tool running beside a server or without one.

func (*CrashGuard) Close

func (g *CrashGuard) Close()

Close: a clean shutdown. Say so, so the next start isn't worried.

func (*CrashGuard) Delete

func (g *CrashGuard) Delete(id string) error

Delete removes one report.

func (*CrashGuard) Dir

func (g *CrashGuard) Dir() string

Dir is the folder holding the reports.

func (*CrashGuard) List

func (g *CrashGuard) List() []Crash

List is every report, newest first.

func (*CrashGuard) MarkSeen

func (g *CrashGuard) MarkSeen(id string) error

MarkSeen: the owner has seen this one, so it stops being pointed out.

func (*CrashGuard) PartPath

func (g *CrashGuard) PartPath(id, part string) (string, error)

PartPath is where one part of a report is, for sending it whole.

func (*CrashGuard) Previous

func (g *CrashGuard) Previous() (LastRun, bool)

Previous is how the run before this one ended, as found at this start.

func (*CrashGuard) Read

func (g *CrashGuard) Read(id string) ([]byte, error)

Read returns one report's text.

func (*CrashGuard) SetLogDir

func (g *CrashGuard) SetLogDir(dir string)

SetLogDir notes where this run's logs are, for the report if it ends badly.

type Earlier

type Earlier struct {
	Name, Logs, Crashes string
}

Earlier is one copy a reset made: its name ("before-reset-20261102-165543"), the log folder inside it and its crash folder, either of which may be missing.

type Explanation

type Explanation struct {
	ID    string `json:"id"`
	Title string `json:"title"`
	What  string `json:"what"`
	Fix   string `json:"fix"`
}

Explanation is a failure in plain words, with what to do about it.

func Explain

func Explain(rec *Record) *Explanation

Explain finds a plain-language explanation for a record, if there is one. It looks at the message, and at what an error or a process said.

type FileInfo

type FileInfo struct {
	Name     string    `json:"name"`
	Size     int64     `json:"size"`
	Modified time.Time `json:"modified"`
}

FileInfo describes one log file.

type Filter

type Filter struct {
	MinLevel slog.Level      // 0 = Info, so use slog.LevelDebug for everything
	Cats     map[string]bool // nil = all
	Session  string          // the session or web request they belong to
	Module   string          // only what this module logged
	Kind     string          // only the sessions of one SessionKind, or audit records
	Text     string          // anywhere in the record, ignoring case
	After    uint64          // only records after this Seq: the live tail
	Before   time.Time       // only records before this: going back in time
	Limit    int             // 0 = 200
	History  bool            // look in the files too when memory runs out
}

Filter says which records a viewer wants. Everything is optional.

type Health

type Health struct {
	Writing   bool      `json:"writing"`             // lines are reaching the disk
	Error     string    `json:"error,omitempty"`     // why they aren't
	Since     time.Time `json:"since,omitzero"`      // when that started; left out while all is well
	Lost      int64     `json:"lost,omitempty"`      // lines that could not be written
	Dropped   int64     `json:"dropped,omitempty"`   // lines dropped because the disk could not keep up
	Quieted   int64     `json:"quieted,omitempty"`   // lines left out while the disk is nearly full
	LowDisk   bool      `json:"lowDisk,omitempty"`   // only warnings and errors are being written
	TotalSize int64     `json:"totalSize,omitempty"` // of all the log files
	MaxSize   int64     `json:"maxSize"`
	KeepDays  int       `json:"keepDays"`
}

Health is how the log itself is doing, for the settings page: the one place a problem with logging can be told when the log can't be written.

type Known

type Known struct {
	Users     []string
	Libraries []string
	Folders   []string // library folders, the data folder and its neighbours
	Hosts     []string // this machine's name, and the address it's reached at
	Titles    []string // what's in the libraries
}

Known is what the server can name exactly: anything here comes out wherever it turns up, including in free text no pattern would recognise.

func KnownFromDB

func KnownFromDB(ctx context.Context, q interface {
	QueryContext(ctx context.Context, query string, args ...any) (*sql.Rows, error)
}) Known

KnownFromDB reads the names a sanitized bundle should hide. A query that fails is left out: a broken database mustn't stop someone getting their logs.

type LastRun

type LastRun struct {
	PID     int       `json:"pid"`
	Version string    `json:"version"`
	Started time.Time `json:"started"`
	Ended   time.Time `json:"ended"`
	Clean   bool      `json:"clean"`
	Stop    Stop      `json:"stop"`
	// Unclean: the report made for it, and the last line it logged.
	Report  string `json:"report,omitempty"`
	LastLog string `json:"lastLog,omitempty"`
}

LastRun is how the run before this one ended, kept in last-run.json beside the crash reports, and the last runs in runs.json.

func Runs

func Runs(crashDir string) []LastRun

Runs is the last runs, newest first, for the support bundle and the log page.

func (LastRun) Summary

func (r LastRun) Summary() string

Summary is the run in one line: "stopped 14:33 (tray-quit), ran 2h38m".

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger owns the log files, the memory ring and the writer goroutine.

func New

func New(dir string, level slog.Level, console io.Writer) (*Logger, error)

New starts logging to dir (created if needed) and to console (nil = none). A folder that can't be used is not fatal: the server still runs with its log in memory and on the console, says so, and keeps trying the folder.

func (*Logger) Accepts

func (l *Logger) Accepts(id string, lv slog.Level) bool

Accepts reports whether a category keeps messages of this level at all.

func (*Logger) Close

func (l *Logger) Close()

Close writes what is left and stops.

func (*Logger) Dir

func (l *Logger) Dir() string

Dir is the folder the log files are written to.

func (*Logger) Enabled

func (l *Logger) Enabled() []string

Enabled lists the categories set to their most detailed level.

func (*Logger) Files

func (l *Logger) Files() []FileInfo

Files lists the log files, newest first.

func (*Logger) FlightRecorderOn

func (l *Logger) FlightRecorderOn() bool

FlightRecorderOn says whether the flight recorder is keeping the last minutes.

func (*Logger) Flush

func (l *Logger) Flush()

Flush writes what is queued to disk, and waits for it, for up to two seconds: a disk that has stopped answering must not stop the caller for longer.

func (*Logger) Handler

func (l *Logger) Handler() slog.Handler

Handler returns the slog handler for the server.

func (*Logger) Health

func (l *Logger) Health() Health

Health reports how the log is doing.

func (*Logger) Level

func (l *Logger) Level() slog.Level

Level is the level of messages without an area of their own.

func (*Logger) Levels

func (l *Logger) Levels() map[string]string

Levels is the current level of each category, by name.

func (*Logger) ModuleActivity

func (l *Logger) ModuleActivity() map[string]Activity

ModuleActivity counts what each module has in memory, for the settings page.

func (*Logger) ModuleEnv

func (l *Logger) ModuleEnv(id string) []string

ModuleEnv is the same settings for a helper process, which can't see this logger: what it should print, if it cares to ask. See docs/MODULES.md.

func (*Logger) On

func (l *Logger) On(id string) bool

On reports whether a category logs everyday detail (Info or lower).

func (*Logger) Preview

func (l *Logger) Preview(g *CrashGuard, o BundleOptions) BundlePreview

Preview says what WriteBundle would write.

func (*Logger) Query

func (l *Logger) Query(f Filter) (Page, error)

Query looks through the records in memory and, if asked, the files.

func (*Logger) RecordEverything

func (l *Logger) RecordEverything(d time.Duration) time.Time

RecordEverything makes every area and module as detailed as it goes, for a while, to catch a problem while it happens. It ends by itself and changes none of the owner's settings, so nobody is left with detailed logging by mistake. A duration of 0 stops it. It says when it will end.

func (*Logger) RecordingUntil

func (l *Logger) RecordingUntil() time.Time

RecordingUntil says when RecordEverything will end, if it's on.

func (*Logger) SetCategories

func (l *Logger) SetCategories(ids []string)

SetCategories turns on exactly these categories at their most detailed; the rest go back to where they start. The older way to set levels, for old settings and clients.

func (*Logger) SetCategoryLevel

func (l *Logger) SetCategoryLevel(cat string, lv slog.Level)

SetCategoryLevel changes one category's level, live.

func (*Logger) SetDir

func (l *Logger) SetDir(dir string) error

SetDir moves logging to another folder (new messages only).

func (*Logger) SetFlightRecorder

func (l *Logger) SetFlightRecorder(on bool)

SetFlightRecorder turns the flight recorder on or off. Off forgets what it held.

func (*Logger) SetFloor

func (l *Logger) SetFloor(lv slog.Level)

SetFloor makes every category at least this detailed, whatever its own level says (the -log debug flag). slog.Level above LevelOff, or LevelOff, removes it.

func (*Logger) SetLevel

func (l *Logger) SetLevel(lv slog.Level)

SetLevel sets the level of messages without an area of their own.

func (*Logger) SetLevels

func (l *Logger) SetLevels(want map[string]slog.Level)

SetLevels changes several at once; unknown names are ignored.

func (*Logger) SetModules

func (l *Logger) SetModules(want map[string]ModuleLog)

SetModules replaces how modules are logged, live. Any line that carries "module", id is then judged by its module's settings. Modules that aren't mentioned follow their area, and cost nothing extra.

func (*Logger) StdLogger

func (l *Logger) StdLogger(cat string, lv slog.Level) *log.Logger

StdLogger is for parts of the standard library that want a *log.Logger, such as http.Server's ErrorLog, whose panics and TLS errors would otherwise reach only the console.

func (*Logger) WriteBundle

func (l *Logger) WriteBundle(w io.Writer, g *CrashGuard, o BundleOptions) error

WriteBundle writes the zip. Whoever calls it streams it to the browser, so it is limited here rather than held in memory.

func (*Logger) WriteFlight

func (l *Logger) WriteFlight(w io.Writer) (int, error)

WriteFlight writes what the flight recorder holds, oldest first, as lines of a log file, and says how many.

type ModuleLog

type ModuleLog struct {
	Level  string          `json:"level,omitempty"`
	Topics map[string]bool `json:"topics,omitempty"`
}

ModuleLog is how one module is logged, on top of its area's level: a level of its own ("" follows the area) and the advanced options, or topics, turned on.

type Page

type Page struct {
	Entries []Record `json:"entries"`
	Last    uint64   `json:"last"`    // pass as After to get what comes next
	More    bool     `json:"more"`    // there is older to ask for, with Before
	Partial bool     `json:"partial"` // the files were only partly searched
	Health  *Health  `json:"health,omitempty"`
}

Page is the answer: oldest first.

type Record

type Record struct {
	Seq     uint64       `json:"seq"`
	Time    time.Time    `json:"t"`
	Lv      slog.Level   `json:"-"`
	Level   string       `json:"level"`
	Cat     string       `json:"cat"`
	Session string       `json:"session,omitempty"`
	Req     string       `json:"req,omitempty"`
	Module  string       `json:"module,omitempty"` // which module it came from, if any
	Topic   string       `json:"topic,omitempty"`  // an advanced option of that module
	Msg     string       `json:"msg"`
	Attrs   []Attr       `json:"attrs,omitempty"`
	Explain *Explanation `json:"explain,omitempty"`
	// contains filtered or unexported fields
}

Record is one log message.

func ParseLine

func ParseLine(line string) Record

ParseLine reads a line of a log file. A line that isn't in the format, from an older version say, comes back as a message of its own.

func (*Record) IsAudit

func (rec *Record) IsAudit() bool

IsAudit says whether a record was written with Audit.

type Sanitizer

type Sanitizer struct {
	// contains filtered or unexported fields
}

Sanitizer replaces what could identify someone in the text of one bundle. It isn't safe for use from several goroutines at once: a bundle is written by one.

func NewSanitizer

func NewSanitizer(k Known) *Sanitizer

NewSanitizer makes one for a bundle. This machine's name, the home folder and the name of the account it runs under are always added.

func (*Sanitizer) Attr

func (s *Sanitizer) Attr(k, v string) string

Attr hides one attribute's value, by its name and by what's in it.

func (*Sanitizer) Counts

func (s *Sanitizer) Counts() map[string]int

Counts says how many places were changed, by kind.

func (*Sanitizer) Final

func (s *Sanitizer) Final(line string) string

Final is the last look at a finished line: any known folder or name still there goes, however it got through. Single common words were never known, so it can't blot those out.

func (*Sanitizer) Record

func (s *Sanitizer) Record(rec *Record)

Record hides everything in a whole record that isn't the server's own vocabulary.

func (*Sanitizer) Text

func (s *Sanitizer) Text(v string) string

Text hides what's in free text: an error, what FFmpeg said.

type SessionKind

type SessionKind struct {
	ID     string   `json:"id"`
	Label  string   `json:"label"`
	Prefix string   `json:"prefix"` // what NewID puts in front of its IDs, if it makes them
	Cats   []string `json:"cats"`   // the areas whose records with a session belong to it
}

SessionKind is one kind of work whose records share an ID from start to end, on the server, in modules and in the apps, so the viewer can follow one of them.

type Stop

type Stop struct {
	Reason string    `json:"reason"`
	Detail string    `json:"detail,omitempty"`
	By     string    `json:"by,omitempty"` // the account, for one pressed in Settings
	At     time.Time `json:"at"`
	// contains filtered or unexported fields
}

Stop is why this run is stopping.

func StopNoted

func StopNoted() Stop

StopNoted is the reason kept, if any.

func (Stop) Words

func (s Stop) Words() string

Words is the reason in a few plain words.

type Tail

type Tail struct {
	// contains filtered or unexported fields
}

Tail is an io.Writer that keeps a bounded part of what is written to it. It never fails, so a child is never blocked or killed by its log.

func (*Tail) Empty

func (t *Tail) Empty() bool

Empty says whether anything was written.

func (*Tail) Last

func (t *Tail) Last(n int) string

Last is up to the last n bytes.

func (*Tail) String

func (t *Tail) String() string

String is what was kept, with a note of what wasn't.

func (*Tail) Write

func (t *Tail) Write(b []byte) (int, error)

Write keeps what it can.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL