logging

package
v0.9.7-dev.2 Latest Latest
Warning

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

Go to latest
Published: Oct 8, 2026 License: GPL-3.0 Imports: 26 Imported by: 0 modules, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

Documentation

Index

Constants

View Source
const (
	// ExportScopeMachineAndCurrentUser includes machine sources and the current user's TUI logs.
	ExportScopeMachineAndCurrentUser = "machine_and_current_user"
	// ExportScopeCurrentUserOnly is the explicit TUI-only export; it never auto-degrades.
	ExportScopeCurrentUserOnly = "current_user_only"
	// ExportSourceCollected means the named source was requested and finished.
	ExportSourceCollected = "collected"
	// ExportSourceNotRequested means the named source was omitted by the caller.
	ExportSourceNotRequested = "not_requested"
	// ExportSourceUnavailable means the named source was requested but could not be read.
	ExportSourceUnavailable = "unavailable"
)
View Source
const (
	// LevelSilent disables ordinary file records, independently of severity.
	LevelSilent slog.Level = 100
	// MaxCaptureLineBytes is the per-line capture cap for mihomo stdout/stderr.
	MaxCaptureLineBytes = 256 << 10
	// MaxExportRecordBytes is the per-record export parse cap.
	MaxExportRecordBytes = 1 << 20
)

Variables

View Source
var (
	// ErrInvalidExportRequest identifies an unsupported range or destination.
	ErrInvalidExportRequest = errors.New("invalid export request")
	// ErrExportTargetExists identifies a destination that must not be overwritten.
	ErrExportTargetExists = errors.New("export target already exists")
	// ErrExportTargetChanged identifies failed destination identity or containment checks.
	ErrExportTargetChanged = errors.New("export target changed")
	// ErrNoLogLines reports that no valid records matched the selected range.
	ErrNoLogLines = errors.New("no log lines in selected range")
)

Functions

func NewDiagnosticReporter added in v0.9.3

func NewDiagnosticReporter(logger *slog.Logger, _ *Redactor) diagnostics.Reporter

NewDiagnosticReporter writes original internal causes to a file logger. The redactor argument is retained for existing owners that also use it for public fallback output; it does not alter file diagnostics.

func NewJSONHandler

func NewJSONHandler(out io.Writer, level *slog.LevelVar, component string, _ *Redactor) slog.Handler

NewJSONHandler returns a slog JSON handler that stamps component, formats time as RFC3339Nano with a numeric offset, and preserves original log content. Terminal control escaping is owned separately by terminal display adapters.

func ParseLevel

func ParseLevel(level string) (slog.Level, error)

ParseLevel converts a persisted logging level to its slog level.

func WithOperation added in v0.9.3

func WithOperation(ctx context.Context, operation OperationMetadata) context.Context

WithOperation attaches a copy of operation to a non-nil context.

Types

type Config

type Config struct {
	Level        slog.Level
	MaxSizeBytes int64
	MaxFiles     int
}

Config is the runtime logging level and rotation limits.

func BootstrapConfig

func BootstrapConfig() Config

BootstrapConfig is the conservative TUI bootstrap: debug, 100 MiB, 10 files.

func ConfigFromFields

func ConfigFromFields(level string, maxSizeMB, maxFiles int64) (Config, error)

ConfigFromFields validates persisted/API fields and converts MiB to bytes.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig is info, 10 MiB, 3 files.

type ExportPaths

type ExportPaths struct {
	LogDir    string
	ExportDir string
	DaemonLog string
	TUILog    string
	MihomoLog string
}

ExportPaths contains the private logging and default export paths.

type ExportRange

type ExportRange struct {
	Kind RangeKind
	From time.Time
	To   time.Time
}

ExportRange describes the requested closed time window.

type ExportRequest

