chore: migrate log.Printf to slog in traffic/, egress/, enrich/ and evidence/

Replace every log.Printf/log.Print call with structured slog equivalents
and swap the "log" import for "log/slog". Update test assertions that
matched the old format strings.
This commit is contained in:
SREsAreHumanToo
2026-11-22 18:27:47 -05:00
parent 38c7477c51
commit 10afb2e79a
13 changed files with 70 additions and 71 deletions
+6 -6
View File
@@ -13,7 +13,7 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"math/rand/v2"
"net"
"net/http"
@@ -68,7 +68,7 @@ func ProfileByName(name string) (p Profile, ok bool) {
return Profile{Name: "off"}, false
}
if ua := strings.TrimSpace(os.Getenv("ARTEX_TARGET_USER_AGENT")); strings.ContainsFunc(ua, unicode.IsControl) {
log.Printf("[egress] ARTEX_TARGET_USER_AGENT contains a control character; ignored")
slog.Warn("ARTEX_TARGET_USER_AGENT contains a control character, ignored")
} else {
p.UserAgent = ua
}
@@ -81,7 +81,7 @@ func ProfileFromEnv() Profile {
name := strings.TrimSpace(os.Getenv("ARTEX_NOISE_PROFILE"))
p, ok := ProfileByName(name)
if !ok && name != "" {
log.Printf("[egress] ARTEX_NOISE_PROFILE=%q is not off, quiet, balanced or aggressive; using off", name)
slog.Warn("unknown noise profile, using off", "ARTEX_NOISE_PROFILE", name)
}
return p
}
@@ -105,7 +105,7 @@ func Current() *Governor {
initCurrent.Do(func() {
g := New(ProfileFromEnv())
if current.CompareAndSwap(nil, g) {
log.Printf("[egress] noise profile: %s", g.p.Name)
slog.Info("noise profile active", "profile", g.p.Name)
}
startReporter()
})
@@ -120,7 +120,7 @@ func CurrentProfile() Profile { return Current().p }
func SetProfile(p Profile) *Governor {
g := New(p)
current.Store(g)
log.Printf("[egress] noise profile: %s", g.p.Name)
slog.Info("noise profile active", "profile", g.p.Name)
startReporter()
return g
}
@@ -135,7 +135,7 @@ func startReporter() {
defer t.Stop()
for range t.C {
for _, l := range Current().report() {
log.Print(l)
slog.Info(l)
}
}
}()
+3 -3
View File
@@ -11,7 +11,7 @@ import (
"crypto/tls"
"html"
"io"
"log"
"log/slog"
"net/http"
"net/url"
"regexp"
@@ -75,7 +75,7 @@ func New(as *db.AssetStore, proxy func() string, workers int) *Engine {
Timeout: 4 * time.Second,
})
if err != nil {
log.Printf("[enrich] dnsx init failed, DNS resolution disabled: %v", err)
slog.Warn("dnsx init failed, DNS resolution disabled", "err", err)
resolv = nil
}
e := &Engine{
@@ -146,7 +146,7 @@ func (e *Engine) enqueue(j job) {
select {
case e.jobs <- j:
default: // queue full → drop (best-effort enrichment)
log.Printf("[enrich] queue full, dropping job kind=%d id=%d", j.kind, j.id)
slog.Warn("enrich queue full, dropping job", "kind", j.kind, "id", j.id)
}
}
+2 -2
View File
@@ -10,7 +10,7 @@ import (
"fmt"
"io"
"io/fs"
"log"
"log/slog"
"os"
"path/filepath"
"slices"
@@ -443,7 +443,7 @@ func (s *Store) RunGC(ctx context.Context) {
return
case now := <-timer.C:
if err := s.Collect(ctx, now); err != nil && !errors.Is(err, context.Canceled) {
log.Printf("[evidence] cleanup failed: %v", err)
slog.Error("evidence cleanup failed", "err", err)
}
}
}
+2 -2
View File
@@ -2,7 +2,7 @@ package traffic
import (
"fmt"
"log"
"log/slog"
"net/url"
"strings"
"time"
@@ -69,7 +69,7 @@ func (t *Traffic) RecordExternal(e ExternalExchange) error {
id := fmt.Sprintf("%d-%04d", now.Unix(), n%10000)
if err := t.insertExchange(id, now.Unix(), host, method, db.TemplatePath(u.EscapedPath()), u.String(), status, respCT, len(e.RequestBody), len(e.ResponseBody), reqHead, reqB, respHead, respB); err != nil {
log.Printf("[traffic] failed to ingest %s: %v", u.String(), err)
slog.Error("failed to ingest external exchange", "url", u.String(), "err", err)
return err
}
return nil
+2 -2
View File
@@ -2,7 +2,7 @@ package traffic
import (
"context"
"log"
"log/slog"
"net/http"
"time"
@@ -62,6 +62,6 @@ func pace(f *mproxy.Flow) {
defer cancel()
host := egress.HostKey(f.Request.URL)
if err := egress.Wait(ctx, host); err != nil {
log.Printf("[traffic] pacing a Bash request to %s stopped waiting (%v); sending it unpaced", host, err)
slog.Warn("pacing request stopped waiting, sending unpaced", "host", host, "err", err)
}
}
+3 -3
View File
@@ -5,7 +5,7 @@ import (
"database/sql"
"encoding/hex"
"fmt"
"log"
"log/slog"
"os"
"path/filepath"
"strings"
@@ -64,13 +64,13 @@ func (t *Traffic) spillRawDir(data []byte, previewCap int) (preview []byte, blob
h := hex.EncodeToString(sum[:])
blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2])
if err := os.MkdirAll(blobDir, 0o700); err != nil {
log.Printf("[traffic/socks5] failed to create blob directory: %v", err)
slog.Error("failed to create blob directory", "err", err)
return append([]byte(nil), data[:previewCap]...), ""
}
blobPath := filepath.Join(blobDir, h+".bin")
if _, err := os.Stat(blobPath); os.IsNotExist(err) {
if err := writeBlobAtomic(blobDir, blobPath, h, data); err != nil {
log.Printf("[traffic/socks5] failed to write blob %s: %v", h, err)
slog.Error("failed to write blob", "hash", h, "err", err)
return append([]byte(nil), data[:previewCap]...), ""
}
}
+8 -8
View File
@@ -3,7 +3,7 @@ package traffic
import (
"database/sql"
"io"
"log"
"log/slog"
"net/http"
"net/url"
"strings"
@@ -219,7 +219,7 @@ func (t *snapTable) convertLocked(cost int64) bool {
t.tombs++
*victim = reqSnap{done: victim.done, rules: victim.rules, host: victim.host, tomb: true, reason: reasonOriginalUnavailable, ruleIDs: ids}
t.conversions.Add(1)
log.Printf("[traffic] rewrite snapshot of a request to %s (rules %v) released under pressure: its exchange will be recorded as original request unavailable", victim.host, ids)
slog.Warn("rewrite snapshot released under pressure, exchange recorded as original request unavailable", "host", victim.host, "rules", ids)
return true
}
@@ -239,7 +239,7 @@ func (t *snapTable) refuseLocked(k flowKey, e *reqSnap) {
}
if now := t.now(); now.Sub(t.lastFullLog) >= time.Minute {
t.lastFullLog = now
log.Printf("[traffic] rewrite snapshot table full: requests are sent without rewriting (%d refused, %d without a trace so far)", t.capacity.Load(), t.tombDrops.Load())
slog.Warn("rewrite snapshot table full, requests sent without rewriting", "refused", t.capacity.Load(), "without_trace", t.tombDrops.Load())
}
}
@@ -469,7 +469,7 @@ func (s *sink) Request(f *mproxy.Flow) {
host := f.Request.URL.Hostname()
defer func() {
if recover() != nil {
log.Printf("[traffic] rewrite rules stopped on a request to %s (class %s): it is sent as the client sent it", host, rewrite.ErrClassPanic)
slog.Error("rewrite rules panicked on request, sent as-is", "host", host, "class", rewrite.ErrClassPanic)
}
}()
in := rewrite.Input{Request: engineRequest(f.Request), IsBinary: rulesIsBinary}
@@ -541,7 +541,7 @@ func (s *sink) applyResponse(f *mproxy.Flow, set *rewrite.Set, hooks *HookSet, i
defer func() {
if recover() != nil {
res = rewrite.Result{}
log.Printf("[traffic] rewrite rules stopped on a response from %s (class %s): it is sent as the target sent it", f.Request.URL.Hostname(), rewrite.ErrClassPanic)
slog.Error("rewrite rules panicked on response, sent as-is", "host", f.Request.URL.Hostname(), "class", rewrite.ErrClassPanic)
}
}()
r := set.Apply(rewrite.PhaseResponse, in)
@@ -614,7 +614,7 @@ func (s *sink) applyRequestTrace(f *mproxy.Flow, set *rewrite.Set, hooks *HookSe
defer func() {
if recover() != nil {
lines = nil
log.Printf("[traffic] rewrite rules stopped on a request to %s (class %s)", f.Request.URL.Hostname(), rewrite.ErrClassPanic)
slog.Error("rewrite rules panicked on request", "host", f.Request.URL.Hostname(), "class", rewrite.ErrClassPanic)
}
}()
in := rewrite.Input{Request: req, IsBinary: rulesIsBinary}
@@ -649,7 +649,7 @@ func (s *sink) RequestError(f *mproxy.Flow, err error) {
for _, id := range ids {
snap.rules.NoteError(id, rewrite.ErrClassTransport)
}
log.Printf("[traffic] a request to %s rewritten by rules %v failed (class %s); the host stays intercepted", snap.host, ids, rewrite.ErrClassTransport)
slog.Warn("rewritten request failed, host stays intercepted", "host", snap.host, "rules", ids, "class", rewrite.ErrClassTransport)
return
}
}
@@ -675,7 +675,7 @@ func (s *sink) StreamResponseModifier(f *mproxy.Flow, in io.Reader) (out io.Read
return in
}
s.t.snaps.largeResponses.Add(1)
log.Printf("[traffic] the response to a request to %s with rewrite rules %v reached %d MiB: passed through, not recorded", snap.host, snap.appliedRuleIDs(), libraryStreamBody>>20)
slog.Warn("large response passed through, not recorded", "host", snap.host, "rules", snap.appliedRuleIDs(), "size_mib", libraryStreamBody>>20)
return in
}
+3 -3
View File
@@ -445,7 +445,7 @@ func TestRewriteTraceFailureRollsBack(t *testing.T) {
}
}
out := logs.String()
if !strings.Contains(out, "failed to record a rewritten exchange of 127.0.0.1 (writing rewrite trace; rules [7])") {
if !strings.Contains(out, "failed to record rewritten exchange") || !strings.Contains(out, "host=127.0.0.1") || !strings.Contains(out, "rules=[7]") {
t.Fatalf("log: %q", out)
}
for _, leak := range []string{"secret-path", "XYZ123", "client-path", "forced"} {
@@ -474,7 +474,7 @@ func TestRewriteRequestErrorRedactedAndCleared(t *testing.T) {
}
waitFor(t, "empty snapshot table", func() bool { e, tb := tr.snaps.counts(); return e == 0 && tb == 0 })
out := logs.String()
if !strings.Contains(out, "a request to 127.0.0.1 rewritten by rules [3] failed (class transport_error)") {
if !strings.Contains(out, "rewritten request failed") || !strings.Contains(out, "host=127.0.0.1") || !strings.Contains(out, "rules=[3]") || !strings.Contains(out, "class=transport_error") {
t.Fatalf("log: %q", out)
}
for _, leak := range []string{"XYZ123", "client-path", dead, "refused"} {
@@ -935,7 +935,7 @@ func TestRewriteSinkRecoverKeepsFlow(t *testing.T) {
if n := countRows(t, tr, "exchanges"); n != 1 {
t.Fatalf("%d exchanges", n)
}
if out := logs.String(); !strings.Contains(out, "class panic") || strings.Contains(out, "/p") {
if out := logs.String(); !strings.Contains(out, "class=panic") || strings.Contains(out, "/p") {
t.Fatalf("log %q", out)
}
}
+5 -5
View File
@@ -6,7 +6,7 @@ import (
"errors"
"fmt"
"io"
"log"
"log/slog"
"net"
"net/url"
"os"
@@ -157,7 +157,7 @@ func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) {
case "1", "true", "on", "yes":
enableUDP = true
default:
log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 UDP disabled", SOCKS5UDPEnabledEnv, rawUDP)
slog.Warn("non-boolean SOCKS5 UDP env value, leaving disabled", "env", SOCKS5UDPEnabledEnv, "value", rawUDP)
}
switch rawEnabled {
@@ -179,7 +179,7 @@ func SOCKS5ConfigFromEnv() (SOCKS5Config, bool) {
}
return SOCKS5Config{Addr: addr, EnableUDP: enableUDP}, true
default:
log.Printf("[traffic] %s=%q is not a boolean; leaving SOCKS5 disabled", SOCKS5EnabledEnv, rawEnabled)
slog.Warn("non-boolean SOCKS5 env value, leaving disabled", "env", SOCKS5EnabledEnv, "value", rawEnabled)
return SOCKS5Config{}, false
}
}
@@ -343,7 +343,7 @@ func (s *socks5Server) serve() {
if errors.As(err, &ne) && ne.Timeout() {
continue
}
log.Printf("[traffic/socks5] accept error: %v", err)
slog.Error("socks5 accept error", "err", err)
return
}
if !s.trackConn(conn) {
@@ -447,7 +447,7 @@ func (s *socks5Server) handleConn(client net.Conn) {
func (s *socks5Server) recordCapture(rec RawTCPCapture) {
if s.t != nil && s.t.db != nil {
if _, err := s.t.RecordRawTCPStream(rec, s.cfg.PreviewBytes); err != nil {
log.Printf("[traffic/socks5] failed to record raw tcp stream %s:%d: %v", rec.Host, rec.Port, err)
slog.Error("failed to record raw tcp stream", "host", rec.Host, "port", rec.Port, "err", err)
}
}
if s.cfg.OnRecord != nil {
+2 -3
View File
@@ -5,7 +5,7 @@ import (
"encoding/binary"
"errors"
"fmt"
"log"
"log/slog"
"net"
"net/url"
"strconv"
@@ -438,8 +438,7 @@ func (s *socks5Server) recordUDPCapture(rec RawUDPCapture) {
}
if s.t != nil && s.t.db != nil {
if _, err := s.t.RecordRawUDPDatagram(rec, s.cfg.UDPPreviewBytes); err != nil {
log.Printf("[traffic/socks5-udp] failed to record datagram assoc=%s dst=%s:%d: %v",
rec.AssociationID, rec.Host, rec.Port, err)
slog.Error("failed to record UDP datagram", "assoc", rec.AssociationID, "dst_host", rec.Host, "dst_port", rec.Port, "err", err)
}
}
}
+11 -11
View File
@@ -6,7 +6,7 @@ import (
"encoding/json"
"errors"
"fmt"
"log"
"log/slog"
"net/url"
"reflect"
"strings"
@@ -152,10 +152,10 @@ func (s *sink) startStream(f *mproxy.Flow, kind string) {
if rewritten, ruleIDs := appliedRules(lines); rewritten {
var re *recordError
errors.As(err, &re)
log.Printf("[traffic] failed to record a rewritten %s stream of %s (%s; rules %v)", kind, f.Request.URL.Hostname(), re.step, ruleIDs)
slog.Error("failed to record rewritten stream", "kind", kind, "host", f.Request.URL.Hostname(), "step", re.step, "rules", ruleIDs)
return
}
log.Printf("[traffic] failed to record %s stream %s: %v", kind, f.Request.URL, err)
slog.Error("failed to record stream", "kind", kind, "url", f.Request.URL.String(), "err", err)
return
}
st.id = id
@@ -200,7 +200,7 @@ func lockLib(v any) (unlock func(), ok bool) {
mu := libMutex(v)
if mu == nil {
libMutexMissing.Do(func() {
log.Printf("[traffic] go-mitmproxy stream data has no mu field; stream messages are not recorded")
slog.Warn("go-mitmproxy stream data has no mu field; stream messages are not recorded")
})
return nil, false
}
@@ -424,7 +424,7 @@ func (t *Traffic) persistStream(st *streamState, rows []streamRow) {
tx, err := t.db.Begin()
if err != nil {
log.Printf("[traffic] failed to record stream messages of %s (beginning transaction): %v", st.id, err)
slog.Error("failed to record stream messages", "exchange_id", st.id, "step", "begin tx", "err", err)
return
}
defer tx.Rollback() //nolint:errcheck // no-op once committed
@@ -436,12 +436,12 @@ func (t *Traffic) persistStream(st *streamState, rows []streamRow) {
if _, err := tx.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,event,event_id,retry,size,payload,payload_blob,truncated)
VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, st.id, p.seq, p.ts, p.direction, p.kind, p.event, p.eventID, p.retry, p.size,
inline, nullIfEmpty(p.body.hash), boolInt(p.truncated)); err != nil {
log.Printf("[traffic] failed to record stream message %d of %s: %v", p.seq, st.id, err)
slog.Error("failed to record stream message", "seq", p.seq, "exchange_id", st.id, "err", err)
return
}
if p.body.hash != "" {
if _, err := tx.Exec(`INSERT OR IGNORE INTO blob_refs(hash,exchange_id) VALUES(?,?)`, p.body.hash, st.id); err != nil {
log.Printf("[traffic] failed to record stream message %d of %s (registering blob reference): %v", p.seq, st.id, err)
slog.Error("failed to register stream message blob ref", "seq", p.seq, "exchange_id", st.id, "err", err)
return
}
}
@@ -449,12 +449,12 @@ VALUES(?,?,?,?,?,?,?,?,?,?,?,?)`, st.id, p.seq, p.ts, p.direction, p.kind, p.eve
if meta != nil {
if _, err := tx.Exec(`INSERT INTO stream_messages(exchange_id,seq,ts,direction,kind,size,payload)
VALUES(?,?,?,'meta',0,?,?)`, st.id, metaSeq, time.Now().Unix(), len(meta), meta); err != nil {
log.Printf("[traffic] failed to record stream limit marker of %s: %v", st.id, err)
slog.Error("failed to record stream limit marker", "exchange_id", st.id, "err", err)
return
}
}
if err := tx.Commit(); err != nil {
log.Printf("[traffic] failed to record stream messages of %s (committing): %v", st.id, err)
slog.Error("failed to record stream messages", "exchange_id", st.id, "step", "commit", "err", err)
}
}
@@ -493,12 +493,12 @@ func (t *Traffic) finishStream(st *streamState) {
t.wmu.Lock()
defer t.wmu.Unlock()
if _, err := t.db.Exec(`UPDATE exchanges SET req_len=?, resp_len=? WHERE id=?`, st.reqBytes, st.respBytes, st.id); err != nil {
log.Printf("[traffic] failed to record stream sizes of %s: %v", st.id, err)
slog.Error("failed to record stream sizes", "exchange_id", st.id, "err", err)
}
if st.dropped {
meta := streamMetaPayload(st)
if _, err := t.db.Exec(`UPDATE stream_messages SET payload=?, size=? WHERE exchange_id=? AND direction='meta'`, meta, len(meta), st.id); err != nil {
log.Printf("[traffic] failed to update stream limit marker of %s: %v", st.id, err)
slog.Error("failed to update stream limit marker", "exchange_id", st.id, "err", err)
}
}
}
+19 -19
View File
@@ -15,7 +15,7 @@ import (
"fmt"
"io"
"io/fs"
"log"
"log/slog"
"net"
"net/http"
"net/url"
@@ -412,7 +412,7 @@ func (t *Traffic) initIndex() error {
}
t.incrementalVacuum = mode == autoVacuumIncremental
if !t.incrementalVacuum {
log.Printf("[traffic] index database does not have incremental vacuum enabled (auto_vacuum=%d): deleting traffic will not shrink index.sqlite; run one storage compaction to convert it", mode)
slog.Warn("index database does not have incremental vacuum enabled: deleting traffic will not shrink index.sqlite; run one storage compaction to convert it", "auto_vacuum", mode)
}
if _, err := conn.ExecContext(ctx, indexSchema); err != nil {
return err
@@ -421,7 +421,7 @@ func (t *Traffic) initIndex() error {
return err
}
if _, err := conn.ExecContext(ctx, ftsSchema); err != nil {
log.Printf("[traffic] full-text index unavailable; body search will be disabled (metadata search is unaffected): %v", err)
slog.Warn("full-text index unavailable; body search will be disabled", "err", err)
return nil
}
t.fts = true
@@ -623,7 +623,7 @@ func (t *Traffic) maybePassthrough(f *mproxy.Flow, err error) {
}
until := time.Now().Add(passthroughTTL)
if _, loaded := t.pass.LoadOrStore(host, until); !loaded {
log.Printf("[traffic] MITM with %s failed, falling back to passthrough for %s (this request failed; the host connects straight to the target and is not recorded until then; the first request after the window fails again if interception still cannot handle it): %v", host, passthroughTTL, err)
slog.Warn("MITM failed, falling back to passthrough", "host", host, "ttl", passthroughTTL, "err", err)
}
}
@@ -740,10 +740,10 @@ func (t *Traffic) recordViews(rq requestView, rs responseView, lines []rewrite.T
rewritten, ruleIDs := appliedRules(lines)
fail := func(step string, err error) {
if rewritten {
log.Printf("[traffic] failed to record a rewritten exchange of %s (%s; rules %v)", host, step, ruleIDs)
slog.Error("failed to record rewritten exchange", "host", host, "step", step, "rules", ruleIDs)
return
}
log.Printf("[traffic] failed to record %s (%s): %v", url, step, err)
slog.Error("failed to record exchange", "url", url, "step", step, "err", err)
}
tx, err := t.db.Begin()
@@ -870,14 +870,14 @@ func tightenBlobPerms(root string) {
if d.IsDir() {
if info.Mode().Perm() != 0o700 {
if err := os.Chmod(path, 0o700); err != nil {
log.Printf("[traffic] failed to restrict blob directory %s: %v", path, err)
slog.Error("failed to restrict blob directory", "path", path, "err", err)
}
}
return nil
}
if info.Mode().IsRegular() && info.Mode().Perm() != 0o600 {
if err := os.Chmod(path, 0o600); err != nil {
log.Printf("[traffic] failed to restrict blob %s: %v", path, err)
slog.Error("failed to restrict blob", "path", path, "err", err)
}
}
return nil
@@ -911,20 +911,20 @@ func (t *Traffic) spillAt(body []byte, contentType string, maxInline int) stored
// the store only ever holds bodies above maxInlineBody, deduplicated by hash.
blobDir := filepath.Join(t.dir, "_blobs", "sha256", h[:2])
if err := os.MkdirAll(blobDir, 0o700); err != nil {
log.Printf("[traffic] failed to create blob directory: %v", err)
slog.Error("failed to create blob directory", "err", err)
return storedBody{inline: clipBytes(body, blobPreview), index: indexText()}
}
if err := os.Chmod(blobDir, 0o700); err != nil {
log.Printf("[traffic] failed to restrict blob directory: %v", err)
slog.Error("failed to restrict blob directory", "err", err)
}
blobPath := filepath.Join(blobDir, h+".bin")
if _, err := os.Stat(blobPath); os.IsNotExist(err) {
if err := os.WriteFile(blobPath, body, 0o600); err != nil {
log.Printf("[traffic] failed to write blob %s: %v", h, err)
slog.Error("failed to write blob", "hash", h, "err", err)
return storedBody{inline: clipBytes(body, blobPreview), index: indexText()}
}
} else if err := os.Chmod(blobPath, 0o600); err != nil {
log.Printf("[traffic] failed to restrict blob %s: %v", h, err)
slog.Error("failed to restrict blob", "hash", h, "err", err)
}
sb := storedBody{hash: h, index: indexText()}
if text {
@@ -1607,7 +1607,7 @@ func (t *Traffic) DeleteAll() (deleted int64, reclaimed int64, err error) {
if err := t.compactIndex(); err != nil {
// The deletion is already durable; compaction is disk space, not
// correctness, so it must not turn a completed purge into a failed one.
log.Printf("[traffic] failed to compact index: %v", err)
slog.Error("failed to compact index", "err", err)
return deleted, 0, nil
}
return deleted, before - t.indexBytes(), nil
@@ -1861,7 +1861,7 @@ func (t *Traffic) reapStage(stageDir string) {
}
t.reaping.Go(func() {
if err := os.RemoveAll(stageDir); err != nil {
log.Printf("[traffic] failed to clean up legacy traffic directory %s: %v", stageDir, err)
slog.Error("failed to clean up legacy traffic directory", "dir", stageDir, "err", err)
}
})
}
@@ -2215,7 +2215,7 @@ func (t *Traffic) reclaim() {
ctx := context.Background()
conn, err := t.db.Conn(ctx)
if err != nil {
log.Printf("[traffic] failed to reclaim index space (getting a connection): %v", err)
slog.Error("failed to reclaim index space", "step", "get connection", "err", err)
return
}
defer conn.Close()
@@ -2226,7 +2226,7 @@ func (t *Traffic) reclaim() {
progressed, err := t.reclaimChunk(ctx, conn, &merges)
t.wmu.Unlock()
if err != nil {
log.Printf("[traffic] failed to reclaim index space: %v", err)
slog.Error("failed to reclaim index space", "err", err)
return
}
if !progressed {
@@ -2236,11 +2236,11 @@ func (t *Traffic) reclaim() {
return // shutdown must not wait out the remaining budget
}
if step+1 >= reclaimMaxSteps {
log.Printf("[traffic] index space reclamation unfinished (used up the %d-step limit); will continue on the next deletion", reclaimMaxSteps)
slog.Info("index space reclamation unfinished, will continue on the next deletion", "reason", "step limit", "max_steps", reclaimMaxSteps)
return
}
if time.Now().After(deadline) {
log.Printf("[traffic] index space reclamation unfinished (used up the %s budget); will continue on the next deletion", reclaimBudget)
slog.Info("index space reclamation unfinished, will continue on the next deletion", "reason", "time budget", "budget", reclaimBudget)
return
}
}
@@ -2250,7 +2250,7 @@ func (t *Traffic) reclaim() {
t.wmu.Lock()
defer t.wmu.Unlock()
if _, err := conn.ExecContext(ctx, `PRAGMA wal_checkpoint(TRUNCATE)`); err != nil {
log.Printf("[traffic] failed to truncate WAL: %v", err)
slog.Error("failed to truncate WAL", "err", err)
}
})
}
+4 -4
View File
@@ -5,7 +5,7 @@ import (
"encoding/binary"
"errors"
"fmt"
"log"
"log/slog"
"net"
"net/url"
"os"
@@ -96,7 +96,7 @@ func TransparentTCPConfigFromEnv() (TransparentTCPConfig, bool) {
}
return TransparentTCPConfig{Addr: rawAddr}, true
default:
log.Printf("[traffic] %s=%q is not a boolean; leaving transparent TCP disabled", TransparentTCPEnabledEnv, rawEnabled)
slog.Warn("transparent TCP env var is not a boolean, leaving disabled", "env", TransparentTCPEnabledEnv, "value", rawEnabled)
return TransparentTCPConfig{}, false
}
}
@@ -302,7 +302,7 @@ func (s *transparentServer) serve() {
if errors.As(err, &ne) && ne.Timeout() {
continue
}
log.Printf("[traffic/transparent] accept error: %v", err)
slog.Error("transparent proxy accept error", "err", err)
return
}
if !s.trackConn(conn) {
@@ -389,7 +389,7 @@ func (s *transparentServer) handleConn(client net.Conn) {
C2SData: c2sCap.buf,
S2CData: s2cCap.buf,
}, s.cfg.PreviewBytes); err != nil {
log.Printf("[traffic/transparent] failed to record raw TCP stream %s: %v", targetAddr, err)
slog.Error("failed to record raw TCP stream", "target", targetAddr, "err", err)
}
}
}