Skip to content

PostgreSQL backup tool with Point-In-Time-Recovery and restore verification

FEATURE (logs): Add OTLP log export, rotating file sink and secret redaction

Rostislav Dugin69e56917a1ad
diff --git a/.env.example b/.env.example
index 8a841b1d..28ff7873 100644
--- a/.env.example
+++ b/.env.example
@@ -25,8 +25,23 @@ VALKEY_PASSWORD=
VALKEY_IS_SSL=false
# logging
-VICTORIA_LOGS_URL=
-VICTORIA_LOGS_PASSWORD=
+# debug | info | warn | error
+LOG_LEVEL=info
+# Mirror logs to a rotating JSON file at <databasus-data>/databasus.log, 4 files of 5 MB
+LOG_FILE_IS_ENABLED=true
+# http:// https:// OTLP/HTTP - VictoriaLogs (HTTP only), Loki, SigNoz, Collector :4318/v1/logs
+# grpc:// grpcs:// OTLP/gRPC - Graylog 6.2+ (gRPC only), SigNoz, Collector :4317
+OPEN_TELEMETRY_URL=
+# VictoriaLogs VL-Stream-Fields=host%2Clevel,VL-Extra-Fields=env%3Dprod (its ?_* params)
+# SigNoz Cloud signoz-ingestion-key=xxx
+# Grafana Cloud Authorization=Basic%20<base64 of instanceID:token>
+# Graylog 6.2+ authorization=Bearer%20xxx
+# Datadog dd-api-key=xxx
+# New Relic api-key=xxx
+# Honeycomb x-honeycomb-team=xxx
+# Axiom Authorization=Bearer%20xxx,X-Axiom-Dataset=logs
+# Elastic Authorization=ApiKey%20xxx
+OPEN_TELEMETRY_HEADERS=
# tests
TEST_PARALLEL_WORKERS=8
diff --git a/adr/0014-otlp-log-export-and-rotating-file-sink.md b/adr/0014-otlp-log-export-and-rotating-file-sink.md
new file mode 100644
index 00000000..f15838da
--- /dev/null
+++ b/adr/0014-otlp-log-export-and-rotating-file-sink.md
@@ -0,0 +1,43 @@
+# ADR-0014: Export logs over OTLP and keep a copy on disk
+
+- **Status:** Accepted
+- **Date:** 2026-08-14
+- **Tags:** backend, observability
+
+## Context
+
+Databasus logs to stdout, which is fine for `docker logs` and useless for everything else.
+Operators want their logs in whatever they already run (Grafana, VictoriaLogs, Graylog, SigNoz)
+and when a container dies or the database gets corrupted, the logs about it should still be
+readable.
+
+## Decision
+
+Every log record goes through `log/slog` and fans out to three sinks: stdout, a rotating JSON file,
+and an OTLP exporter.
+
+**Open Telemetry** because it is the one protocol every log backend speaks. We ship to a single endpoint
+configured by the operator and let the OpenTelemetry Collector handle routing from there. If the
+remote is down, the exporter drops records instead of blocking a request.
+
+**The file** because it survives what the database does not. Audit records are written to it as
+well as to the audit table, so a corrupted or wiped database still leaves a trail on disk. The file
+sink waits a moment before dropping anything, since it is the forensic copy.
+
+**Request IDs** so the three sinks can be joined. A middleware puts a fresh UUID on every request,
+returns it as `X-Request-Id`, and stores it in the request context. Controllers pass that context
+into every service call, so any log written while handling a request carries the same ID without a
+single call site threading a logger by hand. An inbound `X-Request-Id` is ignored, otherwise a
+client could stitch its actions into someone else's trace.
+
+Audit records get a `log_type=audit` marker and ignore `LOG_LEVEL`, so raising the level never
+silences the trail. Redaction happens in the handler, not at call sites, because audit messages
+carry user emails off the machine.
+
+## Consequences
+
+### Positive
+
+- Logs land in any backend the operator already runs, with no Databasus-side integration per vendor.
+- An audit record, its access log line, and any error in between share a `request_id` everywhere.
+- The audit trail outlives the database.
\ No newline at end of file
diff --git a/adr/CLAUDE.md b/adr/CLAUDE.md
new file mode 100644
index 00000000..47b34bf0
--- /dev/null
+++ b/adr/CLAUDE.md
@@ -0,0 +1,49 @@
+# Writing ADRs
+
+ADRs live here, numbered `NNNN-slug.md`. Start from [`0000-adr-template.md`](0000-adr-template.md)
+and drop every section you don't need.
+
+## What an ADR is for
+
+Record **why** a decision was made, so nobody re-litigates it in six months.
+
+Write one only if all three hold:
+
+1. It's expensive to reverse.
+2. A future reader would look at the code and ask "why on earth like this?"
+3. There was a real alternative and we picked against it for a reason.
+
+Obvious decisions don't get an ADR.
+
+## Write the substance, not the details
+
+The code is the source of truth for *how*. The ADR is the source of truth for *why*. Never restate
+the code in prose.
+
+Keep out:
+
+- Env-var names, config keys, flags, defaults, limits
+- Function, package and type names, call chains, file layout
+- Anything you'd have to update after a rename
+
+Keep in:
+
+- The problem and the constraint that forced the decision
+- What we decided, in plain words
+- Alternatives we rejected, and why they lost
+- Consequences we're knowingly accepting
+
+Rule of thumb: if a sentence would go stale after a refactor, it belongs in the code, not here.
+
+## Style
+
+- One page. If it's longer, you're explaining the implementation.
+- Plain language. A new engineer should get it without opening the repo.
+- Present tense, stated as fact: "We export logs over OTLP", not "It was decided that...".
+- English only.
+- Name the decision in the title, not the technology: "Export logs over OTLP" beats "OpenTelemetry".
+
+## Keeping them honest
+
+An ADR is a snapshot of a decision, not living documentation. When a decision is replaced, don't
+edit history: write a new ADR and mark the old one `Superseded by ADR-NNNN`.
diff --git a/backend/CLAUDE.md b/backend/CLAUDE.md
index b48fc77d..e2433303 100644
--- a/backend/CLAUDE.md
+++ b/backend/CLAUDE.md
@@ -387,7 +387,7 @@ logger.Error(fmt.Sprintf("failed to save subscription: %v", err))
Every log line must carry enough to reconstruct one entity's history:
-- **`request_id`** — auto-generated per HTTP request by Gin middleware and echoed back in the response. Attached to every log inside an HTTP request; do not add it manually.
+- **`request_id`** — auto-generated per HTTP request by `middleware.AssignRequestID()`, echoed back as `X-Request-Id`, and carried in the request's `context.Context`. The fan-out handler attaches it to any record logged through a `...Context` method, so on the request path use `logger.InfoContext(ctx, ...)` / `ErrorContext` and pass `ctx.Request.Context()` from the controller into the service. Never set `request_id` by hand.
- **`user_id`, `database_id`, `backup_id`, `verification_id`, etc.** — attach via `logger.With(...)` at the boundary where the entity becomes known so downstream logs inherit it.
- **Background jobs / schedulers** (no HTTP request, no `request_id`): pass these inline on every log call:
- **`job_id`** — fresh UUID per execution; the correlation ID for one run.
@@ -460,7 +460,7 @@ func (c *AuditLogController) GetGlobalAuditLogs(ctx *gin.Context) {
return
}
- response, err := c.auditLogService.GetGlobalAuditLogs(user, request)
+ response, err := c.auditLogService.GetGlobalAuditLogs(ctx.Request.Context(), user, request)
if err != nil {
if err.Error() == "only administrators can view global audit logs" {
ctx.JSON(http.StatusForbidden, gin.H{"error": err.Error()})
@@ -481,6 +481,7 @@ var auditLogRepository = &AuditLogRepository{}
var auditLogService = &AuditLogService{
auditLogRepository,
logger.GetLogger(),
+ logger.GetAuditLogger(),
}
var auditLogController = &AuditLogController{auditLogService}
@@ -537,10 +538,14 @@ func (r *AuditLogRepository) Create(auditLog *AuditLog) error {
return storage.GetDb().Create(auditLog).Error
}
-func (r *AuditLogRepository) GetGlobal(limit, offset int, beforeDate *time.Time) ([]*AuditLog, error) {
+func (r *AuditLogRepository) GetGlobal(
+ ctx context.Context,
+ limit, offset int,
+ beforeDate *time.Time,
+) ([]*AuditLog, error) {
var auditLogs []*AuditLog
- query := storage.GetDb().Order("created_at DESC")
+ query := storage.GetDb().WithContext(ctx).Order("created_at DESC")
if beforeDate != nil {
query = query.Where("created_at < ?", *beforeDate)
}
@@ -557,22 +562,26 @@ func (r *AuditLogRepository) GetGlobal(limit, offset int, beforeDate *time.Time)
type AuditLogService struct {
auditLogRepository *AuditLogRepository
logger *slog.Logger
+ auditLogger *slog.Logger
}
-func (s *AuditLogService) WriteAuditLog(message string, userID, projectID *uuid.UUID) {
+func (s *AuditLogService) WriteAuditLog(ctx context.Context, entry audit_logs_models.AuditEntry) {
auditLog := &AuditLog{
- UserID: userID,
- ProjectID: projectID,
- Message: message,
+ UserID: entry.UserID,
+ ProjectID: entry.ProjectID,
+ Message: entry.Message,
CreatedAt: time.Now().UTC(),
}
+ s.auditLogger.InfoContext(ctx, entry.Message, "user_id", entry.UserID, "project_id", entry.ProjectID)
+
if err := s.auditLogRepository.Create(auditLog); err != nil {
- s.logger.Error("failed to create audit log", "error", err)
+ s.logger.ErrorContext(ctx, "failed to create audit log", "error", err)
}
}
func (s *AuditLogService) GetGlobalAuditLogs(
+ ctx context.Context,
user *user_models.User,
request *GetAuditLogsRequest,
) (*GetAuditLogsResponse, error) {
@@ -587,12 +596,12 @@ func (s *AuditLogService) GetGlobalAuditLogs(
offset := max(request.Offset, 0)
- auditLogs, err := s.auditLogRepository.GetGlobal(limit, offset, request.BeforeDate)
+ auditLogs, err := s.auditLogRepository.GetGlobal(ctx, limit, offset, request.BeforeDate)
if err != nil {
return nil, err
}
- total, err := s.auditLogRepository.CountGlobal(request.BeforeDate)
+ total, err := s.auditLogRepository.CountGlobal(ctx, request.BeforeDate)
if err != nil {
return nil, err
}
diff --git a/backend/go.mod b/backend/go.mod
index 295dd72c..90015d7b 100644
--- a/backend/go.mod
+++ b/backend/go.mod
@@ -29,7 +29,14 @@ require (
github.com/testcontainers/testcontainers-go v0.42.0
github.com/valkey-io/valkey-go v1.0.70
go.mongodb.org/mongo-driver v1.17.9
- golang.org/x/crypto v0.52.0
+ go.opentelemetry.io/contrib/bridges/otelslog v0.20.0
+ go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0
+ go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.21.0
+ go.opentelemetry.io/otel/sdk v1.45.0
+ go.opentelemetry.io/otel/sdk/log v0.21.0
+ go.opentelemetry.io/proto/otlp v1.11.0
+ golang.org/x/crypto v0.54.0
+ gopkg.in/natefinch/lumberjack.v2 v2.2.1
gorm.io/driver/postgres v1.5.11
gorm.io/gorm v1.26.1
)
@@ -90,6 +97,7 @@ require (
github.com/buger/jsonparser v1.1.2 // indirect
github.com/calebcase/tmpfile v1.0.3 // indirect
github.com/cenkalti/backoff/v4 v4.3.0 // indirect
+ github.com/cenkalti/backoff/v5 v5.0.3 // indirect
github.com/cespare/xxhash/v2 v2.3.0 // indirect
github.com/chilts/sid v0.0.0-20190607042430-660e94789ec9 // indirect
github.com/clipperhouse/uax29/v2 v2.7.0 // indirect
@@ -129,6 +137,7 @@ require (
github.com/golang/snappy v0.0.4 // indirect
github.com/google/btree v1.1.3 // indirect
github.com/gorilla/schema v1.4.1 // indirect
+ github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 // indirect
github.com/hashicorp/errwrap v1.1.0 // indirect
github.com/hashicorp/go-cleanhttp v0.5.2 // indirect
github.com/hashicorp/go-multierror v1.1.1 // indirect
@@ -211,13 +220,14 @@ require (
github.com/zeebo/errs v1.4.0 // indirect
github.com/zeebo/xxh3 v1.1.0 // indirect
go.etcd.io/bbolt v1.4.3 // indirect
+ go.opentelemetry.io/otel/log v0.21.0 // indirect
go.yaml.in/yaml/v2 v2.4.3 // indirect
go.yaml.in/yaml/v3 v3.0.4 // indirect
golang.org/x/exp v0.0.0-20260410095643-746e56fc9e2f // indirect
golang.org/x/image v0.41.0 // indirect
- golang.org/x/term v0.43.0 // indirect
+ golang.org/x/term v0.45.0 // indirect
golang.org/x/time v0.15.0 // indirect
- gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect
+ google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d // indirect
gopkg.in/validator.v2 v2.0.1 // indirect
moul.io/http2curl/v2 v2.3.0 // indirect
sigs.k8s.io/yaml v1.6.0 // indirect
@@ -238,8 +248,8 @@ require (
github.com/googleapis/enterprise-certificate-proxy v0.3.14 // indirect
github.com/googleapis/gax-go/v2 v2.21.0 // indirect
github.com/hirochachacha/go-smb2 v1.1.0
- google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 // indirect
- google.golang.org/grpc v1.80.0 // indirect
+ google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d // indirect
+ google.golang.org/grpc v1.83.0 // indirect
)
require (
@@ -257,7 +267,7 @@ require (
github.com/gabriel-vasile/mimetype v1.4.13 // indirect
github.com/gin-contrib/sse v1.1.0 // indirect
github.com/go-ini/ini v1.67.0 // indirect
- github.com/go-logr/logr v1.4.3 // indirect
+ github.com/go-logr/logr v1.4.4 // indirect
github.com/go-logr/stdr v1.2.2 // indirect
github.com/go-ole/go-ole v1.3.0 // indirect
github.com/go-openapi/jsonpointer v0.19.5 // indirect
@@ -297,18 +307,18 @@ require (
github.com/yusufpapurcu/wmi v1.2.4 // indirect
go.opentelemetry.io/auto/sdk v1.2.1 // indirect
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 // indirect
- go.opentelemetry.io/otel v1.43.0 // indirect
- go.opentelemetry.io/otel/metric v1.43.0 // indirect
- go.opentelemetry.io/otel/trace v1.43.0 // indirect
+ go.opentelemetry.io/otel v1.45.0
+ go.opentelemetry.io/otel/metric v1.45.0 // indirect
+ go.opentelemetry.io/otel/trace v1.45.0 // indirect
golang.org/x/arch v0.17.0 // indirect
- golang.org/x/net v0.55.0 // indirect
+ golang.org/x/net v0.57.0 // indirect
golang.org/x/oauth2 v0.36.0
- golang.org/x/sync v0.20.0 // indirect
- golang.org/x/sys v0.45.0 // indirect
- golang.org/x/text v0.37.0 // indirect
- golang.org/x/tools v0.44.0 // indirect
+ golang.org/x/sync v0.22.0 // indirect
+ golang.org/x/sys v0.47.0 // indirect
+ golang.org/x/text v0.40.0 // indirect
+ golang.org/x/tools v0.47.0 // indirect
google.golang.org/api v0.275.0
- google.golang.org/protobuf v1.36.11 // indirect
+ google.golang.org/protobuf v1.36.12
gopkg.in/yaml.v2 v2.4.0 // indirect
gopkg.in/yaml.v3 v3.0.1 // indirect
olympos.io/encoding/edn v0.0.0-20201019073823-d3554ca0b0a3 // indirect
diff --git a/backend/go.sum b/backend/go.sum
index 521d0fa4..f686b3a1 100644
--- a/backend/go.sum
+++ b/backend/go.sum
@@ -184,6 +184,8 @@ github.com/calebcase/tmpfile v1.0.3 h1:BZrOWZ79gJqQ3XbAQlihYZf/YCV0H4KPIdM5K5oMp
github.com/calebcase/tmpfile v1.0.3/go.mod h1:UAUc01aHeC+pudPagY/lWvt2qS9ZO5Zzof6/tIUzqeI=
github.com/cenkalti/backoff/v4 v4.3.0 h1:MyRJ/UdXutAwSAT+s3wNd7MfTIcy71VQueUuFK343L8=
github.com/cenkalti/backoff/v4 v4.3.0/go.mod h1:Y3VNntkOUPxTVeUxJ/G5vcM//AlwfmyYozVcomhLiZE=
+github.com/cenkalti/backoff/v5 v5.0.3 h1:ZN+IMa753KfX5hd8vVaMixjnqRZ3y8CuJKRKj1xcsSM=
+github.com/cenkalti/backoff/v5 v5.0.3/go.mod h1:rkhZdG3JZukswDf7f0cwqPNk4K0sa+F97BxZthm/crw=
github.com/census-instrumentation/opencensus-proto v0.2.1/go.mod h1:f6KPmirojxKA12rnyqOA5BBL4O983OfeGPqjHWSTneU=
github.com/cespare/xxhash/v2 v2.3.0 h1:UL815xU9SqsFlibzuggzjXhog7bL6oX9BbNZnL2UFvs=
github.com/cespare/xxhash/v2 v2.3.0/go.mod h1:VGX0DQ3Q6kWi7AoAeZDth3/j3BFtOZR5XLFGgcrjCOs=
@@ -302,8 +304,8 @@ github.com/go-gl/glfw/v3.3/glfw v0.0.0-20200222043503-6f7a984d4dc4/go.mod h1:tQ2
github.com/go-ini/ini v1.67.0 h1:z6ZrTEZqSWOTyH2FlglNbNgARyHG8oLW9gMELqKr06A=
github.com/go-ini/ini v1.67.0/go.mod h1:ByCAeIL28uOIIG0E3PJtZPDL8WnHpFKFOtgjp+3Ies8=
github.com/go-logr/logr v1.2.2/go.mod h1:jdQByPbusPIv2/zmleS9BjJVeZ6kBagPoEUsqbVz/1A=
-github.com/go-logr/logr v1.4.3 h1:CjnDlHq8ikf6E492q6eKboGOC0T8CDaOvkHCIg8idEI=
-github.com/go-logr/logr v1.4.3/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
+github.com/go-logr/logr v1.4.4 h1:tG4xh9yMsRCAiodLVTxyrkzSZ9+o0L1Kg/+cPVcbP/8=
+github.com/go-logr/logr v1.4.4/go.mod h1:9T104GzyrTigFIr8wt5mBrctHMim0Nb2HLGrmQ40KvY=
github.com/go-logr/stdr v1.2.2 h1:hSWxHoqTgW2S2qGc0LTAI563KZ5YKYRhT3MFKZMbjag=
github.com/go-logr/stdr v1.2.2/go.mod h1:mMo/vtBO5dYbehREoey6XUKy/eSumjCCveDpRre4VKE=
github.com/go-ole/go-ole v1.2.6/go.mod h1:pprOEPIfldk/42T2oK7lQ4v4JSDwmV0As9GaiUsvbm0=
@@ -423,6 +425,8 @@ github.com/gorilla/securecookie v1.1.1 h1:miw7JPhV+b/lAHSXz4qd/nN9jRiAFV5FwjeKyC
github.com/gorilla/securecookie v1.1.1/go.mod h1:ra0sb63/xPlUeL+yeDciTfxMRAA+MP+HVt/4epWDjd4=
github.com/gorilla/sessions v1.2.1 h1:DHd3rPN5lE3Ts3D8rKkQ8x/0kqfeNmBAaiSi+o7FsgI=
github.com/gorilla/sessions v1.2.1/go.mod h1:dk2InVEVJ0sfLlnXv9EAgkf6ecYs/i80K/zI+bUmuGM=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0 h1:5VipnvEpbqr2gA2VbM+nYVbkIF28c5ZQfqCBQ5g2xfk=
+github.com/grpc-ecosystem/grpc-gateway/v2 v2.29.0/go.mod h1:Hyl3n6Twe1hvtd9XUXDec4pTvgMSEixRuQKPTMH2bNs=
github.com/hashicorp/errwrap v1.0.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
github.com/hashicorp/errwrap v1.1.0 h1:OxrOeh75EUXMY8TBjag2fzXGZ40LB6IKw45YeGUDY2I=
github.com/hashicorp/errwrap v1.1.0/go.mod h1:YH+1FKiLXxHSkmPseP+kNlulaMuP3n2brvKWEqk/Jc4=
@@ -770,18 +774,32 @@ go.opencensus.io v0.22.3/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opencensus.io v0.22.4/go.mod h1:yxeiOL68Rb0Xd1ddK5vPZ/oVn4vY4Ynel7k9FzqtOIw=
go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64=
go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y=
+go.opentelemetry.io/contrib/bridges/otelslog v0.20.0 h1:oEl2Pw/i4OQwhAuda2pAHFAcOMivA+Xa+iTccBfab/g=
+go.opentelemetry.io/contrib/bridges/otelslog v0.20.0/go.mod h1:yMSQaiiq5dpfrSJCYLBcqFeJkFFI67seT4ngvx6jfVo=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0 h1:OyrsyzuttWTSur2qN/Lm0m2a8yqyIjUVBZcxFPuXq2o=
go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.67.0/go.mod h1:C2NGBr+kAB4bk3xtMXfZ94gqFDtg/GkI7e9zqGh5Beg=
-go.opentelemetry.io/otel v1.43.0 h1:mYIM03dnh5zfN7HautFE4ieIig9amkNANT+xcVxAj9I=
-go.opentelemetry.io/otel v1.43.0/go.mod h1:JuG+u74mvjvcm8vj8pI5XiHy1zDeoCS2LB1spIq7Ay0=
-go.opentelemetry.io/otel/metric v1.43.0 h1:d7638QeInOnuwOONPp4JAOGfbCEpYb+K6DVWvdxGzgM=
-go.opentelemetry.io/otel/metric v1.43.0/go.mod h1:RDnPtIxvqlgO8GRW18W6Z/4P462ldprJtfxHxyKd2PY=
-go.opentelemetry.io/otel/sdk v1.43.0 h1:pi5mE86i5rTeLXqoF/hhiBtUNcrAGHLKQdhg4h4V9Dg=
-go.opentelemetry.io/otel/sdk v1.43.0/go.mod h1:P+IkVU3iWukmiit/Yf9AWvpyRDlUeBaRg6Y+C58QHzg=
-go.opentelemetry.io/otel/sdk/metric v1.42.0 h1:D/1QR46Clz6ajyZ3G8SgNlTJKBdGp84q9RKCAZ3YGuA=
-go.opentelemetry.io/otel/sdk/metric v1.42.0/go.mod h1:Ua6AAlDKdZ7tdvaQKfSmnFTdHx37+J4ba8MwVCYM5hc=
-go.opentelemetry.io/otel/trace v1.43.0 h1:BkNrHpup+4k4w+ZZ86CZoHHEkohws8AY+WTX09nk+3A=
-go.opentelemetry.io/otel/trace v1.43.0/go.mod h1:/QJhyVBUUswCphDVxq+8mld+AvhXZLhe+8WVFxiFff0=
+go.opentelemetry.io/otel v1.45.0 h1:pdrWmLHofpubmArBv1LgFSv1Z0Ie/ppdZzu+kUN5EeU=
+go.opentelemetry.io/otel v1.45.0/go.mod h1:XZxIqPapzEYnhNSScF5DIqXhm/rYi0FzCe2XddAwZfQ=
+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0 h1:WseeVYf5dJZTsyPiyW5L14k5qsSibqXAMTSiFEDiWr0=
+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc v0.21.0/go.mod h1:SiLZnQS6Qk2eCpvr2CH/XMAOa64TWGXxEZJZCpD2Lmc=
+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.21.0 h1:fvNHGyo3CdRv/DQveXqhqBxnKTDyRaC5sMSQxilX/A0=
+go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp v0.21.0/go.mod h1:zyGrjRKL2B/6+Jc/m4/otPoZqV2MY9ZjC/aBraRO7zc=
+go.opentelemetry.io/otel/log v0.21.0 h1:SLsVDGmtyBrdw8/a2Z0bOIxou/+bN4z56GebH7T0LvA=
+go.opentelemetry.io/otel/log v0.21.0/go.mod h1:iReetQrZL9Wyg84cCkOoCmqDHS5RCFfyxC7J+r8fn8g=
+go.opentelemetry.io/otel/metric v1.45.0 h1:7Eg1uH7CJ5cXv9is6tnBe1FI6rj1nwUdbFypRm3br/M=
+go.opentelemetry.io/otel/metric v1.45.0/go.mod h1:HAPbm1nd3p1PmFH7v2dR+6BjXxw+Lq4a2+pndMAm08s=
+go.opentelemetry.io/otel/sdk v1.45.0 h1:4VVSMgQ83dUgW2aoX5f6JgLvHwIvzcuLnF9lUdCSpCw=
+go.opentelemetry.io/otel/sdk v1.45.0/go.mod h1:Sr40LgXV7DsKMMJMKOhUWOgMWTfAaqvm2kF0g7ilwuA=
+go.opentelemetry.io/otel/sdk/log v0.21.0 h1:QsE7XSR0ktQdKmRKGnR+f1ObGF32WG+7MER/P9KgmYc=
+go.opentelemetry.io/otel/sdk/log v0.21.0/go.mod h1:m9mApjCoD2/1QuKCAptjv+BrG9WKOvQLVdNx+iBldTo=
+go.opentelemetry.io/otel/sdk/log/logtest v0.21.0 h1:X+JBBgKlswCGYsmgL0CnoUUtlE//VB345c84jYAYkdQ=
+go.opentelemetry.io/otel/sdk/log/logtest v0.21.0/go.mod h1:HD1575K8e6sIFBBDd5tZB3t9DlMytWXq9FuR+Y4rfjE=
+go.opentelemetry.io/otel/sdk/metric v1.45.0 h1:oVFszMfyj1Am6s24Vtc7wBb8BKLcwepJjNEYILuiE3o=
+go.opentelemetry.io/otel/sdk/metric v1.45.0/go.mod h1:vUWUxDZvu1WVRj8JA8S0AdhsPrZoDpA2DdZauIh4mDA=
+go.opentelemetry.io/otel/trace v1.45.0 h1:l/mP6Uv7oNO7/TblbhpbgMidxhq1uO/rPsikOyVhxag=
+go.opentelemetry.io/otel/trace v1.45.0/go.mod h1:qoJJA2xNMnxRrdISU/kLtfUH2wNeQbiv+jhs/CxI8bc=
+go.opentelemetry.io/proto/otlp v1.11.0 h1:5rrYs0Ykyj50sdU/JU0x8etU+LubXWb+gED6TbEdMIk=
+go.opentelemetry.io/proto/otlp v1.11.0/go.mod h1:SmVizdCOAm3XBtG1g1NnOdhW6jtddT72hLMhv8VwA8E=
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
go.yaml.in/yaml/v2 v2.4.3 h1:6gvOSjQoTB3vt1l+CU+tSyi/HOjfOjRLJ4YwYZGwRO0=
@@ -806,8 +824,8 @@ golang.org/x/crypto v0.13.0/go.mod h1:y6Z2r+Rw4iayiXXAIxJIDAJ1zMW4yaTpebo8fPOliY
golang.org/x/crypto v0.19.0/go.mod h1:Iy9bg/ha4yyC70EfRS8jz+B6ybOBKMaSxLj6P6oBDfU=
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
golang.org/x/crypto v0.31.0/go.mod h1:kDsLvtWBEx7MV9tJOj9bnXsPbxwJQ6csT/x4KIN4Ssk=
-golang.org/x/crypto v0.52.0 h1:RMs7fP2rXdep0CftQlK8Uf+kibLm7qkCcradZWYz988=
-golang.org/x/crypto v0.52.0/go.mod h1:1QgfPxDqh0T2M/elOJtp9RvuR95kVjir0e6/BvEmGbc=
+golang.org/x/crypto v0.54.0 h1:YLIA59K4fiNzHzjnZt2tUJQjQtUWfWbeHBqKtk3eScw=
+golang.org/x/crypto v0.54.0/go.mod h1:KWL8ny2AZdGR2cWmzeHrp2azQPGogOv+HeQaVEXC2dk=
golang.org/x/exp v0.0.0-20190121172915-509febef88a4/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190306152737-a1d7652674e8/go.mod h1:CJ0aWSM057203Lf6IL+f9T1iT9GByDxfZKAQTCR3kQA=
golang.org/x/exp v0.0.0-20190510132918-efd6b22b2522/go.mod h1:ZjyILWgesfNpC6sMxTJOJm9Kp84zZh5NQWvqDGG3Qr8=
@@ -848,8 +866,8 @@ golang.org/x/mod v0.8.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.12.0/go.mod h1:iBbtSCu2XBx23ZKBPSOrRkjjQPZFPuis4dIYUhu/chs=
golang.org/x/mod v0.15.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
golang.org/x/mod v0.17.0/go.mod h1:hTbmBsO62+eylJbnUtE2MGJUyE7QWk4xUqPFrRgJ+7c=
-golang.org/x/mod v0.35.0 h1:Ww1D637e6Pg+Zb2KrWfHQUnH2dQRLBQyAtpr/haaJeM=
-golang.org/x/mod v0.35.0/go.mod h1:+GwiRhIInF8wPm+4AoT6L0FA1QWAad3OMdTRx4tFYlU=
+golang.org/x/mod v0.37.0 h1:vF1DjpVEshcIqoEaauuHebaLk1O1forxjxBaVn884JQ=
+golang.org/x/mod v0.37.0/go.mod h1:m8S8VeM9r4dzDwjrKO0a1sZP3YjeMamRRlD+fmR2Q/0=
golang.org/x/net v0.0.0-20180724234803-3673e40ba225/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20180826012351-8a410e7b638d/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
golang.org/x/net v0.0.0-20190108225652-1e06a53dbb7e/go.mod h1:mL1N/T3taQHkDXs73rZJwtUhF3w3ftmwwsq0BUmARs4=
@@ -890,8 +908,8 @@ golang.org/x/net v0.15.0/go.mod h1:idbUs1IY1+zTqbi8yxTbhexhEEk5ur9LInksu6HrEpk=
golang.org/x/net v0.21.0/go.mod h1:bIjVDfnllIU7BJ2DNgfnXvpSvtn8VRwhlsaeUTyUS44=
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
golang.org/x/net v0.33.0/go.mod h1:HXLR5J+9DxmrqMwG9qjGCxZ+zKXxBru04zlTvWlWuN4=
-golang.org/x/net v0.55.0 h1:bcvxaJn3e1U6InsFWt1JUq1aSjnRxLzT2rtD2KfkDF8=
-golang.org/x/net v0.55.0/go.mod h1:L5U2KuzuOe1lY7Z+aWVIKK6qEeJXnXV9yzGA+WCHJww=
+golang.org/x/net v0.57.0 h1:K5+3DljvIuDG9/Jv9rvyMywYNFCQ9RSUY6OOTTkT+tE=
+golang.org/x/net v0.57.0/go.mod h1:KpXc8iv+r3XplLAG/f7Jsf9RPszJzdR0f58q9vGOuEU=
golang.org/x/oauth2 v0.0.0-20180821212333-d2e6202438be/go.mod h1:N/0e6XlmueqKjAGxoOufVs8QHGRruUQn6yWY3a++T0U=
golang.org/x/oauth2 v0.0.0-20190226205417-e64efc72b421/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
golang.org/x/oauth2 v0.0.0-20190604053449-0f29369cfe45/go.mod h1:gOpvHmFTYa4IltrdGE7lF6nIHvwfUNPOp7c8zoXwtLw=
@@ -915,8 +933,8 @@ golang.org/x/sync v0.3.0/go.mod h1:FU7BRWz2tNW+3quACPkgCx/L+uEAv1htQ0V83Z9Rj+Y=
golang.org/x/sync v0.6.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.7.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
golang.org/x/sync v0.10.0/go.mod h1:Czt+wKu1gCyEFDUtn0jG5QVvpJ6rzVqr5aXyt9drQfk=
-golang.org/x/sync v0.20.0 h1:e0PTpb7pjO8GAtTs2dQ6jYa5BWYlMuX047Dco/pItO4=
-golang.org/x/sync v0.20.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
+golang.org/x/sync v0.22.0 h1:SZjpbeLmrCk4xhRSZFNZW5gFUeCeFgjekvI/+gfScek=
+golang.org/x/sync v0.22.0/go.mod h1:9xrNwdLfx4jkKbNva9FpL6vEN7evnE43NNNJQ2LF3+0=
golang.org/x/sys v0.0.0-20180830151530-49385e6e1522/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190215142949-d0b11bdaac8a/go.mod h1:STP8DvDyc/dI5b8T5hshtkjS+E42TnysNCUPdjciGhY=
golang.org/x/sys v0.0.0-20190312061237-fead79001313/go.mod h1:h1NjWce9XRLGQEsW7wpKNCjG9DtNlClVuFLEZdDNbEs=
@@ -968,8 +986,8 @@ golang.org/x/sys v0.12.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
golang.org/x/sys v0.17.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
golang.org/x/sys v0.28.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
-golang.org/x/sys v0.45.0 h1:dO4czNzziLiiXplLQgBCEpCvXQ3dnkn0SdaZSYdQ+FY=
-golang.org/x/sys v0.45.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
+golang.org/x/sys v0.47.0 h1:o7XGOvZQCADBQQ4Y7VNq2dRWQR7JmOUW8Kxx4ZsNgWs=
+golang.org/x/sys v0.47.0/go.mod h1:4GL1E5IUh+htKOUEOaiffhrAeqysfVGipDYzABqnCmw=
golang.org/x/telemetry v0.0.0-20240228155512-f48c80bd79b2/go.mod h1:TeRTkGYfJXctD9OcfyVLyj2J3IxLnKwHJR8f4D8a3YE=
golang.org/x/term v0.0.0-20201126162022-7de9c90e9dd1/go.mod h1:bj7SfCRtBDWHUb9snDiAeCFNEtKQo2Wmx5Cou7ajbmo=
golang.org/x/term v0.0.0-20210927222741-03fcf44c2211/go.mod h1:jbD1KX2456YbFQfuXm/mYQcufACuNUgVhRMnK/tPxf8=
@@ -981,8 +999,8 @@ golang.org/x/term v0.12.0/go.mod h1:owVbMEjm3cBLCHdkQu9b1opXd4ETQWc3BhuQGKgXgvU=
golang.org/x/term v0.17.0/go.mod h1:lLRBjIVuehSbZlaOtGMbcMncT+aqLLLmKrsjNrUguwk=
golang.org/x/term v0.20.0/go.mod h1:8UkIAJTvZgivsXaD6/pH6U9ecQzZ45awqEOzuCvwpFY=
golang.org/x/term v0.27.0/go.mod h1:iMsnZpn0cago0GOrHO2+Y7u7JPn5AylBrcoWkElMTSM=
-golang.org/x/term v0.43.0 h1:S4RLU2sB31O/NCl+zFN9Aru9A/Cq2aqKpTZJ6B+DwT4=
-golang.org/x/term v0.43.0/go.mod h1:lrhlHNdQJHO+1qVYiHfFKVuVioJIheAc3fBSMFYEIsk=
+golang.org/x/term v0.45.0 h1:NwWyBmoJCbfTHpxrWoZ9C6/VxOf7ic219I8xZZFdrf0=
+golang.org/x/term v0.45.0/go.mod h1:9aqxs0blBcrm/n0L9QW0aRVD+ktan8ssZromtqJC43w=
golang.org/x/text v0.0.0-20170915032832-14c0d48ead0c/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.0/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
golang.org/x/text v0.3.1-0.20180807135948-17ff2d5776d2/go.mod h1:NqM8EUOU14njkJ3fqMW+pc6Ldnwhi/IjpwHt7yyuwOQ=
@@ -999,8 +1017,8 @@ golang.org/x/text v0.13.0/go.mod h1:TvPlkZtksWOMsz7fbANvkp4WM8x/WCo/om8BMLbz+aE=
golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
golang.org/x/text v0.21.0/go.mod h1:4IBbMaMmOPCJ8SecivzSH54+73PCFmPWxNTLm+vZkEQ=
-golang.org/x/text v0.37.0 h1:Cqjiwd9eSg8e0QAkyCaQTNHFIIzWtidPahFWR83rTrc=
-golang.org/x/text v0.37.0/go.mod h1:a5sjxXGs9hsn/AJVwuElvCAo9v8QYLzvavO5z2PiM38=
+golang.org/x/text v0.40.0 h1:Ub2Z6/xjgF1WrYQz2nuITOEegKFtiIy+rieRJ5lHZKs=
+golang.org/x/text v0.40.0/go.mod h1:hpnzDAfGV753zIKo+wk3u1bVKCGPbrnF7+7LBF/UHVY=
golang.org/x/time v0.0.0-20181108054448-85acf8d2951c/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20190308202827-9d24e82272b4/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
golang.org/x/time v0.0.0-20191024005414-555d28b269f0/go.mod h1:tRJNPiyCQ0inRvYxbN9jk5I+vvW/OXSQhTDSoE431IQ=
@@ -1053,8 +1071,8 @@ golang.org/x/tools v0.1.12/go.mod h1:hNGJHUnrk76NpqgfD5Aqm5Crs+Hm0VOH/i9J2+nxYbc
golang.org/x/tools v0.6.0/go.mod h1:Xwgl3UAJ/d3gWutnCtw505GrjyAbvKui8lOU390QaIU=
golang.org/x/tools v0.13.0/go.mod h1:HvlwmtVNQAhOuCjW7xxvovg8wbNq7LwfXh/k7wXUl58=
golang.org/x/tools v0.21.1-0.20240508182429-e35e4ccd0d2d/go.mod h1:aiJjzUbINMkxbQROHiO6hDPo2LHcIPhhQsa9DLh0yGk=
-golang.org/x/tools v0.44.0 h1:UP4ajHPIcuMjT1GqzDWRlalUEoY+uzoZKnhOjbIPD2c=
-golang.org/x/tools v0.44.0/go.mod h1:KA0AfVErSdxRZIsOVipbv3rQhVXTnlU6UhKxHd1seDI=
+golang.org/x/tools v0.47.0 h1:7Kn5x/d1svx/PzryTsqeoZN4TZwqeH5pGWjefhLi/1Q=
+golang.org/x/tools v0.47.0/go.mod h1:dFHnyTvFWY212G+h7ZY4Vsp/K3U4/7W9TyVaAul8uCA=
golang.org/x/xerrors v0.0.0-20190717185122-a985d3407aa7/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191011141410-1b5146add898/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
golang.org/x/xerrors v0.0.0-20191204190536-9bdfabe68543/go.mod h1:I/5z698sn9Ka8TeJc9MKroUUfqBBauWjQqLJ2OPfmY0=
@@ -1116,10 +1134,10 @@ google.golang.org/genproto v0.0.0-20200804131852-c06518451d9c/go.mod h1:FWY/as6D
google.golang.org/genproto v0.0.0-20200825200019-8632dd797987/go.mod h1:FWY/as6DDZQgahTzZj3fqbO1CbirC29ZNUFHwi0/+no=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7 h1:XzmzkmB14QhVhgnawEVsOn6OFsnpyxNPRY9QV01dNB0=
google.golang.org/genproto v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:L43LFes82YgSonw6iTXTxXUX1OlULt4AQtkik4ULL/I=
-google.golang.org/genproto/googleapis/api v0.0.0-20260319201613-d00831a3d3e7 h1:41r6JMbpzBMen0R/4TZeeAmGXSJC7DftGINUodzTkPI=
-google.golang.org/genproto/googleapis/api v0.0.0-20260319201613-d00831a3d3e7/go.mod h1:EIQZ5bFCfRQDV4MhRle7+OgjNtZ6P1PiZBgAKuxXu/Y=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9 h1:m8qni9SQFH0tJc1X0vmnpw/0t+AImlSvp30sEupozUg=
-google.golang.org/genproto/googleapis/rpc v0.0.0-20260401024825-9d38bb4040a9/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
+google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d h1:FarXi840EJWSHYTN3ERkADbPWjl307+FGrA22KAVjjc=
+google.golang.org/genproto/googleapis/api v0.0.0-20260803160001-6ac0973c030d/go.mod h1:K/+WGbmBY7aNW1HDw1fJnKYo10i0DkAX6pows00dLig=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d h1:IL4hdHzcUv2l/gcg98/Rj3FbtE6axwqslOW8SW0C+S0=
+google.golang.org/genproto/googleapis/rpc v0.0.0-20260803160001-6ac0973c030d/go.mod h1:4Hqkh8ycfw05ld/3BWL7rJOSfebL2Q+DVDeRgYgxUU8=
google.golang.org/grpc v1.19.0/go.mod h1:mqu4LbDTu4XGKhr4mRzUsmM4RtVoemTSY81AxZiDr8c=
google.golang.org/grpc v1.20.1/go.mod h1:10oTOabMzJvdu6/UiuZezV6QK5dSlG84ov/aaiqXj38=
google.golang.org/grpc v1.21.1/go.mod h1:oYelfM1adQP15Ek0mdvEgi9Df8B9CZIaU1084ijfRaM=
@@ -1132,8 +1150,8 @@ google.golang.org/grpc v1.28.0/go.mod h1:rpkK4SK4GF4Ach/+MFLZUBavHOvF2JJB5uozKKa
google.golang.org/grpc v1.29.1/go.mod h1:itym6AZVZYACWQqET3MqgPpjcuV5QH3BxFS3IjizoKk=
google.golang.org/grpc v1.30.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
google.golang.org/grpc v1.31.0/go.mod h1:N36X2cJ7JwdamYAgDz+s+rVMFjt3numwzf/HckM8pak=
-google.golang.org/grpc v1.80.0 h1:Xr6m2WmWZLETvUNvIUmeD5OAagMw3FiKmMlTdViWsHM=
-google.golang.org/grpc v1.80.0/go.mod h1:ho/dLnxwi3EDJA4Zghp7k2Ec1+c2jqup0bFkw07bwF4=
+google.golang.org/grpc v1.83.0 h1:JeNZEKJFbQxArAMl+hiytHauacDNqJUllNfmIMmpqnQ=
+google.golang.org/grpc v1.83.0/go.mod h1:kDyl6SKsiHKt0uylY5gtn5cEjkrIOhQOGDgIc4JGwzQ=
google.golang.org/protobuf v0.0.0-20200109180630-ec00e32a8dfd/go.mod h1:DFci5gLYBciE7Vtevhsrf46CRTquxDuWsQurQQe4oz8=
google.golang.org/protobuf v0.0.0-20200221191635-4d8936d0db64/go.mod h1:kwYJMbMJ01Woi6D6+Kah6886xMZcty6N08ah7+eCXa0=
google.golang.org/protobuf v0.0.0-20200228230310-ab0ca4ff8a60/go.mod h1:cfTl7dwQJ+fmap5saPgwCLgHXTUD7jkjRqWcaiX5VyM=
@@ -1144,8 +1162,8 @@ google.golang.org/protobuf v1.23.0/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2
google.golang.org/protobuf v1.23.1-0.20200526195155-81db48ad09cc/go.mod h1:EGpADcykh3NcUnDUJcl1+ZksZNG86OlYog2l/sGQquU=
google.golang.org/protobuf v1.24.0/go.mod h1:r/3tXBNzIEhYS9I1OUVjXDlt8tc493IdKGjtUeSXeh4=
google.golang.org/protobuf v1.25.0/go.mod h1:9JNX74DMeImyA3h4bdi1ymwjUzf21/xIlbajtzgsN7c=
-google.golang.org/protobuf v1.36.11 h1:fV6ZwhNocDyBLK0dj+fg8ektcVegBBuEolpbTQyBNVE=
-google.golang.org/protobuf v1.36.11/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
+google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc=
+google.golang.org/protobuf v1.36.12/go.mod h1:HTf+CrKn2C3g5S8VImy6tdcUvCska2kB7j23XfzDpco=
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20180628173108-788fd7840127/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
gopkg.in/check.v1 v1.0.0-20200227125254-8fa46927fb4f/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
diff --git a/backend/internal/config/config.go b/backend/internal/config/config.go
index c891b1ec..4404c10e 100644
--- a/backend/internal/config/config.go
+++ b/backend/internal/config/config.go
@@ -142,12 +142,12 @@ func loadEnvVariables() {
envPath := filepath.Join(filepath.Dir(backendRoot), ".env")
- log.Info("Trying to load .env", "path", envPath)
+ log.Info("trying to load .env", "path", envPath)
if err := godotenv.Load(envPath); err != nil {
- log.Error("Error loading .env file from repo root", "path", envPath, "error", err)
- os.Exit(1)
+ log.Error("error loading .env file from repo root", "path", envPath, "error", err)
+ logger.ExitAfterFlush(1)
}
- log.Info("Successfully loaded .env", "path", envPath)
+ log.Info("successfully loaded .env", "path", envPath)
// Empty values for non-string fields (e.g. SMTP_PORT=) crash cleanenv's
// strconv parsing. Drop them so cleanenv falls back to the Go zero value.
@@ -155,13 +155,13 @@ func loadEnvVariables() {
err = cleanenv.ReadEnv(&env)
if err != nil {
- log.Error("Configuration could not be loaded", "error", err)
- os.Exit(1)
+ log.Error("configuration could not be loaded", "error", err)
+ logger.ExitAfterFlush(1)
}
if env.SMTPHost != "" && env.SMTPPort <= 0 {
log.Error("SMTP_PORT must be a positive integer when SMTP_HOST is set", "value", env.SMTPPort)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
// Set default value for ShowDbInstallationVerificationLogs if not defined
@@ -179,7 +179,7 @@ func loadEnvVariables() {
if env.IsTesting {
if env.TestDatabaseDsn == "" {
log.Error("TEST_DATABASE_DSN is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
env.DatabaseDsn = env.TestDatabaseDsn
@@ -198,16 +198,16 @@ func loadEnvVariables() {
if env.DatabaseDsn == "" {
log.Error("DATABASE_DSN is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if env.EnvMode == "" {
log.Error("ENV_MODE is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if env.EnvMode != "development" && env.EnvMode != "production" {
log.Error("ENV_MODE is invalid", "mode", env.EnvMode)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
log.Info("ENV_MODE loaded", "mode", env.EnvMode)
@@ -220,11 +220,11 @@ func loadEnvVariables() {
// Valkey
if env.ValkeyHost == "" {
log.Error("VALKEY_HOST is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if env.ValkeyPort == "" {
log.Error("VALKEY_PORT is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
// Store the data and temp folders one level below the root
@@ -239,19 +239,19 @@ func loadEnvVariables() {
if env.IsTesting {
if env.TestLogicalPostgres16Port == "" {
log.Error("TEST_LOGICAL_POSTGRES_16_PORT is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if env.TestPhysicalPostgres17Port == "" {
log.Error("TEST_PHYSICAL_POSTGRES_17_PORT is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if env.TestPhysicalPostgres18Port == "" {
log.Error("TEST_PHYSICAL_POSTGRES_18_PORT is empty")
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
}
- log.Info("Environment variables loaded successfully!")
+ log.Info("environment variables loaded successfully")
}
func unsetEmptyEnvVars() {
@@ -283,7 +283,7 @@ func applyTestWorkerSlot() {
baseDbName, _, err := RewriteDbName(env.TestDatabaseDsn, systemDbName)
if err != nil {
log.Error("could not parse TEST_DATABASE_DSN for slot isolation", "error", err)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
slot := claimTestWorkerSlot(env.TestDatabaseDsn, env.TestParallelWorkers)
@@ -292,7 +292,7 @@ func applyTestWorkerSlot() {
_, slotDsn, err := RewriteDbName(env.TestDatabaseDsn, slotDbName)
if err != nil {
log.Error("could not build per-slot DSN", "error", err)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
env.DatabaseDsn = slotDsn
@@ -314,20 +314,20 @@ func claimTestWorkerSlot(testDsn string, pool int) int {
_, systemDsn, err := RewriteDbName(testDsn, systemDbName)
if err != nil {
log.Error("could not build system DSN for slot claim", "error", err)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
db, err := sql.Open("pgx", systemDsn)
if err != nil {
log.Error("could not open system DB for slot claim", "error", err)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
ctx := context.Background()
conn, err := db.Conn(ctx)
if err != nil {
log.Error("could not get system DB connection for slot claim", "error", err)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
deadline := time.Now().Add(testSlotClaimTimeout)
@@ -341,7 +341,7 @@ func claimTestWorkerSlot(testDsn string, pool int) int {
).Scan(&locked)
if lockErr != nil {
log.Error("advisory lock query failed during slot claim", "error", lockErr)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
if locked {
@@ -356,7 +356,7 @@ func claimTestWorkerSlot(testDsn string, pool int) int {
"pool", pool,
"hint", "TEST_PARALLEL_WORKERS must be >= the `go test -p` value",
)
- os.Exit(1)
+ logger.ExitAfterFlush(1)
}
time.Sleep(100 * time.Millisecond)
diff --git a/backend/internal/config/signals.go b/backend/internal/config/signals.go
index 64b89ead..9dbfe4f3 100644
--- a/backend/internal/config/signals.go
+++ b/backend/internal/config/signals.go
@@ -4,6 +4,8 @@ import (
"os"
"os/signal"
"syscall"
+
+ "databasus-backend/internal/util/logger"
)
var isShutDownSignalReceived = false
@@ -14,6 +16,10 @@ func StartListeningForShutdownSignal() {
go func() {
<-quit
+
+ // Nothing else records why the process began shutting down.
+ logger.GetLogger().Info("shutdown signal received")
+
isShutDownSignalReceived = true
}()
}
diff --git a/backend/internal/middleware/access_log.go b/backend/internal/middleware/access_log.go
new file mode 100644
index 00000000..a36480ba
--- /dev/null
+++ b/backend/internal/middleware/access_log.go
@@ -0,0 +1,79 @@
+package middleware
+
+import (
+ "fmt"
+ "log/slog"
+ "net/http"
+ "strings"
+ "time"
+
+ "github.com/gin-gonic/gin"
+
+ verification_agents "databasus-backend/internal/features/verification/agents"
+)
+
+// Static assets and the SPA fallback match no route, so ctx.FullPath() is empty for them. A marker
+// keeps that traffic filterable instead of looking like a routing bug.
+const staticRouteName = "static"
+
+// The query string is left out on purpose: download and restore tokens travel there.
+func LogAccess(log *slog.Logger) gin.HandlerFunc {
+ return func(ctx *gin.Context) {
+ startedAt := time.Now().UTC()
+
+ ctx.Next()
+
+ status := ctx.Writer.Status()
+ message := fmt.Sprintf("%s %s -> %d in %dms",
+ ctx.Request.Method,
+ ctx.Request.URL.Path,
+ status,
+ time.Since(startedAt).Milliseconds(),
+ )
+
+ route := ctx.FullPath()
+ if route == "" {
+ route = staticRouteName
+ }
+
+ attributes := []any{
+ "route", route,
+ "client_ip", ctx.ClientIP(),
+ "response_bytes", ctx.Writer.Size(),
+ }
+
+ // user_id already reaches every record from the request context, which AuthMiddleware
+ // populates; an agent has no such carrier, so it is attached here. Runs after ctx.Next(),
+ // so moving this middleware earlier in the chain would drop the agent.
+ if agent, isAgent := verification_agents.GetAgentFromContext(ctx); isAgent {
+ attributes = append(attributes, "agent_id", agent.ID)
+ }
+
+ if status >= http.StatusInternalServerError {
+ // Handlers attach the cause with ctx.Error so the access line carries it, rather than
+ // each of them logging its own near-duplicate of this record.
+ if handlerErrors := collectHandlerErrors(ctx); handlerErrors != "" {
+ attributes = append(attributes, "error", handlerErrors)
+ }
+
+ log.ErrorContext(ctx.Request.Context(), message, attributes...)
+
+ return
+ }
+
+ log.InfoContext(ctx.Request.Context(), message, attributes...)
+ }
+}
+
+func collectHandlerErrors(ctx *gin.Context) string {
+ if len(ctx.Errors) == 0 {
+ return ""
+ }
+
+ messages := make([]string, 0, len(ctx.Errors))
+ for _, handlerError := range ctx.Errors {
+ messages = append(messages, handlerError.Error())
+ }
+
+ return strings.Join(messages, "; ")
+}
diff --git a/backend/internal/middleware/access_log_test.go b/backend/internal/middleware/access_log_test.go
new file mode 100644
index 00000000..99d87a37
--- /dev/null
+++ b/backend/internal/middleware/access_log_test.go
@@ -0,0 +1,182 @@
+package middleware
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ users_models "databasus-backend/internal/features/users/models"
+ verification_agents "databasus-backend/internal/features/verification/agents"
+ "databasus-backend/internal/util/logger"
+)
+
+type capturedAccessRecord struct {
+ level slog.Level
+ message string
+ requestID string
+ userID string
+ attributes map[string]any
+}
+
+type accessRecordCapturer struct {
+ records *[]capturedAccessRecord
+}
+
+func (h accessRecordCapturer) Enabled(context.Context, slog.Level) bool { return true }
+
+func (h accessRecordCapturer) WithAttrs([]slog.Attr) slog.Handler { return h }
+
+func (h accessRecordCapturer) WithGroup(string) slog.Handler { return h }
+
+func (h accessRecordCapturer) Handle(ctx context.Context, record slog.Record) error {
+ captured := capturedAccessRecord{
+ level: record.Level,
+ message: record.Message,
+ requestID: logger.GetRequestID(ctx),
+ userID: logger.GetUserID(ctx),
+ attributes: map[string]any{},
+ }
+
+ record.Attrs(func(attr slog.Attr) bool {
+ captured.attributes[attr.Key] = attr.Value.Any()
+
+ return true
+ })
+
+ *h.records = append(*h.records, captured)
+
+ return nil
+}
+
+func serveAccessLoggedRoute(t *testing.T, path string, authenticatedUser *users_models.User) capturedAccessRecord {
+ t.Helper()
+
+ records := &[]capturedAccessRecord{}
+
+ gin.SetMode(gin.TestMode)
+ router := gin.New()
+ router.Use(AssignRequestID(), LogAccess(slog.New(accessRecordCapturer{records})))
+
+ if authenticatedUser != nil {
+ router.Use(func(ctx *gin.Context) {
+ ctx.Set("user", authenticatedUser)
+ ctx.Request = ctx.Request.WithContext(
+ logger.ContextWithUserID(ctx.Request.Context(), authenticatedUser.ID.String()),
+ )
+ ctx.Next()
+ })
+ }
+
+ router.GET("/api/v1/storages", func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
+ router.GET("/api/v1/databases/:databaseId/crash", func(ctx *gin.Context) {
+ ctx.Status(http.StatusInternalServerError)
+ })
+
+ response := httptest.NewRecorder()
+ router.ServeHTTP(response, httptest.NewRequest(http.MethodGet, path, nil))
+
+ require.Len(t, *records, 1)
+ assert.Equal(t, response.Header().Get(RequestIDHeader), (*records)[0].requestID,
+ "the logged request id must be the one the client was given")
+
+ return (*records)[0]
+}
+
+func Test_LogAccess_OnSuccessfulRequest_LogsMethodPathAndStatusAtInfo(t *testing.T) {
+ record := serveAccessLoggedRoute(t, "/api/v1/storages", nil)
+
+ assert.Equal(t, slog.LevelInfo, record.level)
+ assert.Contains(t, record.message, "GET /api/v1/storages -> 200 in ")
+ assert.Equal(t, "/api/v1/storages", record.attributes["route"])
+}
+
+func Test_LogAccess_WhenHandlerFails_LogsAtErrorLevel(t *testing.T) {
+ record := serveAccessLoggedRoute(t, "/api/v1/databases/db-42/crash", nil)
+
+ assert.Equal(t, slog.LevelError, record.level)
+ assert.Contains(t, record.message, "-> 500 in ")
+ assert.Equal(t, "/api/v1/databases/:databaseId/crash", record.attributes["route"])
+}
+
+// The principal reaches the record from the request context, the same way request_id does, so the
+// access line is not a second place that has to remember to attach it.
+func Test_LogAccess_WhenRequestIsAuthenticated_AttachesUserID(t *testing.T) {
+ authenticatedUser := &users_models.User{ID: uuid.New()}
+
+ record := serveAccessLoggedRoute(t, "/api/v1/storages", authenticatedUser)
+
+ assert.Equal(t, authenticatedUser.ID.String(), record.userID)
+ assert.NotContains(t, record.attributes, "user_id",
+ "the context carries it; attaching it here as well would emit the key twice")
+}
+
+// Download and restore tokens travel in the query string, so it must never reach a sink.
+func Test_LogAccess_WithQueryString_LeavesItOutOfTheRecord(t *testing.T) {
+ record := serveAccessLoggedRoute(t, "/api/v1/storages?token=secret-download-token", nil)
+
+ assert.NotContains(t, record.message, "secret-download-token")
+ assert.NotContains(t, record.message, "?")
+}
+
+func Test_LogAccess_WhenRequestUsesAgentToken_AttachesAgentID(t *testing.T) {
+ authenticatedAgent := &verification_agents.Agent{ID: uuid.New()}
+
+ gin.SetMode(gin.TestMode)
+
+ records := &[]capturedAccessRecord{}
+ router := gin.New()
+ router.Use(AssignRequestID(), LogAccess(slog.New(accessRecordCapturer{records})))
+ router.Use(func(ctx *gin.Context) {
+ ctx.Set("verification_agent", authenticatedAgent)
+ ctx.Next()
+ })
+ router.GET("/api/v1/agent/verification/heartbeat", func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
+
+ router.ServeHTTP(
+ httptest.NewRecorder(),
+ httptest.NewRequest(http.MethodGet, "/api/v1/agent/verification/heartbeat", nil),
+ )
+
+ require.Len(t, *records, 1)
+ assert.Equal(t, authenticatedAgent.ID, (*records)[0].attributes["agent_id"])
+}
+
+func Test_LogAccess_WhenStaticAssetIsServed_MarksTheRouteAsStatic(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ records := &[]capturedAccessRecord{}
+ router := gin.New()
+ router.Use(AssignRequestID(), LogAccess(slog.New(accessRecordCapturer{records})))
+ router.NoRoute(func(ctx *gin.Context) { ctx.Status(http.StatusOK) })
+
+ router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/assets/index.js", nil))
+
+ require.Len(t, *records, 1)
+ assert.Equal(t, staticRouteName, (*records)[0].attributes["route"])
+}
+
+// A handler attaches the cause with ctx.Error instead of logging its own near-duplicate record.
+func Test_LogAccess_WhenHandlerAttachesAnError_PutsItOnTheAccessLine(t *testing.T) {
+ gin.SetMode(gin.TestMode)
+
+ records := &[]capturedAccessRecord{}
+ router := gin.New()
+ router.Use(AssignRequestID(), LogAccess(slog.New(accessRecordCapturer{records})))
+ router.GET("/api/v1/storages", func(ctx *gin.Context) {
+ _ = ctx.Error(errors.New("storage backend unreachable"))
+ ctx.Status(http.StatusInternalServerError)
+ })
+
+ router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/api/v1/storages", nil))
+
+ require.Len(t, *records, 1)
+ assert.Contains(t, (*records)[0].attributes["error"], "storage backend unreachable")
+}
diff --git a/backend/internal/middleware/request_id.go b/backend/internal/middleware/request_id.go
new file mode 100644
index 00000000..2c442e60
--- /dev/null
+++ b/backend/internal/middleware/request_id.go
@@ -0,0 +1,23 @@
+package middleware
+
+import (
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+
+ "databasus-backend/internal/util/logger"
+)
+
+const RequestIDHeader = "X-Request-Id"
+
+// An inbound X-Request-Id is ignored: a client that picked its own ID could merge its actions into
+// another user's trace.
+func AssignRequestID() gin.HandlerFunc {
+ return func(ctx *gin.Context) {
+ requestID := uuid.NewString()
+
+ ctx.Header(RequestIDHeader, requestID)
+ ctx.Request = ctx.Request.WithContext(logger.ContextWithRequestID(ctx.Request.Context(), requestID))
+
+ ctx.Next()
+ }
+}
diff --git a/backend/internal/middleware/request_id_test.go b/backend/internal/middleware/request_id_test.go
new file mode 100644
index 00000000..a61251e4
--- /dev/null
+++ b/backend/internal/middleware/request_id_test.go
@@ -0,0 +1,64 @@
+package middleware
+
+import (
+ "net/http"
+ "net/http/httptest"
+ "testing"
+
+ "github.com/gin-gonic/gin"
+ "github.com/google/uuid"
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+
+ "databasus-backend/internal/util/logger"
+)
+
+func buildRouterWithRequestID() *gin.Engine {
+ gin.SetMode(gin.TestMode)
+
+ router := gin.New()
+ router.Use(AssignRequestID())
+ router.GET("/api/v1/system/version", func(ctx *gin.Context) {
+ ctx.String(http.StatusOK, logger.GetRequestID(ctx.Request.Context()))
+ })
+
+ return router
+}
+
+func serveRequestIDRoute(inboundRequestID string) *httptest.ResponseRecorder {
+ request := httptest.NewRequest(http.MethodGet, "/api/v1/system/version", nil)
+ if inboundRequestID != "" {
+ request.Header.Set(RequestIDHeader, inboundRequestID)
+ }
+
+ response := httptest.NewRecorder()
+ buildRouterWithRequestID().ServeHTTP(response, request)
+
+ return response
+}
+
+func Test_AssignRequestID_OnEveryRequest_EchoesTheIDAndPutsItInTheContext(t *testing.T) {
+ response := serveRequestIDRoute("")
+
+ requestID := response.Header().Get(RequestIDHeader)
+ _, err := uuid.Parse(requestID)
+ require.NoError(t, err, "the echoed request id must be a UUID")
+
+ assert.Equal(t, requestID, response.Body.String(), "handlers must see the same id as the client")
+}
+
+func Test_AssignRequestID_AcrossRequests_GeneratesADistinctID(t *testing.T) {
+ firstRequestID := serveRequestIDRoute("").Header().Get(RequestIDHeader)
+ secondRequestID := serveRequestIDRoute("").Header().Get(RequestIDHeader)
+
+ assert.NotEqual(t, firstRequestID, secondRequestID)
+}
+
+func Test_AssignRequestID_WhenClientSendsOne_IgnoresIt(t *testing.T) {
+ clientRequestID := "11111111-1111-1111-1111-111111111111"
+
+ response := serveRequestIDRoute(clientRequestID)
+
+ assert.NotEqual(t, clientRequestID, response.Header().Get(RequestIDHeader))
+ assert.NotEqual(t, clientRequestID, response.Body.String())
+}
diff --git a/backend/internal/util/logger/doc.go b/backend/internal/util/logger/doc.go
new file mode 100644
index 00000000..5b80414a
--- /dev/null
+++ b/backend/internal/util/logger/doc.go
@@ -0,0 +1,9 @@
+// Package logger builds the application's slog pipeline: a stdout console sink, an optional
+// rotating file, and an optional OpenTelemetry exporter, fanned out from a single handler.
+//
+// internal/config imports this package, so this package must not import internal/config. That is
+// why it loads .env and reads its own environment variables instead of going through EnvVariables.
+//
+// Redaction lives here rather than at call sites because every sink must be covered by it, and a
+// call site cannot know that its line is about to be written to disk and shipped off-box.
+package logger
diff --git a/backend/internal/util/logger/fan_out_handler.go b/backend/internal/util/logger/fan_out_handler.go
new file mode 100644
index 00000000..a10735ca
--- /dev/null
+++ b/backend/internal/util/logger/fan_out_handler.go
@@ -0,0 +1,97 @@
+package logger
+
+import (
+ "context"
+ "errors"
+ "log/slog"
+)
+
+var _ slog.Handler = (*fanOutHandler)(nil)
+
+// fanOutHandler owns every level decision. Its children are built at LevelDebug and are never
+// asked whether they are enabled, so audit records can bypass the configured level by flipping
+// isLevelBypassed without any child re-filtering them.
+type fanOutHandler struct {
+ children []slog.Handler
+ level *slog.LevelVar
+ isLevelBypassed bool
+}
+
+func newFanOutHandler(children []slog.Handler, level *slog.LevelVar) *fanOutHandler {
+ return &fanOutHandler{
+ children: children,
+ level: level,
+ isLevelBypassed: false,
+ }
+}
+
+func (h *fanOutHandler) Enabled(_ context.Context, level slog.Level) bool {
+ return h.isLevelBypassed || level >= h.level.Level()
+}
+
+func (h *fanOutHandler) Handle(ctx context.Context, record slog.Record) error {
+ redactedRecord := slog.NewRecord(record.Time, record.Level, redactMessage(record.Message), record.PC)
+ record.Attrs(func(attr slog.Attr) bool {
+ redactedRecord.AddAttrs(redactAttr(attr))
+
+ return true
+ })
+
+ if requestID := GetRequestID(ctx); requestID != "" {
+ redactedRecord.AddAttrs(slog.String(requestIDKey, requestID))
+ }
+
+ if userID := GetUserID(ctx); userID != "" {
+ redactedRecord.AddAttrs(slog.String(userIDKey, userID))
+ }
+
+ var sinkErrors []error
+ for _, child := range h.children {
+ if err := child.Handle(ctx, redactedRecord); err != nil {
+ sinkErrors = append(sinkErrors, err)
+ }
+ }
+
+ return errors.Join(sinkErrors...)
+}
+
+// WithAttrs redacts here as well as in Handle: scoped attrs are baked into the children at this
+// point and would never pass through Handle's redaction again.
+func (h *fanOutHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
+ redactedAttrs := make([]slog.Attr, 0, len(attrs))
+ for _, attr := range attrs {
+ redactedAttrs = append(redactedAttrs, redactAttr(attr))
+ }
+
+ children := make([]slog.Handler, 0, len(h.children))
+ for _, child := range h.children {
+ children = append(children, child.WithAttrs(redactedAttrs))
+ }
+
+ return &fanOutHandler{
+ children: children,
+ level: h.level,
+ isLevelBypassed: h.isLevelBypassed,
+ }
+}
+
+func (h *fanOutHandler) WithGroup(name string) slog.Handler {
+ children := make([]slog.Handler, 0, len(h.children))
+ for _, child := range h.children {
+ children = append(children, child.WithGroup(name))
+ }
+
+ return &fanOutHandler{
+ children: children,
+ level: h.level,
+ isLevelBypassed: h.isLevelBypassed,
+ }
+}
+
+func (h *fanOutHandler) withLevelBypass() *fanOutHandler {
+ return &fanOutHandler{
+ children: h.children,
+ level: h.level,
+ isLevelBypassed: true,
+ }
+}
diff --git a/backend/internal/util/logger/fan_out_handler_test.go b/backend/internal/util/logger/fan_out_handler_test.go
new file mode 100644
index 00000000..f11b14ce
--- /dev/null
+++ b/backend/internal/util/logger/fan_out_handler_test.go
@@ -0,0 +1,164 @@
+package logger
+
+import (
+ "bytes"
+ "encoding/json"
+ "log/slog"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+type capturedSinks struct {
+ firstSink *bytes.Buffer
+ secondSink *bytes.Buffer
+}
+
+func newTestFanOutHandler(level slog.Level) (*fanOutHandler, capturedSinks) {
+ sinks := capturedSinks{firstSink: &bytes.Buffer{}, secondSink: &bytes.Buffer{}}
+
+ levelVar := new(slog.LevelVar)
+ levelVar.Set(level)
+
+ children := []slog.Handler{
+ slog.NewJSONHandler(sinks.firstSink, &slog.HandlerOptions{Level: slog.LevelDebug}),
+ slog.NewJSONHandler(sinks.secondSink, &slog.HandlerOptions{Level: slog.LevelDebug}),
+ }
+
+ return newFanOutHandler(children, levelVar), sinks
+}
+
+func decodeSingleRecord(t *testing.T, sink *bytes.Buffer) map[string]any {
+ t.Helper()
+
+ var decoded map[string]any
+ require.NoError(t, json.Unmarshal(sink.Bytes(), &decoded))
+
+ return decoded
+}
+
+func Test_Handle_WithMultipleSinks_WritesRecordToEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).Info("backup finished")
+
+ assert.Contains(t, sinks.firstSink.String(), "backup finished")
+ assert.Contains(t, sinks.secondSink.String(), "backup finished")
+}
+
+func Test_WithAttrs_WithMultipleSinks_ScopedAttrsReachEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).With("database_id", "db-42").Info("backup finished")
+
+ assert.Equal(t, "db-42", decodeSingleRecord(t, sinks.firstSink)["database_id"])
+ assert.Equal(t, "db-42", decodeSingleRecord(t, sinks.secondSink)["database_id"])
+}
+
+func Test_WithGroup_WithMultipleSinks_PreservesNestingInEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).WithGroup("backup").Info("finished", "size_mb", 12)
+
+ for _, sink := range []*bytes.Buffer{sinks.firstSink, sinks.secondSink} {
+ group, isGroup := decodeSingleRecord(t, sink)["backup"].(map[string]any)
+
+ require.True(t, isGroup)
+ assert.EqualValues(t, 12, group["size_mb"])
+ }
+}
+
+func Test_Handle_WhenLevelIsAboveRecord_SuppressesRecordInEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelError)
+
+ slog.New(handler).Info("routine work")
+
+ assert.Empty(t, sinks.firstSink.String())
+ assert.Empty(t, sinks.secondSink.String())
+}
+
+func Test_Handle_WhenLevelBypassed_AuditRecordSurvivesErrorLevel(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelError)
+
+ auditLogger := slog.New(handler.withLevelBypass()).With(logTypeKey, logTypeAudit)
+ auditLogger.Info("Database deleted: payments")
+
+ auditRecord := decodeSingleRecord(t, sinks.firstSink)
+ assert.Equal(t, logTypeAudit, auditRecord[logTypeKey])
+ assert.Equal(t, "Database deleted: payments", auditRecord["msg"])
+ assert.NotEmpty(t, sinks.secondSink.String())
+}
+
+// withLevelBypass must return a new handler, not flip a flag on the receiver: logger.go builds
+// the audit logger and the application logger from the same fanOut, so a mutating receiver would
+// make the whole application ignore LOG_LEVEL.
+func Test_WithLevelBypass_WhenDerived_LeavesOriginalHandlerFiltering(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelError)
+
+ bypassed := slog.New(handler.withLevelBypass())
+ bypassed.Info("audit record")
+ require.NotEmpty(t, sinks.firstSink.String(), "the derived handler must bypass the level")
+
+ sinks.firstSink.Reset()
+ sinks.secondSink.Reset()
+
+ slog.New(handler).Info("routine work")
+
+ assert.Empty(t, sinks.firstSink.String(), "the original handler must still filter")
+ assert.Empty(t, sinks.secondSink.String())
+}
+
+func Test_Handle_WithRequestIDInContext_AddsRequestIDToEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ ctx := ContextWithRequestID(t.Context(), "6f1c2b7e-0a3d-4c8f-9b21-5d7e4a1c3f90")
+ slog.New(handler).InfoContext(ctx, "storage created")
+
+ assert.Equal(t, "6f1c2b7e-0a3d-4c8f-9b21-5d7e4a1c3f90", decodeSingleRecord(t, sinks.firstSink)[requestIDKey])
+ assert.Equal(t, "6f1c2b7e-0a3d-4c8f-9b21-5d7e4a1c3f90", decodeSingleRecord(t, sinks.secondSink)[requestIDKey])
+}
+
+func Test_Handle_WithoutRequestIDInContext_OmitsRequestID(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).Info("storage created")
+
+ assert.NotContains(t, decodeSingleRecord(t, sinks.firstSink), requestIDKey)
+}
+
+func Test_Handle_WithSensitiveAttrs_RedactsBeforeReachingSinks(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).Info("connecting", "password", "hunter2", "database_id", "db-42")
+
+ record := decodeSingleRecord(t, sinks.firstSink)
+ assert.Equal(t, redactedValue, record["password"])
+ assert.Equal(t, "db-42", record["database_id"])
+}
+
+func Test_WithAttrs_WithSensitiveAttrs_RedactsScopedAttrsToo(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).With("api_key", "sk-live-1234").Info("calling storage")
+
+ assert.Equal(t, redactedValue, decodeSingleRecord(t, sinks.firstSink)["api_key"])
+}
+
+func Test_Handle_WithUserIDInContext_AddsUserIDToEverySink(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ ctx := ContextWithUserID(t.Context(), "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed")
+ slog.New(handler).InfoContext(ctx, "storage created")
+
+ assert.Equal(t, "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", decodeSingleRecord(t, sinks.firstSink)[userIDKey])
+ assert.Equal(t, "1b9d6bcd-bbfd-4b2d-9b5d-ab8dfbbd4bed", decodeSingleRecord(t, sinks.secondSink)[userIDKey])
+}
+
+func Test_Handle_WithoutUserIDInContext_OmitsUserID(t *testing.T) {
+ handler, sinks := newTestFanOutHandler(slog.LevelInfo)
+
+ slog.New(handler).Info("storage created")
+
+ assert.NotContains(t, decodeSingleRecord(t, sinks.firstSink), userIDKey)
+}
diff --git a/backend/internal/util/logger/file_sink.go b/backend/internal/util/logger/file_sink.go
new file mode 100644
index 00000000..7c320655
--- /dev/null
+++ b/backend/internal/util/logger/file_sink.go
@@ -0,0 +1,144 @@
+package logger
+
+import (
+ "context"
+ "fmt"
+ "os"
+ "path/filepath"
+ "slices"
+ "sync"
+ "sync/atomic"
+ "time"
+
+ "gopkg.in/natefinch/lumberjack.v2"
+)
+
+const (
+ fileQueueCapacity = 4096
+ fileEnqueueTimeout = 1 * time.Second
+ dropReportInterval = 30 * time.Second
+)
+
+// rotatingFileWriter decouples log calls from disk with its own queue. Unlike the remote sink it
+// applies backpressure before dropping: the file is the forensic copy, and local disk is fast
+// enough that waiting beats losing lines. The timeout still caps the damage a hung disk can do.
+type rotatingFileWriter struct {
+ queue chan []byte
+ rotator *lumberjack.Logger
+ stop chan struct{}
+ drained chan struct{}
+ shutdownOnce func()
+ droppedCount atomic.Int64
+ lastDropReportAt atomic.Int64
+}
+
+type rotatingFileSpec struct {
+ path string
+ maxSizeMB int
+ maxBackups int
+}
+
+func newRotatingFileWriter(spec rotatingFileSpec) (*rotatingFileWriter, error) {
+ if err := os.MkdirAll(filepath.Dir(spec.path), 0o750); err != nil {
+ return nil, fmt.Errorf("failed to create log directory: %w", err)
+ }
+
+ writer := &rotatingFileWriter{
+ queue: make(chan []byte, fileQueueCapacity),
+ rotator: &lumberjack.Logger{
+ Filename: spec.path,
+ MaxSize: spec.maxSizeMB,
+ MaxBackups: spec.maxBackups,
+ },
+ stop: make(chan struct{}),
+ drained: make(chan struct{}),
+ }
+
+ writer.shutdownOnce = sync.OnceFunc(func() { close(writer.stop) })
+
+ go writer.drain()
+
+ return writer, nil
+}
+
+func (w *rotatingFileWriter) Write(line []byte) (int, error) {
+ queued := slices.Clone(line)
+
+ select {
+ case w.queue <- queued:
+ return len(line), nil
+ case <-w.stop:
+ return len(line), nil
+ default:
+ }
+
+ timeout := time.NewTimer(fileEnqueueTimeout)
+ defer timeout.Stop()
+
+ select {
+ case w.queue <- queued:
+ case <-w.stop:
+ case <-timeout.C:
+ w.recordDrop()
+ }
+
+ return len(line), nil
+}
+
+func (w *rotatingFileWriter) Shutdown(ctx context.Context) error {
+ w.shutdownOnce()
+
+ select {
+ case <-w.drained:
+ case <-ctx.Done():
+ return fmt.Errorf("log file writer did not drain in time: %w", ctx.Err())
+ }
+
+ return w.rotator.Close()
+}
+
+func (w *rotatingFileWriter) drain() {
+ defer close(w.drained)
+
+ for {
+ select {
+ case line := <-w.queue:
+ w.writeLine(line)
+
+ case <-w.stop:
+ for {
+ select {
+ case line := <-w.queue:
+ w.writeLine(line)
+ default:
+ return
+ }
+ }
+ }
+ }
+}
+
+func (w *rotatingFileWriter) writeLine(line []byte) {
+ if _, err := w.rotator.Write(line); err != nil {
+ fmt.Fprintf(os.Stderr, "logger: failed to write to log file: %v\n", err)
+ }
+}
+
+// recordDrop reports to stderr rather than through the logger: the sink is saturated at this
+// point, so routing the report back through it would re-enter the very path that is failing.
+func (w *rotatingFileWriter) recordDrop() {
+ dropped := w.droppedCount.Add(1)
+
+ now := time.Now().UTC().UnixNano()
+ lastReportedAt := w.lastDropReportAt.Load()
+
+ if now-lastReportedAt < int64(dropReportInterval) {
+ return
+ }
+
+ if !w.lastDropReportAt.CompareAndSwap(lastReportedAt, now) {
+ return
+ }
+
+ fmt.Fprintf(os.Stderr, "logger: log file queue is full, dropped %d entries so far\n", dropped)
+}
diff --git a/backend/internal/util/logger/file_sink_test.go b/backend/internal/util/logger/file_sink_test.go
new file mode 100644
index 00000000..fee6bf80
--- /dev/null
+++ b/backend/internal/util/logger/file_sink_test.go
@@ -0,0 +1,88 @@
+package logger
+
+import (
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_RotatingFileWriter_OnShutdown_DrainsQueuedLinesToDisk(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "logs", "databasus.log")
+
+ writer, err := newRotatingFileWriter(rotatingFileSpec{path: logPath, maxSizeMB: 5, maxBackups: 3})
+ require.NoError(t, err)
+
+ fileLogger := slog.New(slog.NewJSONHandler(writer, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ fileLogger.Info("backup finished", "database_id", "db-42")
+
+ require.NoError(t, writer.Shutdown(t.Context()))
+
+ writtenLog, err := os.ReadFile(logPath)
+ require.NoError(t, err)
+ assert.Contains(t, string(writtenLog), "backup finished")
+ assert.Contains(t, string(writtenLog), "db-42")
+}
+
+func Test_RotatingFileWriter_WhenSizeExceeded_KeepsAtMostMaxBackupsPlusActive(t *testing.T) {
+ logDirectory := t.TempDir()
+ logPath := filepath.Join(logDirectory, "databasus.log")
+
+ writer, err := newRotatingFileWriter(rotatingFileSpec{path: logPath, maxSizeMB: 1, maxBackups: 3})
+ require.NoError(t, err)
+
+ line := append([]byte(strings.Repeat("x", 8*1024)), '\n')
+ for range 700 {
+ _, writeErr := writer.Write(line)
+ require.NoError(t, writeErr)
+ }
+
+ require.NoError(t, writer.Shutdown(t.Context()))
+
+ logFiles, err := filepath.Glob(filepath.Join(logDirectory, "databasus*.log"))
+ require.NoError(t, err)
+ // Both bounds matter: >1 proves rotation happened at all, <=4 proves it was capped. Asserting
+ // only the upper bound would pass if rotation never ran.
+ assert.Greater(t, len(logFiles), 1, "5.6 MB through a 1 MB limit must rotate")
+ assert.LessOrEqual(t, len(logFiles), 4, "active file plus at most 3 backups")
+
+ for _, logFile := range logFiles {
+ info, statErr := os.Stat(logFile)
+ require.NoError(t, statErr)
+ assert.LessOrEqual(t, info.Size(), int64(2*1024*1024), "file %s", logFile)
+ }
+}
+
+func Test_RotatingFileWriter_AfterShutdown_WriteDoesNotBlockOrPanic(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "databasus.log")
+
+ writer, err := newRotatingFileWriter(rotatingFileSpec{path: logPath, maxSizeMB: 5, maxBackups: 3})
+ require.NoError(t, err)
+ require.NoError(t, writer.Shutdown(t.Context()))
+
+ written, err := writer.Write([]byte("after shutdown\n"))
+
+ require.NoError(t, err)
+ assert.Equal(t, len("after shutdown\n"), written)
+}
+
+func Test_NewRotatingFileWriter_WhenDirectoryIsUnwritable_ReturnsError(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root ignores directory permissions")
+ }
+
+ blockedRoot := filepath.Join(t.TempDir(), "blocked")
+ require.NoError(t, os.Mkdir(blockedRoot, 0o500))
+
+ _, err := newRotatingFileWriter(rotatingFileSpec{
+ path: filepath.Join(blockedRoot, "nested", "databasus.log"),
+ maxSizeMB: 5,
+ maxBackups: 3,
+ })
+
+ require.Error(t, err)
+}
diff --git a/backend/internal/util/logger/logger.go b/backend/internal/util/logger/logger.go
index ad7f94dd..3004f0e3 100644
--- a/backend/internal/util/logger/logger.go
+++ b/backend/internal/util/logger/logger.go
@@ -1,122 +1,148 @@
package logger
import (
+ "context"
+ "errors"
"fmt"
"log/slog"
"os"
- "path/filepath"
"sync"
+ "sync/atomic"
"time"
+)
+
+const (
+ logTypeKey = "log_type"
+ logTypeAudit = "audit"
- "github.com/joho/godotenv"
+ flushOnExitTimeout = 5 * time.Second
)
var (
- loggerInstance *slog.Logger
- victoriaLogsWriter *VictoriaLogsWriter
+ loggerInstance *slog.Logger
+ auditLoggerInstance *slog.Logger
+ sinkShutdowns []func(context.Context) error
+
+ // isInitialized publishes the writes above so Shutdown can read them without initializing.
+ isInitialized atomic.Bool
)
var initLogger = sync.OnceFunc(func() {
- // Create stdout handler
- stdoutHandler := slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
- Level: slog.LevelInfo,
- ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
- if a.Key == slog.TimeKey {
- a.Value = slog.StringValue(time.Now().Format("2006/01/02 15:04:05"))
- }
- if a.Key == slog.LevelKey {
- return slog.Attr{}
- }
- return a
- },
- })
-
- // Try to initialize VictoriaLogs writer if configured
- // Note: This will be called before config is fully loaded in some cases,
- // so we need to handle that gracefully
- victoriaLogsWriter = tryInitVictoriaLogs()
-
- // Create multi-handler
- multiHandler := NewMultiHandler(stdoutHandler, victoriaLogsWriter)
- loggerInstance = slog.New(multiHandler)
-
- loggerInstance.Info("Text structured logger initialized")
- if victoriaLogsWriter != nil {
- loggerInstance.Info("VictoriaLogs enabled")
- } else {
- loggerInstance.Info("VictoriaLogs disabled")
+ loadedSettings := mustLoadSettings()
+
+ level := new(slog.LevelVar)
+ level.Set(loadedSettings.level)
+
+ assembledSinks := buildSinks(loadedSettings)
+ sinkShutdowns = assembledSinks.shutdowns
+
+ fanOut := newFanOutHandler(assembledSinks.handlers, level)
+ loggerInstance = slog.New(fanOut)
+ auditLoggerInstance = slog.New(fanOut.withLevelBypass()).With(logTypeKey, logTypeAudit)
+
+ isInitialized.Store(true)
+
+ for _, failure := range assembledSinks.failures {
+ loggerInstance.Warn(failure.message, "error", failure.err)
}
})
-// GetLogger returns a singleton slog.Logger that logs to the console
func GetLogger() *slog.Logger {
initLogger()
+
return loggerInstance
}
-// ShutdownVictoriaLogs gracefully shuts down the VictoriaLogs writer
-var ShutdownVictoriaLogs = sync.OnceFunc(func() {
- if victoriaLogsWriter != nil {
- victoriaLogsWriter.Shutdown(5 * time.Second)
- }
-})
+// GetAuditLogger's records carry log_type=audit and ignore LOG_LEVEL, so raising the level to
+// error never silently drops the audit trail.
+func GetAuditLogger() *slog.Logger {
+ initLogger()
-func tryInitVictoriaLogs() *VictoriaLogsWriter {
- // Ensure .env is loaded before reading environment variables
- ensureEnvLoaded()
+ return auditLoggerInstance
+}
- // Try to get config - this may fail early in startup
- url := getVictoriaLogsURL()
- username := getVictoriaLogsUsername()
- password := getVictoriaLogsPassword()
+// ExitAfterFlush exists because os.Exit skips deferred work while the file and OTLP sinks buffer:
+// without it the line describing a fatal startup failure - the one an operator actually needs -
+// is the single class of log guaranteed never to reach the forensic copy.
+func ExitAfterFlush(code int) {
+ FlushAndCloseSinks()
+ os.Exit(code)
+}
- if url == "" {
- fmt.Println("VictoriaLogs URL is not set")
- return nil
- }
+// FlushAndCloseSinks is one-way - the file writer stops accepting writes and the OTLP provider
+// becomes a no-op - so it belongs only at process exit. It reports to stderr rather than through
+// the logger: by the time it can fail, the sinks it would report through are the ones it closed.
+func FlushAndCloseSinks() {
+ ctx, cancel := context.WithTimeout(context.Background(), flushOnExitTimeout)
+ defer cancel()
- return NewVictoriaLogsWriter(url, username, password)
+ if err := Shutdown(ctx); err != nil {
+ fmt.Fprintf(os.Stderr, "logger: failed to flush log sinks: %v\n", err)
+ }
}
-var ensureEnvLoaded = sync.OnceFunc(func() {
- cwd, err := os.Getwd()
- if err != nil {
- fmt.Printf("Warning: could not get current working directory: %v\n", err)
- cwd = "."
+// Shutdown deliberately does not initialize: building the sinks only to close them would create
+// the log file on a process that never logged, and would let a malformed OPEN_TELEMETRY_URL exit
+// the process from inside a shutdown path.
+func Shutdown(ctx context.Context) error {
+ if !isInitialized.Load() {
+ return nil
}
- backendRoot := cwd
- for {
- if _, err := os.Stat(filepath.Join(backendRoot, "go.mod")); err == nil {
- break
- }
-
- parent := filepath.Dir(backendRoot)
- if parent == backendRoot {
- break
+ var shutdownErrors []error
+ for _, shutdownSink := range sinkShutdowns {
+ if err := shutdownSink(ctx); err != nil {
+ shutdownErrors = append(shutdownErrors, err)
}
-
- backendRoot = parent
- }
-
- envPath := filepath.Join(filepath.Dir(backendRoot), ".env")
-
- if err := godotenv.Load(envPath); err == nil {
- fmt.Printf("Logger: loaded .env from %s\n", envPath)
- return
}
- fmt.Println("Logger: .env file not found at repo root, using existing environment variables")
-})
+ return errors.Join(shutdownErrors...)
+}
-func getVictoriaLogsURL() string {
- return os.Getenv("VICTORIA_LOGS_URL")
+type sinkFailure struct {
+ message string
+ err error
}
-func getVictoriaLogsUsername() string {
- return os.Getenv("VICTORIA_LOGS_USERNAME")
+type builtSinks struct {
+ handlers []slog.Handler
+ shutdowns []func(context.Context) error
+ failures []sinkFailure
}
-func getVictoriaLogsPassword() string {
- return os.Getenv("VICTORIA_LOGS_PASSWORD")
+// buildSinks reports failures instead of logging them: it runs before the logger exists, and an
+// optional sink that fails to open must not take the process down the way malformed config does.
+func buildSinks(loadedSettings settings) builtSinks {
+ assembledSinks := builtSinks{handlers: []slog.Handler{newStdoutHandler()}}
+
+ if loadedSettings.file.isEnabled {
+ fileWriter, err := newRotatingFileWriter(rotatingFileSpec{
+ path: loadedSettings.file.path,
+ maxSizeMB: logFileMaxSizeMB,
+ maxBackups: logFileMaxBackups,
+ })
+ if err == nil {
+ assembledSinks.handlers = append(assembledSinks.handlers,
+ slog.NewJSONHandler(fileWriter, &slog.HandlerOptions{Level: slog.LevelDebug}))
+ assembledSinks.shutdowns = append(assembledSinks.shutdowns, fileWriter.Shutdown)
+ } else {
+ assembledSinks.failures = append(assembledSinks.failures, sinkFailure{"log file sink disabled", err})
+ }
+ }
+
+ if loadedSettings.openTelemetry != nil {
+ otelHandler, shutdownProvider, err := newOpenTelemetryHandler(
+ context.Background(),
+ *loadedSettings.openTelemetry,
+ loadedSettings.serviceVersion,
+ )
+ if err == nil {
+ assembledSinks.handlers = append(assembledSinks.handlers, otelHandler)
+ assembledSinks.shutdowns = append(assembledSinks.shutdowns, shutdownProvider)
+ } else {
+ assembledSinks.failures = append(assembledSinks.failures, sinkFailure{"otlp log sink disabled", err})
+ }
+ }
+
+ return assembledSinks
}
diff --git a/backend/internal/util/logger/logger_test.go b/backend/internal/util/logger/logger_test.go
new file mode 100644
index 00000000..17c4c5db
--- /dev/null
+++ b/backend/internal/util/logger/logger_test.go
@@ -0,0 +1,133 @@
+package logger
+
+import (
+ "encoding/json"
+ "log/slog"
+ "os"
+ "path/filepath"
+ "strings"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func readLogFileRecords(t *testing.T, logPath string) []map[string]any {
+ t.Helper()
+
+ writtenLog, err := os.ReadFile(logPath)
+ require.NoError(t, err)
+
+ var records []map[string]any
+ for line := range strings.SplitSeq(strings.TrimSpace(string(writtenLog)), "\n") {
+ if line == "" {
+ continue
+ }
+
+ var record map[string]any
+ require.NoError(t, json.Unmarshal([]byte(line), &record))
+ records = append(records, record)
+ }
+
+ return records
+}
+
+// This is the requirement the whole change exists for: an audit entry has to survive on disk even
+// when the level is raised, so it outlives the database it describes.
+func Test_BuildSinks_WithFileEnabled_AuditRecordReachesDiskAtErrorLevel(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "logs", "databasus.log")
+
+ assembledSinks := buildSinks(settings{
+ level: slog.LevelError,
+ file: logFileSettings{isEnabled: true, path: logPath},
+ })
+ require.Empty(t, assembledSinks.failures)
+ require.Len(t, assembledSinks.handlers, 2, "stdout plus file")
+ require.Len(t, assembledSinks.shutdowns, 1)
+
+ level := new(slog.LevelVar)
+ level.Set(slog.LevelError)
+ fanOut := newFanOutHandler(assembledSinks.handlers, level)
+
+ slog.New(fanOut).Info("routine work that should be filtered")
+ slog.New(fanOut.withLevelBypass()).With(logTypeKey, logTypeAudit).
+ Info("Database deleted: payments", "user_id", "user-7")
+
+ for _, shutdown := range assembledSinks.shutdowns {
+ require.NoError(t, shutdown(t.Context()))
+ }
+
+ records := readLogFileRecords(t, logPath)
+ require.Len(t, records, 1, "the info record must be filtered, the audit record must survive")
+ assert.Equal(t, logTypeAudit, records[0][logTypeKey])
+ assert.Equal(t, "Database deleted: payments", records[0]["msg"])
+ assert.Equal(t, "user-7", records[0]["user_id"])
+}
+
+func Test_BuildSinks_WithFileEnabled_RedactsBeforeTouchingDisk(t *testing.T) {
+ logPath := filepath.Join(t.TempDir(), "databasus.log")
+
+ assembledSinks := buildSinks(settings{
+ level: slog.LevelInfo,
+ file: logFileSettings{isEnabled: true, path: logPath},
+ })
+ require.Empty(t, assembledSinks.failures)
+
+ level := new(slog.LevelVar)
+ level.Set(slog.LevelInfo)
+
+ slog.New(newFanOutHandler(assembledSinks.handlers, level)).
+ Info("connecting to postgres://admin:hunter2@db:5432/app", "user_email", "[email protected]")
+
+ for _, shutdown := range assembledSinks.shutdowns {
+ require.NoError(t, shutdown(t.Context()))
+ }
+
+ writtenLog, err := os.ReadFile(logPath)
+ require.NoError(t, err)
+ assert.NotContains(t, string(writtenLog), "hunter2")
+ assert.NotContains(t, string(writtenLog), "[email protected]")
+ assert.Contains(t, string(writtenLog), "db:5432")
+}
+
+func Test_BuildSinks_WhenFileIsDisabled_OnlyStdoutSinkIsBuilt(t *testing.T) {
+ assembledSinks := buildSinks(settings{level: slog.LevelInfo})
+
+ assert.Len(t, assembledSinks.handlers, 1)
+ assert.Empty(t, assembledSinks.shutdowns)
+ assert.Empty(t, assembledSinks.failures)
+}
+
+// An unopenable log file must degrade to a warning, not take the process down the way a malformed
+// OPEN_TELEMETRY_URL does.
+func Test_BuildSinks_WhenLogFileCannotBeOpened_ReportsFailureAndKeepsStdout(t *testing.T) {
+ if os.Geteuid() == 0 {
+ t.Skip("root ignores directory permissions")
+ }
+
+ blockedRoot := filepath.Join(t.TempDir(), "blocked")
+ require.NoError(t, os.Mkdir(blockedRoot, 0o500))
+
+ assembledSinks := buildSinks(settings{
+ level: slog.LevelInfo,
+ file: logFileSettings{
+ isEnabled: true,
+ path: filepath.Join(blockedRoot, "nested", "databasus.log"),
+ },
+ })
+
+ assert.Len(t, assembledSinks.handlers, 1, "stdout survives")
+ require.Len(t, assembledSinks.failures, 1)
+ assert.Equal(t, "log file sink disabled", assembledSinks.failures[0].message)
+ require.Error(t, assembledSinks.failures[0].err)
+}
+
+// Shutdown must not build the pipeline just to close it: that would create the log file on a
+// process that never logged, and a malformed OPEN_TELEMETRY_URL would exit the test binary.
+func Test_Shutdown_WhenLoggerWasNeverInitialized_ReturnsWithoutBuildingSinks(t *testing.T) {
+ require.False(t, isInitialized.Load(), "no test in this package may touch the singleton")
+
+ require.NoError(t, Shutdown(t.Context()))
+
+ assert.False(t, isInitialized.Load())
+}
diff --git a/backend/internal/util/logger/multi_handler.go b/backend/internal/util/logger/multi_handler.go
deleted file mode 100644
index 84bfaac4..00000000
--- a/backend/internal/util/logger/multi_handler.go
+++ /dev/null
@@ -1,65 +0,0 @@
-package logger
-
-import (
- "context"
- "log/slog"
-)
-
-type MultiHandler struct {
- stdoutHandler slog.Handler
- victoriaLogsWriter *VictoriaLogsWriter
-}
-
-func NewMultiHandler(
- stdoutHandler slog.Handler,
- victoriaLogsWriter *VictoriaLogsWriter,
-) *MultiHandler {
- return &MultiHandler{
- stdoutHandler: stdoutHandler,
- victoriaLogsWriter: victoriaLogsWriter,
- }
-}
-
-func (h *MultiHandler) Enabled(ctx context.Context, level slog.Level) bool {
- if h.victoriaLogsWriter != nil {
- return level >= slog.LevelDebug
- }
-
- return h.stdoutHandler.Enabled(ctx, level)
-}
-
-func (h *MultiHandler) Handle(ctx context.Context, record slog.Record) error {
- // Send to stdout handler (only if level is enabled for stdout)
- if h.stdoutHandler.Enabled(ctx, record.Level) {
- if err := h.stdoutHandler.Handle(ctx, record); err != nil {
- return err
- }
- }
-
- // Send to VictoriaLogs if configured
- if h.victoriaLogsWriter != nil {
- attrs := make(map[string]any)
- record.Attrs(func(a slog.Attr) bool {
- attrs[a.Key] = a.Value.Any()
- return true
- })
-
- h.victoriaLogsWriter.Write(record.Level.String(), record.Message, attrs)
- }
-
- return nil
-}
-
-func (h *MultiHandler) WithAttrs(attrs []slog.Attr) slog.Handler {
- return &MultiHandler{
- stdoutHandler: h.stdoutHandler.WithAttrs(attrs),
- victoriaLogsWriter: h.victoriaLogsWriter,
- }
-}
-
-func (h *MultiHandler) WithGroup(name string) slog.Handler {
- return &MultiHandler{
- stdoutHandler: h.stdoutHandler.WithGroup(name),
- victoriaLogsWriter: h.victoriaLogsWriter,
- }
-}
diff --git a/backend/internal/util/logger/otlp_sink.go b/backend/internal/util/logger/otlp_sink.go
new file mode 100644
index 00000000..a46dec87
--- /dev/null
+++ b/backend/internal/util/logger/otlp_sink.go
@@ -0,0 +1,76 @@
+package logger
+
+import (
+ "context"
+ "fmt"
+ "log/slog"
+
+ "go.opentelemetry.io/contrib/bridges/otelslog"
+ "go.opentelemetry.io/otel/attribute"
+ "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
+ "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
+ sdklog "go.opentelemetry.io/otel/sdk/log"
+ "go.opentelemetry.io/otel/sdk/resource"
+ semconv "go.opentelemetry.io/otel/semconv/v1.43.0"
+)
+
+func newOpenTelemetryHandler(
+ ctx context.Context,
+ openTelemetry openTelemetrySettings,
+ serviceVersion string,
+) (slog.Handler, func(context.Context) error, error) {
+ exporter, err := newOpenTelemetryExporter(ctx, openTelemetry)
+ if err != nil {
+ return nil, nil, err
+ }
+
+ provider := sdklog.NewLoggerProvider(
+ sdklog.WithProcessor(sdklog.NewBatchProcessor(exporter)),
+ sdklog.WithResource(newOpenTelemetryResource(serviceVersion)),
+ )
+
+ return otelslog.NewHandler(serviceName, otelslog.WithLoggerProvider(provider)), provider.Shutdown, nil
+}
+
+// newOpenTelemetryExporter passes the endpoint through WithEndpointURL so the path survives
+// verbatim: a Collector listens on /v1/logs, VictoriaLogs on /insert/opentelemetry/v1/logs, and
+// appending a fixed suffix would break one of them.
+func newOpenTelemetryExporter(ctx context.Context, openTelemetry openTelemetrySettings) (sdklog.Exporter, error) {
+ if openTelemetry.isGRPC {
+ exporter, err := otlploggrpc.New(
+ ctx,
+ otlploggrpc.WithEndpointURL(openTelemetry.endpointURL),
+ otlploggrpc.WithHeaders(openTelemetry.headers),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to create OTLP/gRPC log exporter: %w", err)
+ }
+
+ return exporter, nil
+ }
+
+ exporter, err := otlploghttp.New(
+ ctx,
+ otlploghttp.WithEndpointURL(openTelemetry.endpointURL),
+ otlploghttp.WithHeaders(openTelemetry.headers),
+ )
+ if err != nil {
+ return nil, fmt.Errorf("failed to create OTLP/HTTP log exporter: %w", err)
+ }
+
+ return exporter, nil
+}
+
+func newOpenTelemetryResource(serviceVersion string) *resource.Resource {
+ attributes := []attribute.KeyValue{semconv.ServiceName(serviceName)}
+ if serviceVersion != "" {
+ attributes = append(attributes, semconv.ServiceVersion(serviceVersion))
+ }
+
+ merged, err := resource.Merge(resource.Default(), resource.NewWithAttributes(semconv.SchemaURL, attributes...))
+ if err != nil {
+ return resource.NewWithAttributes(semconv.SchemaURL, attributes...)
+ }
+
+ return merged
+}
diff --git a/backend/internal/util/logger/otlp_sink_test.go b/backend/internal/util/logger/otlp_sink_test.go
new file mode 100644
index 00000000..c276d160
--- /dev/null
+++ b/backend/internal/util/logger/otlp_sink_test.go
@@ -0,0 +1,164 @@
+package logger
+
+import (
+ "io"
+ "log/slog"
+ "net/http"
+ "net/http/httptest"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+ "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploggrpc"
+ "go.opentelemetry.io/otel/exporters/otlp/otlplog/otlploghttp"
+ collectorpb "go.opentelemetry.io/proto/otlp/collector/logs/v1"
+ "google.golang.org/protobuf/proto"
+)
+
+type receivedExport struct {
+ headers http.Header
+ request *collectorpb.ExportLogsServiceRequest
+}
+
+func startOTLPHTTPReceiver(t *testing.T) (string, <-chan receivedExport) {
+ t.Helper()
+
+ exports := make(chan receivedExport, 1)
+
+ server := httptest.NewServer(http.HandlerFunc(func(writer http.ResponseWriter, request *http.Request) {
+ body, err := io.ReadAll(request.Body)
+ require.NoError(t, err)
+
+ exportRequest := &collectorpb.ExportLogsServiceRequest{}
+ require.NoError(t, proto.Unmarshal(body, exportRequest))
+
+ select {
+ case exports <- receivedExport{headers: request.Header.Clone(), request: exportRequest}:
+ default:
+ }
+
+ response, err := proto.Marshal(&collectorpb.ExportLogsServiceResponse{})
+ require.NoError(t, err)
+
+ writer.Header().Set("Content-Type", "application/x-protobuf")
+ _, _ = writer.Write(response)
+ }))
+ t.Cleanup(server.Close)
+
+ return server.URL + "/v1/logs", exports
+}
+
+func Test_NewOpenTelemetryHandler_OverHttp_DeliversRecordToEndpoint(t *testing.T) {
+ endpointURL, exports := startOTLPHTTPReceiver(t)
+
+ openTelemetry, err := parseOpenTelemetryEndpoint(endpointURL, map[string]string{"x-tenant": "acme"})
+ require.NoError(t, err)
+ require.NotNil(t, openTelemetry)
+
+ handler, shutdown, err := newOpenTelemetryHandler(t.Context(), *openTelemetry, "3.26.0")
+ require.NoError(t, err)
+
+ slog.New(handler).Info("backup finished", "database_id", "db-42")
+ require.NoError(t, shutdown(t.Context()))
+
+ var export receivedExport
+ select {
+ case export = <-exports:
+ case <-time.After(10 * time.Second):
+ t.Fatal("no OTLP export reached the endpoint")
+ }
+
+ assert.Equal(t, "acme", export.headers.Get("x-tenant"))
+
+ logRecords := export.request.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()
+ require.Len(t, logRecords, 1)
+ assert.Equal(t, "backup finished", logRecords[0].GetBody().GetStringValue())
+
+ attributesByKey := map[string]string{}
+ for _, attribute := range logRecords[0].GetAttributes() {
+ attributesByKey[attribute.GetKey()] = attribute.GetValue().GetStringValue()
+ }
+ assert.Equal(t, "db-42", attributesByKey["database_id"])
+}
+
+func Test_NewOpenTelemetryHandler_WithEncodedHeaderValue_SendsItDecodedOnTheWire(t *testing.T) {
+ endpointURL, exports := startOTLPHTTPReceiver(t)
+
+ headers, err := parseOpenTelemetryHeaders("VL-Extra-Fields=host%3Dweb1%2Cdc%3Deu")
+ require.NoError(t, err)
+
+ openTelemetry, err := parseOpenTelemetryEndpoint(endpointURL, headers)
+ require.NoError(t, err)
+ require.NotNil(t, openTelemetry)
+
+ handler, shutdown, err := newOpenTelemetryHandler(t.Context(), *openTelemetry, "")
+ require.NoError(t, err)
+
+ slog.New(handler).Info("storage created")
+ require.NoError(t, shutdown(t.Context()))
+
+ var export receivedExport
+ select {
+ case export = <-exports:
+ case <-time.After(10 * time.Second):
+ t.Fatal("no OTLP export reached the endpoint")
+ }
+
+ assert.Equal(t, "host=web1,dc=eu", export.headers.Get("VL-Extra-Fields"))
+}
+
+func Test_NewOpenTelemetryHandler_WithScopedAttrs_ShipsThemWithTheRecord(t *testing.T) {
+ endpointURL, exports := startOTLPHTTPReceiver(t)
+
+ openTelemetry, err := parseOpenTelemetryEndpoint(endpointURL, map[string]string{})
+ require.NoError(t, err)
+
+ handler, shutdown, err := newOpenTelemetryHandler(t.Context(), *openTelemetry, "")
+ require.NoError(t, err)
+
+ slog.New(handler).With("workspace_id", "ws-7").Info("storage created")
+ require.NoError(t, shutdown(t.Context()))
+
+ var export receivedExport
+ select {
+ case export = <-exports:
+ case <-time.After(10 * time.Second):
+ t.Fatal("no OTLP export reached the endpoint")
+ }
+
+ logRecords := export.request.GetResourceLogs()[0].GetScopeLogs()[0].GetLogRecords()
+ require.Len(t, logRecords, 1)
+
+ attributesByKey := map[string]string{}
+ for _, attribute := range logRecords[0].GetAttributes() {
+ attributesByKey[attribute.GetKey()] = attribute.GetValue().GetStringValue()
+ }
+ assert.Equal(t, "ws-7", attributesByKey["workspace_id"])
+}
+
+// The gRPC transport is covered by branch selection only; an end-to-end gRPC round trip would need
+// a registered LogsServiceServer for one assertion the manual Collector check already makes.
+// otlploggrpc.New dials lazily and never errors here, so the exporter type is the real assertion -
+// without it the HTTP branch would satisfy this test just as well.
+func Test_NewOpenTelemetryExporter_WithGrpcScheme_SelectsTheGrpcExporter(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint("grpc://localhost:4317", map[string]string{})
+ require.NoError(t, err)
+
+ exporter, err := newOpenTelemetryExporter(t.Context(), *openTelemetry)
+ require.NoError(t, err)
+
+ require.IsType(t, &otlploggrpc.Exporter{}, exporter)
+ require.NoError(t, exporter.Shutdown(t.Context()))
+}
+
+func Test_NewOpenTelemetryExporter_WithHttpScheme_SelectsTheHttpExporter(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint("http://localhost:4318/v1/logs", map[string]string{})
+ require.NoError(t, err)
+
+ exporter, err := newOpenTelemetryExporter(t.Context(), *openTelemetry)
+ require.NoError(t, err)
+
+ require.IsType(t, &otlploghttp.Exporter{}, exporter)
+ require.NoError(t, exporter.Shutdown(t.Context()))
+}
diff --git a/backend/internal/util/logger/redaction.go b/backend/internal/util/logger/redaction.go
new file mode 100644
index 00000000..ac8ba349
--- /dev/null
+++ b/backend/internal/util/logger/redaction.go
@@ -0,0 +1,212 @@
+package logger
+
+import (
+ "fmt"
+ "log/slog"
+ "net/url"
+ "regexp"
+ "strings"
+)
+
+const redactedValue = "***"
+
+var (
+ // "webhook" belongs here rather than with the URL keys: an incoming-webhook URL is itself the
+ // credential, and its secret sits in the path, where stripping userinfo would not reach it.
+ secretKeyParts = []string{
+ "password", "passwd", "secret", "token", "api_key", "apikey",
+ "authorization", "cookie", "credential", "private_key", "webhook",
+ }
+ urlKeyParts = []string{"url", "uri", "dsn", "endpoint", "conn"}
+ emailKeyParts = []string{"email", "mail"}
+
+ urlCredentialsPattern = regexp.MustCompile(`([a-zA-Z][a-zA-Z0-9+.-]*)://[^\s:/@]+:[^\s@]*@`)
+ keyValueSecretPattern = regexp.MustCompile(
+ `(?i)\b(password|passwd|secret|token|api[_-]?key|authorization)\s*=\s*\S+`,
+ )
+ // Header-shaped secrets use a colon, not "=", so the key=value pattern never sees them. The auth
+ // scheme is kept because knowing which one was sent is diagnostic; the credential is not.
+ headerSecretPattern = regexp.MustCompile(
+ `(?i)\b(password|passwd|secret|token|api[_-]?key|authorization)(\s*:\s*)` +
+ `((?:bearer|basic|digest|token)\s+)?(\S+)`,
+ )
+ emailPattern = regexp.MustCompile(`[\w.+-]+@[\w-]+(?:\.[\w-]+)+`)
+)
+
+func redactAttr(attr slog.Attr) slog.Attr {
+ attr.Value = attr.Value.Resolve()
+
+ if attr.Value.Kind() == slog.KindGroup {
+ group := attr.Value.Group()
+
+ redactedGroup := make([]slog.Attr, 0, len(group))
+ for _, member := range group {
+ redactedGroup = append(redactedGroup, redactAttr(member))
+ }
+
+ attr.Value = slog.GroupValue(redactedGroup...)
+
+ return attr
+ }
+
+ key := strings.ToLower(attr.Key)
+
+ // Numbers keep their type even under a secret-looking key: "token_count" is a diagnostic, not a
+ // secret, and blanking it loses information without protecting anything.
+ if hasAnyPart(key, secretKeyParts) && !isNumericLike(attr.Value) {
+ attr.Value = slog.StringValue(redactedValue)
+
+ return attr
+ }
+
+ // "error" is the most common attr key in this codebase and errors are KindAny, so without this
+ // an error text carrying a DSN - url.Error formats the whole URL, password included - would
+ // reach the file and the remote backend untouched.
+ if wrapped, isError := attr.Value.Any().(error); isError {
+ attr.Value = slog.StringValue(redactMessage(wrapped.Error()))
+
+ return attr
+ }
+
+ isText := attr.Value.Kind() == slog.KindString
+
+ switch {
+ // These keys are semantically textual, so rendering a non-string value to a scrubbed string is
+ // safe. Numeric look-alikes such as "connection_count" or "endpoint_timeout" are not: they
+ // match the same substring lists, and retyping them would corrupt the record.
+ case hasAnyPart(key, urlKeyParts) && (isText || isRenderableText(attr.Value)):
+ attr.Value = slog.StringValue(stripURLCredentials(attr.Value.String()))
+ case hasAnyPart(key, emailKeyParts) && (isText || isRenderableText(attr.Value)):
+ attr.Value = slog.StringValue(maskEmails(attr.Value.String()))
+ case isText:
+ attr.Value = slog.StringValue(redactMessage(attr.Value.String()))
+ // A struct or map handed to slog.Any matches none of the arms above, so without this a DTO or a
+ // header map carrying a password would reach the sinks verbatim. The rendered form is kept only
+ // when it actually held a secret: rendering costs the typed value, and this runs on every record.
+ case attr.Value.Kind() == slog.KindAny:
+ rendered := fmt.Sprintf("%+v", attr.Value.Any())
+
+ if scrubbed := redactMessage(rendered); scrubbed != rendered {
+ attr.Value = slog.StringValue(scrubbed)
+ }
+ }
+
+ return attr
+}
+
+// Credentials and addresses reach the message through fmt.Sprintf at call sites - audit messages
+// in particular embed raw user emails, and those messages are now exported off-box.
+// The strings.Contains guards keep three regex scans off the hot path: this runs on every record,
+// and the overwhelming majority of messages contain none of these markers.
+func redactMessage(message string) string {
+ if strings.Contains(message, "://") {
+ message = urlCredentialsPattern.ReplaceAllString(message, "$1://"+redactedValue+":"+redactedValue+"@")
+ }
+
+ if strings.Contains(message, "=") {
+ message = keyValueSecretPattern.ReplaceAllString(message, "$1="+redactedValue)
+ }
+
+ if strings.Contains(message, ":") {
+ message = redactHeaderSecrets(message)
+ }
+
+ return maskEmails(message)
+}
+
+// A purely numeric value is a count, not a credential - the same carve-out redactAttr makes for
+// "token_count" - so "replication token: 5 slots" survives intact. Sentence punctuation is split
+// off first, because \S+ swallows it and would make "token: 5," look non-numeric.
+func redactHeaderSecrets(message string) string {
+ return headerSecretPattern.ReplaceAllStringFunc(message, func(match string) string {
+ groups := headerSecretPattern.FindStringSubmatch(match)
+ secretKey, separator, authScheme, value := groups[1], groups[2], groups[3], groups[4]
+
+ value, trailingPunctuation := splitTrailingPunctuation(value)
+
+ if isAllDigits(value) {
+ return match
+ }
+
+ return secretKey + separator + authScheme + redactedValue + trailingPunctuation
+ })
+}
+
+func splitTrailingPunctuation(value string) (string, string) {
+ trimmed := strings.TrimRight(value, ".,;:!?)]}")
+
+ return trimmed, value[len(trimmed):]
+}
+
+func isAllDigits(value string) bool {
+ if value == "" {
+ return false
+ }
+
+ return strings.IndexFunc(value, func(character rune) bool {
+ return character < '0' || character > '9'
+ }) < 0
+}
+
+func hasAnyPart(key string, parts []string) bool {
+ for _, part := range parts {
+ if strings.Contains(key, part) {
+ return true
+ }
+ }
+
+ return false
+}
+
+func isNumericLike(value slog.Value) bool {
+ switch value.Kind() {
+ case slog.KindInt64, slog.KindUint64, slog.KindFloat64, slog.KindBool,
+ slog.KindDuration, slog.KindTime:
+ return true
+ default:
+ return false
+ }
+}
+
+func isRenderableText(value slog.Value) bool {
+ if value.Kind() != slog.KindAny {
+ return false
+ }
+
+ _, isStringer := value.Any().(fmt.Stringer)
+
+ return isStringer
+}
+
+// stripURLCredentials keeps the host readable instead of blanking the whole value - an endpoint
+// nobody can identify is useless when diagnosing where logs are going.
+func stripURLCredentials(value string) string {
+ parsed, err := url.Parse(value)
+ if err != nil || parsed.User == nil {
+ // Not a bare URL, so fall through to the full message scrub rather than the key=value
+ // pattern alone - that pattern does not match userinfo, and a value like
+ // "connecting to postgres://admin:pw@db/app" would otherwise pass through intact.
+ return redactMessage(value)
+ }
+
+ // A literal "***" would be percent-encoded by url.String(); this marker survives round-tripping
+ // while still showing that credentials were present.
+ parsed.User = url.User("redacted")
+
+ return parsed.String()
+}
+
+func maskEmails(value string) string {
+ if !strings.Contains(value, "@") {
+ return value
+ }
+
+ return emailPattern.ReplaceAllStringFunc(value, func(address string) string {
+ localPart, domain, isFound := strings.Cut(address, "@")
+ if !isFound || localPart == "" {
+ return address
+ }
+
+ return localPart[:1] + redactedValue + "@" + domain
+ })
+}
diff --git a/backend/internal/util/logger/redaction_test.go b/backend/internal/util/logger/redaction_test.go
new file mode 100644
index 00000000..e24512e1
--- /dev/null
+++ b/backend/internal/util/logger/redaction_test.go
@@ -0,0 +1,205 @@
+package logger
+
+import (
+ "context"
+ "log/slog"
+ "net/url"
+ "testing"
+ "time"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_RedactAttr_WithSecretKeyNames_ReplacesValue(t *testing.T) {
+ secretKeys := []string{
+ "password", "db_passwd", "client_secret", "access_token",
+ "api_key", "apikey", "Authorization", "cookie", "aws_credential", "private_key",
+ }
+
+ for _, key := range secretKeys {
+ redactedAttr := redactAttr(slog.String(key, "hunter2"))
+
+ assert.Equal(t, redactedValue, redactedAttr.Value.String(), "key %q", key)
+ }
+}
+
+func Test_RedactAttr_WithUrlKey_StripsCredentialsButKeepsHost(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("endpoint_url", "https://viewer:[email protected]/v1/logs"))
+
+ assert.Equal(t, "https://[email protected]/v1/logs", redactedAttr.Value.String())
+}
+
+func Test_RedactAttr_WithKeyValueDsn_RedactsOnlyThePassword(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("dsn", "host=localhost user=postgres password=Q1234567 dbname=databasus"))
+
+ assert.Equal(
+ t,
+ "host=localhost user=postgres password="+redactedValue+" dbname=databasus",
+ redactedAttr.Value.String(),
+ )
+}
+
+func Test_RedactAttr_WithEmailKey_MasksLocalPartAndKeepsDomain(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("user_email", "[email protected]"))
+
+ assert.Equal(t, "r"+redactedValue+"@acme.com", redactedAttr.Value.String())
+}
+
+func Test_RedactAttr_WithNestedGroup_RedactsGroupMembers(t *testing.T) {
+ redactedAttr := redactAttr(slog.Group("storage",
+ slog.String("bucket", "backups"),
+ slog.Group("auth", slog.String("secret_key", "sk-live-1234")),
+ ))
+
+ require.Equal(t, slog.KindGroup, redactedAttr.Value.Kind())
+
+ outerMembers := redactedAttr.Value.Group()
+ assert.Equal(t, "backups", outerMembers[0].Value.String())
+
+ innerMembers := outerMembers[1].Value.Group()
+ assert.Equal(t, redactedValue, innerMembers[0].Value.String())
+}
+
+// "error" is the codebase's most common attr key and url.Error embeds the whole URL.
+func Test_RedactAttr_WithErrorCarryingDsn_ScrubsCredentialsFromErrorText(t *testing.T) {
+ _, parseErr := url.Parse("postgres://postgres:Q1234567@localhost:5437/databasus\n")
+ require.Error(t, parseErr)
+
+ redactedAttr := redactAttr(slog.Any("error", parseErr))
+
+ assert.NotContains(t, redactedAttr.Value.String(), "Q1234567")
+ assert.Contains(t, redactedAttr.Value.String(), "localhost:5437")
+}
+
+func Test_RedactAttr_WithNonStringValue_KeepsOriginalKind(t *testing.T) {
+ assert.Equal(t, slog.KindInt64, redactAttr(slog.Int("connection_count", 5)).Value.Kind())
+ assert.EqualValues(t, 5, redactAttr(slog.Int("connection_count", 5)).Value.Int64())
+ assert.Equal(t, slog.KindDuration, redactAttr(slog.Duration("endpoint_timeout", time.Second)).Value.Kind())
+}
+
+func Test_RedactAttr_WithArbitraryStringHoldingSecret_ScrubsIt(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("command", "mongodump --uri=mongodb://root:hunter2@db:27017"))
+
+ assert.NotContains(t, redactedAttr.Value.String(), "hunter2")
+}
+
+// A url-keyed attr whose value is prose rather than a bare URL must not get weaker treatment than
+// any other key: url.Parse fails on it, so the fallback has to be the full message scrub.
+func Test_RedactAttr_WithUrlKeyHoldingProse_ScrubsEmbeddedCredentials(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("endpoint", "connecting to postgres://admin:hunter2@db:5432/app"))
+
+ assert.NotContains(t, redactedAttr.Value.String(), "hunter2")
+}
+
+func Test_RedactAttr_WithHarmlessKey_LeavesValueAlone(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("database_id", "db-42"))
+
+ assert.Equal(t, "db-42", redactedAttr.Value.String())
+}
+
+func Test_RedactMessage_WithUrlCredentials_ReplacesUserAndPassword(t *testing.T) {
+ redactedMessage := redactMessage("restoring from mongodb://admin:[email protected]/db")
+
+ assert.Equal(
+ t,
+ "restoring from mongodb://"+redactedValue+":"+redactedValue+"@cluster0.example.net/db",
+ redactedMessage,
+ )
+}
+
+func Test_RedactMessage_WithKeyValueSecret_ReplacesOnlyTheSecret(t *testing.T) {
+ redactedMessage := redactMessage("connecting with host=localhost password=Q1234567")
+
+ assert.Equal(t, "connecting with host=localhost password="+redactedValue, redactedMessage)
+}
+
+// Audit messages embed raw addresses via fmt.Sprintf, and the dual-write ships them off-box.
+func Test_RedactMessage_WithAuditEmailMessage_MasksAddress(t *testing.T) {
+ redactedMessage := redactMessage("User deactivated: [email protected]")
+
+ assert.Equal(t, "User deactivated: r"+redactedValue+"@acme.com", redactedMessage)
+}
+
+func Test_RedactMessage_WithNothingSensitive_LeavesMessageAlone(t *testing.T) {
+ assert.Equal(t, "backup finished: 12 GB", redactMessage("backup finished: 12 GB"))
+}
+
+func Test_RedactMessage_WithBearerHeader_RemovesCredential(t *testing.T) {
+ scrubbed := redactMessage("upstream rejected us, sent Authorization: Bearer eyJhbGciOiJIUzI1NiJ9.abc.def")
+
+ assert.NotContains(t, scrubbed, "eyJhbGciOiJIUzI1NiJ9.abc.def")
+ assert.Contains(t, scrubbed, "Bearer")
+}
+
+func Test_RedactMessage_WithSchemelessTokenHeader_RemovesCredential(t *testing.T) {
+ assert.NotContains(t, redactMessage("x-api-key: sk-live-abc123"), "sk-live-abc123")
+}
+
+func Test_RedactMessage_WithNumericTokenValue_LeavesItIntact(t *testing.T) {
+ counts := []string{
+ "replication token: 5 slots",
+ "replication token: 5, and more",
+ "replication token: 5.",
+ "replication token: 5",
+ }
+
+ for _, message := range counts {
+ assert.Equal(t, message, redactMessage(message))
+ }
+}
+
+func Test_RedactMessage_WithSecretFollowedByPunctuation_KeepsThePunctuation(t *testing.T) {
+ scrubbed := redactMessage("rejected, sent token: sk-live-abc123, retrying")
+
+ assert.NotContains(t, scrubbed, "sk-live-abc123")
+ assert.Contains(t, scrubbed, ", retrying")
+}
+
+func Test_RedactAttr_WithWebhookUrlKey_ReplacesWholeValue(t *testing.T) {
+ redactedAttr := redactAttr(slog.String("webhook_url", "https://discord.com/api/webhooks/999/SECRETTOKEN"))
+
+ assert.Equal(t, redactedValue, redactedAttr.Value.String())
+}
+
+func Test_RedactAttr_WithStructValue_RemovesCredential(t *testing.T) {
+ credentials := struct {
+ Host string
+ Password string
+ }{Host: "db.example.com", Password: "hunter2"}
+
+ redactedAttr := redactAttr(slog.Any("connection", credentials))
+
+ assert.NotContains(t, redactedAttr.Value.String(), "hunter2")
+ assert.Contains(t, redactedAttr.Value.String(), "db.example.com")
+}
+
+func Test_RedactAttr_WithMapValue_RemovesCredential(t *testing.T) {
+ headers := map[string]string{"authorization": "Bearer secrettokenvalue"}
+
+ assert.NotContains(t, redactAttr(slog.Any("headers", headers)).Value.String(), "secrettokenvalue")
+}
+
+func Test_RedactMessage_WithTimestampsAndRatios_LeavesThemIntact(t *testing.T) {
+ untouched := []string{
+ "backup completed in 01:23:45",
+ "chain cleanup progress: 12 wal, 3 incr, complete=true",
+ "listening on 0.0.0.0:4005",
+ }
+
+ for _, message := range untouched {
+ assert.Equal(t, message, redactMessage(message))
+ }
+}
+
+// Services hold a process-wide logger, so the principal has to ride the context the controllers
+// already pass down; without it only the access line knows who made the request.
+func Test_ContextWithUserID_WhenReadBack_ReturnsTheSamePrincipal(t *testing.T) {
+ ctx := ContextWithUserID(context.Background(), "user-42")
+
+ assert.Equal(t, "user-42", GetUserID(ctx))
+}
+
+func Test_GetUserID_WithNoPrincipalOnTheContext_ReturnsEmpty(t *testing.T) {
+ assert.Empty(t, GetUserID(context.Background()))
+}
diff --git a/backend/internal/util/logger/request_context.go b/backend/internal/util/logger/request_context.go
new file mode 100644
index 00000000..f5ef4870
--- /dev/null
+++ b/backend/internal/util/logger/request_context.go
@@ -0,0 +1,34 @@
+package logger
+
+import "context"
+
+const (
+ requestIDKey = "request_id"
+ userIDKey = "user_id"
+)
+
+type requestIDContextKey struct{}
+
+type userIDContextKey struct{}
+
+func ContextWithRequestID(ctx context.Context, requestID string) context.Context {
+ return context.WithValue(ctx, requestIDContextKey{}, requestID)
+}
+
+func GetRequestID(ctx context.Context) string {
+ requestID, _ := ctx.Value(requestIDContextKey{}).(string)
+
+ return requestID
+}
+
+// The principal rides the context for the same reason the request ID does: services hold a
+// process-wide logger, so there is no scoped logger to attach it to.
+func ContextWithUserID(ctx context.Context, userID string) context.Context {
+ return context.WithValue(ctx, userIDContextKey{}, userID)
+}
+
+func GetUserID(ctx context.Context) string {
+ userID, _ := ctx.Value(userIDContextKey{}).(string)
+
+ return userID
+}
diff --git a/backend/internal/util/logger/settings.go b/backend/internal/util/logger/settings.go
new file mode 100644
index 00000000..43b3c748
--- /dev/null
+++ b/backend/internal/util/logger/settings.go
@@ -0,0 +1,245 @@
+package logger
+
+import (
+ "encoding/base64"
+ "errors"
+ "fmt"
+ "log/slog"
+ "net/url"
+ "os"
+ "path/filepath"
+ "strings"
+ "sync"
+
+ "github.com/joho/godotenv"
+)
+
+const (
+ logFileMaxSizeMB = 5
+ logFileMaxBackups = 3
+
+ serviceName = "databasus"
+)
+
+type logFileSettings struct {
+ isEnabled bool
+ path string
+}
+
+type openTelemetrySettings struct {
+ endpointURL string
+ isGRPC bool
+ headers map[string]string
+}
+
+type settings struct {
+ level slog.Level
+ serviceVersion string
+ file logFileSettings
+ openTelemetry *openTelemetrySettings
+}
+
+// ADR-0014: a malformed endpoint or header is a typo whose only alternative is shipping no logs
+// and no error.
+func mustLoadSettings() settings {
+ ensureEnvLoaded()
+
+ headers, err := parseOpenTelemetryHeaders(os.Getenv("OPEN_TELEMETRY_HEADERS"))
+ if err != nil {
+ exitOnBrokenLoggingConfiguration(err)
+ }
+
+ openTelemetry, err := parseOpenTelemetryEndpoint(os.Getenv("OPEN_TELEMETRY_URL"), headers)
+ if err != nil {
+ exitOnBrokenLoggingConfiguration(err)
+ }
+
+ return settings{
+ level: parseLevel(os.Getenv("LOG_LEVEL")),
+ serviceVersion: os.Getenv("APP_VERSION"),
+ file: parseLogFileSettings(),
+ openTelemetry: openTelemetry,
+ }
+}
+
+func exitOnBrokenLoggingConfiguration(err error) {
+ fmt.Fprintln(os.Stderr, err.Error())
+ os.Exit(1)
+}
+
+func parseLevel(rawLevel string) slog.Level {
+ switch strings.ToLower(strings.TrimSpace(rawLevel)) {
+ case "":
+ return slog.LevelInfo
+ case "debug":
+ return slog.LevelDebug
+ case "info":
+ return slog.LevelInfo
+ case "warn", "warning":
+ return slog.LevelWarn
+ case "error":
+ return slog.LevelError
+ }
+
+ fmt.Fprintf(os.Stderr, "LOG_LEVEL %q is not one of debug, info, warn, error - falling back to info\n", rawLevel)
+
+ return slog.LevelInfo
+}
+
+// The file is the forensic copy an operator reaches for when stdout is already gone, so only an
+// explicit opt-out turns it off. Its location and rotation limits are fixed: it shares the data
+// volume with secret.key, and a path outside that volume would not survive a container restart.
+func parseLogFileSettings() logFileSettings {
+ return logFileSettings{
+ isEnabled: !strings.EqualFold(strings.TrimSpace(os.Getenv("LOG_FILE_IS_ENABLED")), "false"),
+ path: filepath.Join(getDataFolder(), serviceName+".log"),
+ }
+}
+
+// parseOpenTelemetryHeaders deliberately matches the format of the standard
+// OTEL_EXPORTER_OTLP_HEADERS variable, percent-decoding included: that is the only way to write a
+// value containing the separator, and VictoriaLogs takes comma-separated lists in VL-Stream-Fields
+// and VL-Extra-Fields. Errors name the position rather than the entry, since these carry tokens
+// and stderr is collected.
+func parseOpenTelemetryHeaders(rawHeaders string) (map[string]string, error) {
+ headers := make(map[string]string)
+
+ for index, pair := range strings.Split(rawHeaders, ",") {
+ if strings.TrimSpace(pair) == "" {
+ continue
+ }
+
+ key, encodedValue, isPair := strings.Cut(pair, "=")
+
+ key = strings.TrimSpace(key)
+ if !isPair || key == "" {
+ return nil, fmt.Errorf("OPEN_TELEMETRY_HEADERS entry %d is not key=value", index+1)
+ }
+
+ value, err := url.PathUnescape(strings.TrimSpace(encodedValue))
+ if err != nil {
+ return nil, fmt.Errorf("OPEN_TELEMETRY_HEADERS entry %d has a broken percent escape", index+1)
+ }
+
+ headers[key] = value
+ }
+
+ return headers, nil
+}
+
+// parseOpenTelemetryEndpoint rejects a missing or unknown scheme rather than guessing: SigNoz and
+// friends document bare "host:443" endpoints, and treating those as HTTP yields neither logs nor
+// an error. grpc:// and grpcs:// are Databasus-level schemes - the gRPC exporter only understands
+// http/https and derives TLS from the scheme, so they are translated here.
+func parseOpenTelemetryEndpoint(rawURL string, headers map[string]string) (*openTelemetrySettings, error) {
+ rawURL = strings.TrimSpace(rawURL)
+ if rawURL == "" {
+ return nil, nil
+ }
+
+ // Every error below reports the endpoint via reportableEndpoint or not at all: .env.example
+ // tells operators to put credentials in this variable, and these messages go to stderr, which
+ // is collected. A url.Error formats the whole raw URL, so it must not be wrapped either.
+ endpoint, err := url.Parse(rawURL)
+ if err != nil {
+ return nil, errors.New("OPEN_TELEMETRY_URL is not a valid URL")
+ }
+
+ reportableEndpoint := getReportableEndpoint(endpoint)
+
+ isGRPC := endpoint.Scheme == "grpc" || endpoint.Scheme == "grpcs"
+
+ switch endpoint.Scheme {
+ case "http", "grpc":
+ endpoint.Scheme = "http"
+ case "https", "grpcs":
+ endpoint.Scheme = "https"
+ default:
+ return nil, fmt.Errorf(
+ "OPEN_TELEMETRY_URL must start with http://, https://, grpc:// or grpcs://, got %q",
+ reportableEndpoint,
+ )
+ }
+
+ if endpoint.Host == "" {
+ return nil, fmt.Errorf("OPEN_TELEMETRY_URL is missing a host: %q", reportableEndpoint)
+ }
+
+ // The exporter builds its request URL from host and path alone, so a query string would be
+ // dropped without a word. Ingest options belong in OPEN_TELEMETRY_HEADERS: VictoriaLogs accepts
+ // every one of its params as a VL-* header, and OTLP/gRPC has no query to carry them in.
+ if endpoint.RawQuery != "" || endpoint.Fragment != "" {
+ return nil, errors.New("OPEN_TELEMETRY_URL must not carry a query string or fragment, " +
+ "pass ingest options as headers in OPEN_TELEMETRY_HEADERS instead")
+ }
+
+ if authorization, isPresent := takeBasicAuthorization(endpoint); isPresent && !hasAuthorization(headers) {
+ headers["Authorization"] = authorization
+ }
+
+ return &openTelemetrySettings{
+ endpointURL: endpoint.String(),
+ isGRPC: isGRPC,
+ headers: headers,
+ }, nil
+}
+
+// getReportableEndpoint drops the query and the fragment as well as the password, since a
+// mistyped endpoint is often one where an ingestion key was pasted as a query param.
+func getReportableEndpoint(endpoint *url.URL) string {
+ withoutIngestOptions := *endpoint
+ withoutIngestOptions.RawQuery = ""
+ withoutIngestOptions.Fragment = ""
+
+ return withoutIngestOptions.Redacted()
+}
+
+func takeBasicAuthorization(endpoint *url.URL) (string, bool) {
+ if endpoint.User == nil {
+ return "", false
+ }
+
+ password, _ := endpoint.User.Password()
+ credentials := endpoint.User.Username() + ":" + password
+ endpoint.User = nil
+
+ return "Basic " + base64.StdEncoding.EncodeToString([]byte(credentials)), true
+}
+
+func hasAuthorization(headers map[string]string) bool {
+ for key := range headers {
+ if strings.EqualFold(key, "Authorization") {
+ return true
+ }
+ }
+
+ return false
+}
+
+func getDataFolder() string {
+ return filepath.Join(filepath.Dir(getBackendRoot()), "databasus-data")
+}
+
+func getBackendRoot() string {
+ backendRoot, err := os.Getwd()
+ if err != nil {
+ return "."
+ }
+
+ for {
+ if _, err := os.Stat(filepath.Join(backendRoot, "go.mod")); err == nil {
+ return backendRoot
+ }
+
+ parent := filepath.Dir(backendRoot)
+ if parent == backendRoot {
+ return backendRoot
+ }
+
+ backendRoot = parent
+ }
+}
+
+var ensureEnvLoaded = sync.OnceFunc(func() {
+ _ = godotenv.Load(filepath.Join(filepath.Dir(getBackendRoot()), ".env"))
+})
diff --git a/backend/internal/util/logger/settings_test.go b/backend/internal/util/logger/settings_test.go
new file mode 100644
index 00000000..bbf3f410
--- /dev/null
+++ b/backend/internal/util/logger/settings_test.go
@@ -0,0 +1,188 @@
+package logger
+
+import (
+ "encoding/base64"
+ "log/slog"
+ "path/filepath"
+ "testing"
+
+ "github.com/stretchr/testify/assert"
+ "github.com/stretchr/testify/require"
+)
+
+func Test_ParseLevel_WithEachSupportedName_ReturnsMatchingLevel(t *testing.T) {
+ levelsByName := map[string]slog.Level{
+ "debug": slog.LevelDebug,
+ "DEBUG": slog.LevelDebug,
+ " info ": slog.LevelInfo,
+ "warn": slog.LevelWarn,
+ "warning": slog.LevelWarn,
+ "error": slog.LevelError,
+ "": slog.LevelInfo,
+ "loudest": slog.LevelInfo,
+ }
+
+ for name, level := range levelsByName {
+ assert.Equal(t, level, parseLevel(name), "level name %q", name)
+ }
+}
+
+func Test_ParseOpenTelemetryEndpoint_WhenUrlIsEmpty_DisablesSink(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint(" ", map[string]string{})
+
+ require.NoError(t, err)
+ assert.Nil(t, openTelemetry)
+}
+
+func Test_ParseOpenTelemetryEndpoint_WithHttpScheme_KeepsPathVerbatim(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint(
+ "http://victorialogs:9428/insert/opentelemetry/v1/logs",
+ map[string]string{},
+ )
+
+ require.NoError(t, err)
+ require.NotNil(t, openTelemetry)
+ assert.False(t, openTelemetry.isGRPC)
+ assert.Equal(t, "http://victorialogs:9428/insert/opentelemetry/v1/logs", openTelemetry.endpointURL)
+}
+
+func Test_ParseOpenTelemetryEndpoint_WithGrpcSchemes_TranslatesToHttpForExporter(t *testing.T) {
+ insecureEndpoint, err := parseOpenTelemetryEndpoint("grpc://graylog:4317", map[string]string{})
+ require.NoError(t, err)
+ require.NotNil(t, insecureEndpoint)
+ assert.True(t, insecureEndpoint.isGRPC)
+ assert.Equal(t, "http://graylog:4317", insecureEndpoint.endpointURL)
+
+ secureEndpoint, err := parseOpenTelemetryEndpoint("grpcs://ingest.signoz.cloud:443", map[string]string{})
+ require.NoError(t, err)
+ require.NotNil(t, secureEndpoint)
+ assert.True(t, secureEndpoint.isGRPC)
+ assert.Equal(t, "https://ingest.signoz.cloud:443", secureEndpoint.endpointURL)
+}
+
+func Test_ParseOpenTelemetryEndpoint_WithMissingOrUnknownScheme_ReturnsError(t *testing.T) {
+ rejectedURLs := []string{"ingest.eu.signoz.cloud:443", "ftp://logs:9428", "//logs:9428/v1/logs"}
+
+ for _, rejectedURL := range rejectedURLs {
+ openTelemetry, err := parseOpenTelemetryEndpoint(rejectedURL, map[string]string{})
+
+ require.Error(t, err, "URL %q", rejectedURL)
+ assert.Nil(t, openTelemetry)
+ assert.Contains(t, err.Error(), "OPEN_TELEMETRY_URL")
+ }
+}
+
+func Test_ParseOpenTelemetryEndpoint_WithQueryOrFragment_ReturnsErrorPointingAtHeaders(t *testing.T) {
+ rejectedURLs := []string{
+ "http://victorialogs:9428/insert/opentelemetry/v1/logs?_stream_fields=host",
+ "http://victorialogs:9428/insert/opentelemetry/v1/logs#logs",
+ }
+
+ for _, rejectedURL := range rejectedURLs {
+ openTelemetry, err := parseOpenTelemetryEndpoint(rejectedURL, map[string]string{})
+
+ require.Error(t, err, "URL %q", rejectedURL)
+ assert.Nil(t, openTelemetry)
+ assert.Contains(t, err.Error(), "OPEN_TELEMETRY_HEADERS")
+ }
+}
+
+func Test_ParseOpenTelemetryEndpoint_WhenRejectedUrlCarriesCredentials_KeepsThemOutOfTheError(t *testing.T) {
+ rejectedURLs := []string{
+ "ingest.eu.signoz.cloud:443?api-key=secret",
+ "http://victorialogs:9428/insert/opentelemetry/v1/logs?api-key=secret",
+ "ftp://viewer:secret@victorialogs:9428/insert/opentelemetry/v1/logs",
+ "https://viewer:secret@/insert/opentelemetry/v1/logs",
+ }
+
+ for _, rejectedURL := range rejectedURLs {
+ _, err := parseOpenTelemetryEndpoint(rejectedURL, map[string]string{})
+
+ require.Error(t, err, "URL %q", rejectedURL)
+ assert.NotContains(t, err.Error(), "secret")
+ }
+}
+
+func Test_ParseOpenTelemetryEndpoint_WithUserInfo_MovesCredentialsIntoHeaderAndStripsThem(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint("http://viewer:hunter2@logs:9428/v1/logs", map[string]string{})
+
+ require.NoError(t, err)
+ require.NotNil(t, openTelemetry)
+ assert.Equal(t, "http://logs:9428/v1/logs", openTelemetry.endpointURL)
+ assert.Equal(t,
+ "Basic "+base64.StdEncoding.EncodeToString([]byte("viewer:hunter2")),
+ openTelemetry.headers["Authorization"],
+ )
+}
+
+func Test_ParseOpenTelemetryEndpoint_WhenHeaderAndUserInfoBothSetAuthorization_HeaderWins(t *testing.T) {
+ openTelemetry, err := parseOpenTelemetryEndpoint(
+ "http://viewer:hunter2@logs:9428/v1/logs",
+ map[string]string{"authorization": "Bearer from-header"},
+ )
+
+ require.NoError(t, err)
+ require.NotNil(t, openTelemetry)
+ assert.Equal(t, "Bearer from-header", openTelemetry.headers["authorization"])
+ assert.NotContains(t, openTelemetry.headers, "Authorization")
+ assert.Equal(t, "http://logs:9428/v1/logs", openTelemetry.endpointURL)
+}
+
+func Test_ParseOpenTelemetryHeaders_WithPaddedPairsAndEmptyEntries_KeepsEveryPair(t *testing.T) {
+ headers, err := parseOpenTelemetryHeaders(" signoz-ingestion-key=abc123 , x-scope-org-id=tenant-1 ,, ")
+
+ require.NoError(t, err)
+ assert.Equal(t, map[string]string{
+ "signoz-ingestion-key": "abc123",
+ "x-scope-org-id": "tenant-1",
+ }, headers)
+}
+
+func Test_ParseOpenTelemetryHeaders_WithEncodedValue_DecodesPercentEscapes(t *testing.T) {
+ headers, err := parseOpenTelemetryHeaders("VL-Extra-Fields=host%3Dweb1%2Cdc%3Deu,Authorization=Basic%20abc")
+
+ require.NoError(t, err)
+ assert.Equal(t, map[string]string{
+ "VL-Extra-Fields": "host=web1,dc=eu",
+ "Authorization": "Basic abc",
+ }, headers)
+}
+
+func Test_ParseOpenTelemetryHeaders_WithMalformedEntry_FailsWithoutEchoingValue(t *testing.T) {
+ headers, err := parseOpenTelemetryHeaders("x-tenant=acme,signoz-ingestion-key-and-secret-token")
+
+ require.Error(t, err)
+ assert.Nil(t, headers)
+ assert.Contains(t, err.Error(), "entry 2")
+ assert.NotContains(t, err.Error(), "signoz-ingestion-key-and-secret-token")
+}
+
+func Test_ParseOpenTelemetryHeaders_WithBrokenPercentEscape_FailsWithoutEchoingValue(t *testing.T) {
+ headers, err := parseOpenTelemetryHeaders("Authorization=Bearer%2secret")
+
+ require.Error(t, err)
+ assert.Nil(t, headers)
+ assert.Contains(t, err.Error(), "entry 1")
+ assert.NotContains(t, err.Error(), "secret")
+}
+
+func Test_ParseLogFileSettings_WhenUnset_EnabledAtDataVolumeRoot(t *testing.T) {
+ t.Setenv("LOG_FILE_IS_ENABLED", "")
+
+ fileSettings := parseLogFileSettings()
+
+ assert.True(t, fileSettings.isEnabled)
+ assert.Equal(t, filepath.Join(getDataFolder(), "databasus.log"), fileSettings.path)
+}
+
+func Test_ParseLogFileSettings_WhenSetToFalse_Disabled(t *testing.T) {
+ t.Setenv("LOG_FILE_IS_ENABLED", " FALSE ")
+
+ assert.False(t, parseLogFileSettings().isEnabled)
+}
+
+func Test_ParseLogFileSettings_WithUnrecognisedValue_StaysEnabled(t *testing.T) {
+ t.Setenv("LOG_FILE_IS_ENABLED", "nope")
+
+ assert.True(t, parseLogFileSettings().isEnabled)
+}
diff --git a/backend/internal/util/logger/stdout_sink.go b/backend/internal/util/logger/stdout_sink.go
new file mode 100644
index 00000000..45aca2b2
--- /dev/null
+++ b/backend/internal/util/logger/stdout_sink.go
@@ -0,0 +1,21 @@
+package logger
+
+import (
+ "log/slog"
+ "os"
+)
+
+const consoleTimeFormat = "2006/01/02 15:04:05"
+
+func newStdoutHandler() slog.Handler {
+ return slog.NewTextHandler(os.Stdout, &slog.HandlerOptions{
+ Level: slog.LevelDebug,
+ ReplaceAttr: func(_ []string, attr slog.Attr) slog.Attr {
+ if attr.Key == slog.TimeKey && attr.Value.Kind() == slog.KindTime {
+ attr.Value = slog.StringValue(attr.Value.Time().UTC().Format(consoleTimeFormat))
+ }
+
+ return attr
+ },
+ })
+}
diff --git a/backend/internal/util/logger/victorialogs_writer.go b/backend/internal/util/logger/victorialogs_writer.go
deleted file mode 100644
index edc43745..00000000
--- a/backend/internal/util/logger/victorialogs_writer.go
+++ /dev/null
@@ -1,202 +0,0 @@
-package logger
-
-import (
- "bytes"
- "context"
- "encoding/base64"
- "encoding/json"
- "fmt"
- "io"
- "log/slog"
- "net/http"
- "os"
- "sync"
- "time"
-)
-
-type logEntry struct {
- Time string `json:"_time"`
- Message string `json:"_msg"`
- Level string `json:"level"`
- Attrs map[string]any `json:",inline"`
-}
-
-type VictoriaLogsWriter struct {
- url string
- username string
- password string
- httpClient *http.Client
- logChannel chan logEntry
- wg sync.WaitGroup
- shutdown func()
- ctx context.Context
- cancel context.CancelFunc
- logger *slog.Logger
-}
-
-func NewVictoriaLogsWriter(url, username, password string) *VictoriaLogsWriter {
- ctx, cancel := context.WithCancel(context.Background())
-
- writer := &VictoriaLogsWriter{
- url: url,
- username: username,
- password: password,
- httpClient: &http.Client{
- Timeout: 10 * time.Second,
- },
- logChannel: make(chan logEntry, 1000),
- ctx: ctx,
- cancel: cancel,
- logger: slog.New(slog.NewTextHandler(os.Stdout, nil)),
- }
-
- writer.shutdown = sync.OnceFunc(func() {
- // Stop accepting new logs
- writer.cancel()
-
- // Wait for workers to finish with timeout
- done := make(chan struct{})
- go func() {
- writer.wg.Wait()
- close(done)
- }()
-
- select {
- case <-done:
- writer.logger.Info("VictoriaLogs writer shutdown gracefully")
- case <-time.After(5 * time.Second):
- writer.logger.Warn("VictoriaLogs writer shutdown timeout, some logs may be lost")
- }
- })
-
- // Start 3 worker goroutines
- for range 3 {
- writer.wg.Go(writer.worker)
- }
-
- return writer
-}
-
-func (w *VictoriaLogsWriter) Write(level, message string, attrs map[string]any) {
- entry := logEntry{
- Time: time.Now().UTC().Format(time.RFC3339Nano),
- Message: message,
- Level: level,
- Attrs: attrs,
- }
-
- select {
- case w.logChannel <- entry:
- // Successfully queued
- default:
- // Channel is full, drop log with warning
- w.logger.Warn("VictoriaLogs channel buffer full, dropping log entry")
- }
-}
-
-func (w *VictoriaLogsWriter) Shutdown(timeout time.Duration) {
- w.shutdown()
-}
-
-func (w *VictoriaLogsWriter) worker() {
- batch := make([]logEntry, 0, 100)
- ticker := time.NewTicker(1 * time.Second)
- defer ticker.Stop()
-
- for {
- select {
- case <-w.ctx.Done():
- w.flushBatch(batch)
- return
-
- case entry, ok := <-w.logChannel:
- if !ok {
- w.flushBatch(batch)
- return
- }
-
- batch = append(batch, entry)
-
- // Send batch if it reaches 100 entries
- if len(batch) >= 100 {
- w.sendBatch(batch)
- batch = make([]logEntry, 0, 100)
- }
-
- case <-ticker.C:
- if len(batch) > 0 {
- w.sendBatch(batch)
- batch = make([]logEntry, 0, 100)
- }
- }
- }
-}
-
-func (w *VictoriaLogsWriter) sendBatch(entries []logEntry) {
- backoffs := []time.Duration{0, 5 * time.Second, 30 * time.Second, 1 * time.Minute}
-
- for attempt := range 4 {
- if backoffs[attempt] > 0 {
- time.Sleep(backoffs[attempt])
- }
-
- if err := w.sendHTTP(entries); err == nil {
- return
- } else if attempt == 3 {
- w.logger.Error("VictoriaLogs failed to send logs after 4 attempts",
- "error", err,
- "entries_count", len(entries))
- }
- }
-}
-
-func (w *VictoriaLogsWriter) sendHTTP(entries []logEntry) error {
- // Build JSON Lines payload
- var buf bytes.Buffer
- encoder := json.NewEncoder(&buf)
-
- for _, entry := range entries {
- if err := encoder.Encode(entry); err != nil {
- return fmt.Errorf("failed to encode log entry: %w", err)
- }
- }
-
- // Build request
- url := fmt.Sprintf("%s/insert/jsonline?_stream_fields=level&_msg_field=_msg", w.url)
- req, err := http.NewRequestWithContext(w.ctx, "POST", url, &buf)
- if err != nil {
- return fmt.Errorf("failed to create request: %w", err)
- }
-
- // Set headers
- req.Header.Set("Content-Type", "application/x-ndjson")
-
- // Set Basic Auth (username:password)
- if w.password != "" {
- auth := base64.StdEncoding.EncodeToString([]byte(w.username + ":" + w.password))
- req.Header.Set("Authorization", "Basic "+auth)
- }
-
- // Send request
- resp, err := w.httpClient.Do(req)
- if err != nil {
- return fmt.Errorf("failed to send request: %w", err)
- }
- defer func() {
- _ = resp.Body.Close()
- }()
-
- // Check response
- if resp.StatusCode < 200 || resp.StatusCode >= 300 {
- body, _ := io.ReadAll(resp.Body)
- return fmt.Errorf("VictoriaLogs returned status %d: %s", resp.StatusCode, string(body))
- }
-
- return nil
-}
-
-func (w *VictoriaLogsWriter) flushBatch(batch []logEntry) {
- if len(batch) > 0 {
- w.sendBatch(batch)
- }
-}
diff --git a/deploy/helm/README.md b/deploy/helm/README.md
index 25e43380..82838201 100644
--- a/deploy/helm/README.md
+++ b/deploy/helm/README.md
@@ -97,6 +97,50 @@ Notes:
- Env values must be strings. Use quoted `"true"` / `"false"` rather than bare booleans, and pass `--set-string` on the CLI (e.g. `--set-string 'extraEnv[0].value=true'`) to avoid Kubernetes rejecting non-string values.
- `extraEnv` is appended after `SSL_CERT_FILE` (when `customRootCA` is set), so an entry with the same name will override `SSL_CERT_FILE`. Avoid duplicate `name` entries unless that override is intentional.
+### Logging and Observability
+
+Databasus logs to stdout and can additionally export to any OpenTelemetry backend. There is no dedicated chart value for this — configure it through `extraEnv` like any other application setting.
+
+| Variable | Description | Default |
+| ------------------------ | ---------------------------------------------------------------- | ------- |
+| `LOG_LEVEL` | `debug`, `info`, `warn` or `error` | `info` |
+| `OPEN_TELEMETRY_URL` | Full OTLP endpoint URL; empty disables export | empty |
+| `OPEN_TELEMETRY_HEADERS` | `k=v` pairs, comma separated, values percent-encoded | empty |
+
+The URL is used verbatim, path included, and the scheme selects the transport. Pointing at a backend directly and pointing at an OTel Collector are the same setting — a Collector is itself an OTLP receiver:
+
+```yaml
+extraEnv:
+ - name: LOG_LEVEL
+ value: "info"
+ # OTLP/gRPC — Graylog 6.2+, SigNoz, a Collector on :4317
+ - name: OPEN_TELEMETRY_URL
+ value: "grpc://otel-collector.observability:4317"
+ # OTLP/HTTP — VictoriaLogs, Loki, a Collector on :4318/v1/logs
+ # value: "http://victoria-logs.observability:9428/insert/opentelemetry/v1/logs"
+```
+
+Headers are how a backend is authenticated and tuned: `signoz-ingestion-key` for SigNoz Cloud, `Authorization=Basic%20<base64>` for Grafana Cloud, `dd-api-key` for Datadog, `x-honeycomb-team` for Honeycomb, `VL-Stream-Fields` and `VL-Extra-Fields` for VictoriaLogs. The format matches the standard `OTEL_EXPORTER_OTLP_HEADERS`, so values are percent-decoded and a value may itself contain a comma (`%2C`), an equals sign (`%3D`) or a space (`%20`). A query string in the URL is rejected rather than silently dropped, since the exporter cannot send one.
+
+Use a Collector when you need to fan out to several backends or to survive a long backend outage — it has a disk-backed queue, whereas the in-process exporter drops records once its buffer fills.
+
+Audit entries (user actions) are exported alongside application logs and carry `log_type=audit`. They ignore `LOG_LEVEL`, so raising the level never silently drops the audit trail.
+
+**Credentials.** A token in `OPEN_TELEMETRY_HEADERS`, or a password embedded as userinfo in `OPEN_TELEMETRY_URL`, belongs in a Secret — never as a literal `extraEnv[].value`, which ends up in `values.yaml`, in git and in `helm get values`:
+
+```yaml
+extraEnv:
+ - name: OPEN_TELEMETRY_HEADERS
+ valueFrom:
+ secretKeyRef:
+ name: databasus-observability
+ key: otlp-headers
+```
+
+Over `http://` and `grpc://` those credentials travel in clear — use `https://` or `grpcs://` outside a trusted network.
+
+**File logging.** `logFileIsEnabled` is the one logging setting with its own chart value, and it is `false` here even though the application defaults it to on: stdout is already collected by the cluster's node agent, and that is the platform's logging model. The file sink exists for Docker and bare-metal installs. Set it to `true` and the pod writes `/databasus-data/databasus.log`, capped at 4 files of 5 MB, which needs `persistence` enabled or the logs vanish with the pod. The location and the limits are not configurable.
+
### Service
| Parameter | Description | Default Value |
diff --git a/deploy/helm/templates/statefulset.yaml b/deploy/helm/templates/statefulset.yaml
index 35f2c508..8e29b2ff 100644
--- a/deploy/helm/templates/statefulset.yaml
+++ b/deploy/helm/templates/statefulset.yaml
@@ -57,8 +57,9 @@ spec:
securityContext:
{{- toYaml . | nindent 12 }}
{{- end }}
- {{- if or .Values.customRootCA .Values.extraEnv }}
env:
+ - name: LOG_FILE_IS_ENABLED
+ value: {{ .Values.logFileIsEnabled | quote }}
{{- if .Values.customRootCA }}
- name: SSL_CERT_FILE
value: /etc/ssl/certs/custom-root-ca.crt
@@ -66,7 +67,6 @@ spec:
{{- with .Values.extraEnv }}
{{- toYaml . | nindent 12 }}
{{- end }}
- {{- end }}
{{- with .Values.extraEnvFrom }}
envFrom:
{{- toYaml . | nindent 12 }}
diff --git a/deploy/helm/values.yaml b/deploy/helm/values.yaml
index cb6dffa2..e908ad22 100644
--- a/deploy/helm/values.yaml
+++ b/deploy/helm/values.yaml
@@ -16,6 +16,10 @@ replicaCount: 1
# RootCA setup, need name of secret in same namespace
customRootCA: ""
+# Mirror logs to a rotating file at <mountPath>/databasus.log, 4 files of 5 MB. Off here because
+# the cluster already collects the container's stdout; turning it on requires `persistence`.
+logFileIsEnabled: false
+
# Extra environment variables to inject into the databasus container.
# Accepts the standard Kubernetes EnvVar shape (value or valueFrom).
# Note: env values must be strings — use quoted "true"/"false" rather than bare
@@ -24,6 +28,10 @@ customRootCA: ""
extraEnv: []
# - name: IS_DISABLE_ANONYMOUS_TELEMETRY
# value: "true"
+# - name: LOG_LEVEL
+# value: "info"
+# - name: OPEN_TELEMETRY_URL
+# value: "grpc://otel-collector.observability:4317"
# - name: SOME_TOKEN
# valueFrom:
# secretKeyRef:
diff --git a/docker-compose.yml b/docker-compose.yml
index b7430a64..a7d695a7 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -81,6 +81,8 @@ services:
command:
- -storageDataPath=/victoria-logs-data
- -retentionPeriod=7d
+ # VictoriaLogs only enforces basic auth when BOTH are set; password alone is a no-op.
+ - -httpAuth.username=databasus
- -httpAuth.password=devpassword
volumes:
- /victoria-logs-data