type ExportRequest struct {
	Now        time.Time
	Range      ExportRange
	OutputPath string
	AutoNumber bool
	Paths      ExportPaths
	PrivateFS  *platform.PrivateFS

	OpenLock         func(*platform.PrivateFS, string) (platform.AdvisoryLock, error)
	EnterRecordMutex func(basePath string) func()
	Redactor         *Redactor
	OnWarning        func(error)
}

ExportRequest contains one immutable log export request.

type ExportResult

type ExportResult struct {
	Path string
}

ExportResult identifies the published archive.

func Assemble added in v0.9.3

func Assemble(ctx context.Context, request ExportRequest, scope string, sources []NamedSource, finish func(context.Context) error) (ExportResult, error)

Assemble consumes NamedSource readers, then finish, then publishes a ZIP.

func Export

func Export(ctx context.Context, request ExportRequest) (ExportResult, error)

Export preserves diagnostic content in an archive and atomically publishes it.

type FailureClass

type FailureClass string

FailureClass is a stable, rate-limited stderr category.

const (
	FailureDropped FailureClass = "dropped"
	FailureWrite   FailureClass = "write"
	FailureRotate  FailureClass = "rotate"
	FailureCleanup FailureClass = "cleanup"
)

type FailureReporter

type FailureReporter interface {
	Report(class FailureClass, err error)
}

FailureReporter records classified logging failures.

func NewFailureReporter

func NewFailureReporter(out io.Writer, redactor *Redactor, now func() time.Time) FailureReporter

NewFailureReporter writes bounded original failure details through an independent outlet.

type Group

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

Group applies one config to multiple runtimes (daemon and mihomo).

func NewGroup

func NewGroup(dir string, config Config, targets ...*Runtime) *Group

NewGroup stores dir, the initial config, and the given targets.

func (*Group) Apply

func (g *Group) Apply(ctx context.Context, cfg Config)

Apply swaps config on every target, then converges archives one by one. It must not call Runtime.Apply per target.

func (*Group) Config

func (g *Group) Config() Config

Config returns the last applied group config.

func (*Group) Dir

func (g *Group) Dir() string

Dir returns the log directory associated with the group.

type LineCaptureWriter

type LineCaptureWriter interface {
	io.WriteCloser
	Flush() error
}

LineCaptureWriter splits arbitrary stdout/stderr chunks into JSONL records.

func NewLineCaptureWriter

func NewLineCaptureWriter(logger *slog.Logger, level slog.Level, stream string) LineCaptureWriter

NewLineCaptureWriter returns a writer that logs each logical line at level with stream set. Write returns len(p), nil unless the writer is closed.

func NewMihomoCaptureWriter added in v0.9.5

func NewMihomoCaptureWriter(logger *slog.Logger, fallback slog.Level, stream string) LineCaptureWriter

NewMihomoCaptureWriter recognizes core severity while preserving raw messages.

type MachineSnapshotOptions added in v0.9.3

type MachineSnapshotOptions struct {
	PrivateFS        *platform.PrivateFS
	Paths            ExportPaths
	EnterRecordMutex func(context.Context, string) (func(), error)
	Redactor         *Redactor
}

MachineSnapshotOptions contains daemon-owned storage and writer synchronization.

type MachineSnapshotSource added in v0.9.3

type MachineSnapshotSource interface {
	Open(context.Context, SnapshotWindow) (SnapshotSet, error)
}

MachineSnapshotSource opens daemon and mihomo prefixes with no client path input.

func NewMachineSnapshotSource added in v0.9.3

func NewMachineSnapshotSource(options MachineSnapshotOptions) MachineSnapshotSource

NewMachineSnapshotSource borrows the daemon's logging filesystem.

type NamedSource added in v0.9.3

type NamedSource struct {
	ID     SourceID
	Source SnapshotSource
}

NamedSource binds an export input to its fixed archive entry.

func NamedSourcesFromSet added in v0.9.3

func NamedSourcesFromSet(set SnapshotSet) []NamedSource

