debuglog

package
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: Nov 12, 2026 License: GPL-3.0 Imports: 7 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

Overview

Package debuglog provides opt-in, leveled diagnostic logging for redactproxy, entirely separate from the normal operational log (startup, rules reload, errors) that always goes to stderr.

It deliberately includes REAL (pre-tokenize/post-detokenize) values. A log that only ever showed tokens would be useless for the one thing it exists for: manually verifying that real client PII is actually being caught and replaced correctly.

That means real client data sitting on disk, so three rules apply. It is opt-in only (off by default, enabled via -debug-level). The file it writes to must live outside any directory a Claude Code session running through the proxy would have reason to read (see cmd/redactproxy's placement, and its warning if -data-dir points inside the working directory). And it should be deleted once it has served its debugging purpose.

Index

Constants

View Source
const DefaultMaxLogBytes int64 = 10 << 20 // 10 MiB

DefaultMaxLogBytes is the default size threshold at which a RotatingWriter archives the current log file and starts a fresh one. "Full" tier logging carries real risk of unbounded growth (see debuglog's own package doc comment on why it logs real values at all): every request body it logs is the ENTIRE conversation history up to that point (the Messages API is stateless, so Claude Code re- sends everything on every turn), so a long session's total logged bytes grow roughly with the square of turn count, not linearly. 10 MiB keeps any one part small enough to grep/inspect comfortably while still being large enough that routine chatty traffic doesn't rotate every few requests.

Variables

This section is empty.

Functions

This section is empty.

Types

type Level

type Level int

Level is a verbosity tier. Higher levels include everything lower levels log, plus more, the conventional cumulative verbosity contract, so turning it up never loses a signal a lower level showed.

const (
	// Off disables debug logging entirely (the default).
	Off Level = iota
	// NewValues logs only the first time a real value is seen, i.e.
	// when a token is actually minted, not when an already-known value
	// is looked up again. The lowest non-off tier: "what new PII is
	// showing up in this engagement, and what did it become."
	NewValues
	// Replacements additionally logs every substitution (tokenize or
	// detokenize), not just first-time discoveries: "what's actually
	// being redacted, request by request."
	Replacements
	// Full additionally logs the entire body of every request and
	// response, both the real and the tokenized form side by side,
	// the most direct way to manually confirm redaction is correct.
	Full
)

func ParseLevel

func ParseLevel(s string) (Level, error)

ParseLevel parses a level name (case-insensitive): "off", "new", "replacements", or "full".

type Logger

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

Logger writes leveled debug events as line-delimited JSON to an underlying writer. Safe for concurrent use.

func New

func New(level Level, w io.Writer) *Logger

New builds a Logger. w is typically a file dedicated to this purpose; see cmd/redactproxy for where that file lives and the access-control reasoning behind its placement, since real values will be written here.

func (*Logger) BeginRoundTrip

func (l *Logger) BeginRoundTrip()

BeginRoundTrip marks the start of one request/response round trip; call it before logging any event for that round trip (see proxyserver.Server.ServeHTTP). If the underlying writer supports boundary-aligned rotation, this is where that check happens: doing it here, before the first event of a new round trip rather than reactively after whichever write happens to cross the size threshold, keeps a full round trip (the request's full_body entry, every replacement/new_value event, and every full_sse_frame of a streamed response) from landing split across two rotated files in the common case where the round trip as a whole is smaller than the rotation threshold. A single round trip LARGER than the threshold on its own can still get cut mid-stream by the writer's own reactive check; there's no way to know a round trip's total size in advance without buffering it, which is exactly what streaming exists to avoid.

func (*Logger) Enabled

func (l *Logger) Enabled(lvl Level) bool

Enabled reports whether lvl would actually produce output; lets a caller skip building an event (e.g. serializing a full body) when nothing would use it.

func (*Logger) FullBody

func (l *Logger) FullBody(direction, path string, real, tokenized []byte)

FullBody logs one leg of a request/response with BOTH its real and tokenized forms side by side; direction is "request" or "response", path is the HTTP path.

func (*Logger) FullSSEFrame

func (l *Logger) FullSSEFrame(path, side, eventType, data string)

FullSSEFrame logs one SSE frame of a streaming response. side is "upstream" (the tokenized wire frame as received from Anthropic, logged as-is before any detokenization) or "client" (what was actually emitted to Claude Code, real values substituted back in). These are logged independently rather than paired 1:1, since the flush logic that decides frame boundaries (see proxyserver/sse.go's SafeFlushPoint-driven buffering) can reshape client-emitted frames relative to the upstream frames they were built from. Reading the two directions as separate chronological streams is still fully sufficient to manually compare what came in against what went out.

func (*Logger) NewValue

func (l *Logger) NewValue(entityType, real, token, wireValue string)

NewValue logs that a real value of entityType was seen for the first time and minted as token, the bare stored key, i.e. the token store's canonical identity for this value (stable for the life of the engagement, independent of any particular occurrence). wireValue is the actual substituted text this specific occurrence produced on the wire (e.g. a domain token plus its preserved real suffix), what you'd actually grep for in a Full-tier body dump to find this mint event's own substitution. For a detection combining multiple lookups (e.g. an email's local part and domain), wireValue is the whole combined substitution, not isolated to just this one lookup.

func (*Logger) Replacement

func (l *Logger) Replacement(direction, entityType, real, token string)

Replacement logs one substitution. direction is "tokenize" (real seen, token substituted, outbound) or "detokenize" (token seen, real substituted back, inbound).

type RotatingWriter

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

RotatingWriter is an io.Writer that appends to a plain file at path until it reaches maxBytes, then archives the current file as a gzip-compressed part named for the moment of rotation (path + ".<timestamp>.gz") and continues writing to a fresh, empty file at path. Compression runs in the background so a large rotation doesn't stall the write that triggered it; the rename that hands the closed file off to the compression goroutine is the only synchronous rotation cost.

Parts are named by timestamp rather than a persistent sequence number, the more common convention among mature log-rotation tools (e.g. lumberjack, logrotate's own dateext option) over the simpler but less standard incrementing-integer scheme. It sidesteps a whole class of question a counter raises: what should the next number be if an operator deletes a part mid-run, or deletes the highest- numbered one and then restarts the proxy? A number resumed by scanning the directory can end up reused for entirely different content across such a gap. A timestamp has no such ambiguity: deleting any archived part, at any time, has zero effect on what later parts get named, and the name itself tells a reviewer when that slice of traffic happened without cross-referencing file mtimes. No directory scan is needed at startup either, unlike the counter scheme this replaced.

Safe for concurrent use; debuglog.Logger already serializes its own writes under one mutex, but RotatingWriter holds its own regardless so it's correct even used directly.

func NewRotatingWriter

func NewRotatingWriter(path string, maxBytes int64) (*RotatingWriter, error)

NewRotatingWriter opens (or resumes) a rotating log file at path. maxBytes <= 0 uses DefaultMaxLogBytes. Resuming means: if path already has content from a previous run, this appends to it rather than truncating, and rotates immediately if it's already at or past the threshold, so restarting redactproxy with debug logging still on never silently lets one file grow past the limit just because the size check didn't get a chance to run again until the next write.

func (*RotatingWriter) Close

func (rw *RotatingWriter) Close() error

Close closes the currently-open file, then waits (briefly; see closeWaitTimeout) for any rotation already handed off to a background compression goroutine to finish, rather than abandoning it mid-flight. Without this, a normal shutdown (SIGTERM, the wizard restarting the proxy, even just Ctrl-C) that happens to land while a rotation is compressing leaves that part as an orphaned ".tmp" file plus its uncompressed source, neither harmful nor a data-loss risk (the uncompressed original is still complete and readable), but needless clutter on every shutdown that happens to catch a rotation mid-flight, which for a long, chatty engagement session is not a rare timing coincidence. Time-bounded rather than an unconditional wait so a stuck or unusually slow compression still can't block shutdown forever, matching this writer's overall best-effort posture (see compressAndRemove's own doc comment) at the process-exit boundary instead of the per-event one.

func (*RotatingWriter) MaybeRotate

func (rw *RotatingWriter) MaybeRotate()

MaybeRotate checks the current file size and rotates now if it's at or past the threshold, the same check Write performs reactively after each write, exposed here for a caller (see debuglog.Logger.BeginRoundTrip) that wants rotation aligned to a logical boundary instead of whatever byte happened to cross the line. Also detects and recovers from the active file having been deleted out from under this writer; see reopenAfterDeletionLocked. Both checks run at the same, once-per-round-trip cadence rather than on every individual Write, deliberately: an extra stat(2) call on every full_sse_frame event (there can be hundreds in one streamed response) would be real, avoidable per-event overhead for something that only needs to be noticed within a round trip or so, not instantly.

func (*RotatingWriter) Write

func (rw *RotatingWriter) Write(p []byte) (int, error)

Jump to

Keyboard shortcuts

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