NamedSourcesFromSet borrows daemon then mihomo readers from a SnapshotSet.

type OperationMetadata added in v0.9.3

type OperationMetadata = diagnostics.OperationMetadata

OperationMetadata identifies a logical operation in all diagnostic outlets.

func OperationFromContext added in v0.9.3

func OperationFromContext(ctx context.Context) (OperationMetadata, bool)

OperationFromContext returns operation metadata explicitly bound to ctx.

type RangeKind

type RangeKind string

RangeKind identifies a supported log export time window.

const (
	// RangeLast24Hours selects the 24 hours ending at export time.
	RangeLast24Hours RangeKind = "last_24h"
	// RangeLast60Minutes selects the 60 minutes ending at export time.
	RangeLast60Minutes RangeKind = "last_60m"
	// RangeBetween selects an explicit closed time interval.
	RangeBetween RangeKind = "between"
	// RangeAll selects every valid timestamped record.
	RangeAll RangeKind = "all"
)

type Redactor

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

Redactor applies immutable exact-secret and generic redaction rules to log text and attrs.

func NewRedactor

func NewRedactor(exact ...string) *Redactor

NewRedactor builds a redactor and registers optional exact secrets.

func (*Redactor) ReplaceAttr

func (r *Redactor) ReplaceAttr(groups []string, attr slog.Attr) slog.Attr

ReplaceAttr recursively redacts slog attributes. Sensitive keys and sensitive ancestor groups replace values with ***; strings, errors, and LogValuer results run through String.

func (*Redactor) ReplaceExact

func (r *Redactor) ReplaceExact(values []string)

ReplaceExact replaces the exact-secret snapshot. Empty and too-short values are dropped; remaining values are copied and sorted longest-first. Generic regexes are package-level.

func (*Redactor) RetainCredential added in v0.9.3

func (r *Redactor) RetainCredential(value string)

RetainCredential keeps a successfully loaded control credential redacted for this redactor's lifetime, including after configured secrets are replaced.

func (*Redactor) String

func (r *Redactor) String(value string) string

String redacts a free-form text value using the current rules snapshot.

func (*Redactor) Value

func (r *Redactor) Value(value any) (redacted any, changed bool)

Value recursively redacts decoded JSON values without modifying the input. The changed result is record-scoped: it reports whether any nested value was replaced or sensitive-key member omitted, regardless of the replacement count.

type RotatingWriter

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

RotatingWriter appends full JSONL records with overflow-safe rotation.

func OpenRotatingWriter

func OpenRotatingWriter(ctx context.Context, opts RotatorOptions) (*RotatingWriter, error)

OpenRotatingWriter creates the lock, converges archives, and creates the base file. The initial lock wait uses the earlier of the caller deadline and the hard write-wait bound. On failure, acquired resources are closed.

func (*RotatingWriter) Apply

func (w *RotatingWriter) Apply(ctx context.Context, cfg Config)

Apply atomically stores cfg, then waits min(ctx deadline, WriteWait) for the exclusive lock and converges archives. Lock timeout or ctx cancel skip maintenance; the swapped config is kept. After the lock is held, ReadDir and Remove are not canceled.

func (*RotatingWriter) Close

func (w *RotatingWriter) Close() error

Close closes the current write handle and lock. It does not close PrivateFS.

func (*RotatingWriter) Dropped

func (w *RotatingWriter) Dropped() uint64

Dropped returns the number of records dropped because the write lock wait failed.

func (*RotatingWriter) Write

func (w *RotatingWriter) Write(p []byte) (n int, err error)

Write appends one complete JSONL record. It takes the process mutex, then an exclusive advisory lock (WriteWait, default 250ms). After the lock it opens and Stats the base file. A lock wait failure drops the whole record.

type RotatorOptions

type RotatorOptions struct {
	BasePath  string
	Config    Config
	PrivateFS *platform.PrivateFS
	OpenLock  func(*platform.PrivateFS, string) (platform.AdvisoryLock, error)
	WriteWait time.Duration
	Reporter  FailureReporter
}

RotatorOptions opens a process-safe rotating JSONL writer.

type Runtime

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

Runtime owns a slog logger, LevelVar, and rotating writer for one log file.

func Open

func Open(ctx context.Context, opts RuntimeOptions) (*Runtime, error)

Open creates the base log file and returns a runtime. ctx cancel aborts the initial lock wait. The shared PrivateFS is not owned by the runtime.

func (*Runtime) Apply

func (r *Runtime) Apply(ctx context.Context, cfg Config)

Apply swaps level and rotator limits, then converges archives. A canceled context still completes the in-memory swap.

func (*Runtime) Close

func (r *Runtime) Close() error

Close closes the rotator, lock, and current write handle. It does not close the shared PrivateFS.

func (*Runtime) Config

func (r *Runtime) Config() Config

Config returns the current logging config.

func (*Runtime) EnterRecordMutex

func (r *Runtime) EnterRecordMutex() func()

EnterRecordMutex locks the process-local record mutex and returns unlock.

func (*Runtime) EnterRecordMutexContext added in v0.9.3

func (r *Runtime) EnterRecordMutexContext(ctx context.Context) (func(), error)

EnterRecordMutexContext acquires the same gate as logging and rotation, with cancellation while waiting. The returned release must be called exactly once.

func (*Runtime) Logger

func (r *Runtime) Logger() *slog.Logger

Logger returns the runtime slog logger.

type RuntimeOptions

type RuntimeOptions struct {
	BasePath  string
	Component string
	Config    Config
	PrivateFS *platform.PrivateFS
	OpenLock  func(*platform.PrivateFS, string) (platform.AdvisoryLock, error)
	Redactor  *Redactor
	Reporter  FailureReporter
}

RuntimeOptions opens a component-scoped JSONL logging runtime.

type SnapshotSet added in v0.9.3

type SnapshotSet interface {
	Source(SourceID) (SourceReader, error)
	Finish(context.Context) error
	Close() error
}

SnapshotSet owns both source readers, consumed in daemon then mihomo order. Finish is required before an assembler publishes any output.

type SnapshotSource added in v0.9.3

type SnapshotSource interface {
	Open(context.Context, SnapshotWindow) (SourceReader, error)
}

SnapshotSource opens a bounded prefix of one fixed log sequence.

func NewFileSnapshotSource added in v0.9.3

func NewFileSnapshotSource(id SourceID, options MachineSnapshotOptions) SnapshotSource

NewFileSnapshotSource reads one local log sequence; TUI is capped at 10 files / 1GiB.

type SnapshotWindow added in v0.9.3

type SnapshotWindow struct {
	From *time.Time
	To   time.Time
}

SnapshotWindow is an immutable closed UTC interval; nil From means no lower bound.

type SourceID added in v0.9.3

type SourceID string

SourceID identifies a fixed diagnostic stream, never a filesystem path.

const (
	// DaemonSource contains Mihari daemon diagnostics.
	DaemonSource SourceID = "daemon"
	// MihomoSource contains captured core diagnostics.
	MihomoSource SourceID = "mihomo"
	// TUISource contains only the current user's terminal diagnostics.
	TUISource SourceID = "tui"
)

type SourceReader added in v0.9.3

type SourceReader interface {
	Next(context.Context) ([]byte, bool, error)
	Finish(context.Context) (SourceStats, error)
	Close() error
}

SourceReader emits one JSON object at a time; Finish requires successful EOF. Next and Finish are called serially by the consumer.

type SourceStats added in v0.9.3

type SourceStats struct {
	Source                                 SourceID
	Lines, SkippedInvalid, Redacted, Bytes int64
	Files                                  []string
	SHA256                                 string
}

SourceStats accounts for records as emitted, with one LF counted per payload.

Jump to

Keyboard shortcuts

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