// Package logshipper is the client-side adapter for LoggingServer // (Web/LoggingServer), the workspace's centralized log sink. It is the // logging equivalent of the authclient package added alongside AuthServer: // each service currently owns its own local internal/logging package (see // Original/OutdoorGames/OutdoorGamesServerGo/internal/logging/logging.go for // the canonical shape — a Logger tagged by module name, an env-driven level // threshold, Debug/Info/Warn/Error/Critical/Audit/*Ctx methods, and an // optional verbose JSON context dump gated by LOG_ALL). Shipper exposes that // exact same method surface so a project can eventually swap its local // logging.New(...) call for logshipper.New(...) with no call-site changes, // once the owner decides to migrate a given service. // // No project imports this yet — see LoggingServer/README.md's "Migration // notes" for the deliberate, per-project follow-up this requires. // // Shipper always writes the same human-readable line to stdout/stderr that // the local loggers write today, in addition to batching entries off to // LoggingServer. Nothing is lost if LoggingServer is never wired up, never // reachable, or removed later — this is a mirror, not a replacement, for the // container's own stdout/stderr logs. package logshipper import ( "bytes" "context" "encoding/json" "fmt" "net/http" "os" "strings" "sync" "time" ) // Level mirrors internal/logging's severity scale in every service's local // logger, so a threshold configured via the same LOG env var behaves // identically whether it gates a local Logger or a Shipper. type Level int const ( LevelDebug Level = 10 LevelInfo Level = 20 LevelWarn Level = 30 LevelError Level = 40 LevelCritical Level = 50 LevelSilent Level = 100 ) func levelOf(s string) Level { switch strings.ToLower(strings.TrimSpace(s)) { case "debug": return LevelDebug case "warn", "warning": return LevelWarn case "error": return LevelError case "critical": return LevelCritical case "silent", "none", "off": return LevelSilent default: return LevelInfo } } // sevName is the canonical, lowercase level name LoggingServer's ingest API // expects (debug/info/warn/error/critical), independent of the uppercase // name used in the local stdout/stderr line. func sevName(sev Level) (upper, lower string) { switch sev { case LevelDebug: return "DEBUG", "debug" case LevelWarn: return "WARN", "warn" case LevelError: return "ERROR", "error" case LevelCritical: return "CRITICAL", "critical" default: return "INFO", "info" } } const ( defaultFlushInterval = 2 * time.Second defaultMaxBatchSize = 100 defaultBufferCapacity = 2000 defaultHTTPTimeout = 5 * time.Second defaultWarnInterval = time.Minute ) // Config configures a Shipper. Only BaseURL, IngestToken, and Service are // normally set by a caller; everything else has a workable default. type Config struct { // BaseURL is LoggingServer's base URL, e.g. "http://loggingserver:8090". // Required. BaseURL string // IngestToken is the shared INGEST_TOKEN bearer secret LoggingServer // requires (see LoggingServer/README.md). Required. IngestToken string // Service is this process's service name as reported to LoggingServer, // e.g. "playhouse" or "outdoorgames-server-go". Required. Service string // Module is the local tag included in the human-readable stdout/stderr // line, mirroring internal/logging.New's module argument. Defaults to // Service when empty. Module string // Level is the severity threshold, same values/aliases as the LOG env // var (debug/info/warn/error/critical/silent). Defaults to "info". Level string // LogAll mirrors the LOG_ALL env var: when true, a verbose JSON context // dump is also printed locally (never sent to LoggingServer differently // than normal — see Debug/InfoCtx doc comments). LogAll bool // FlushInterval is how often buffered entries are sent to LoggingServer. // Defaults to 2s. FlushInterval time.Duration // MaxBatchSize triggers an out-of-band flush as soon as the buffer // reaches this many entries, instead of waiting for FlushInterval. // Defaults to 100. MaxBatchSize int // BufferCapacity is the maximum number of not-yet-flushed entries held // in memory. Once full, new entries are dropped (oldest-first callers // are not blocked) rather than applying backpressure to the caller. // Defaults to 2000. BufferCapacity int // HTTPClient overrides the client used to POST to LoggingServer. // Defaults to a client with a 5s timeout. HTTPClient *http.Client } // wireEntry mirrors LoggingServer's POST /api/logs request shape // (LoggingServer/internal/httpapi.LogEntryInput) field-for-field. type wireEntry struct { Service string `json:"service"` Level string `json:"level"` Message string `json:"message"` Context json.RawMessage `json:"context,omitempty"` OccurredAt time.Time `json:"occurred_at"` } // Shipper batches log entries in memory and flushes them to LoggingServer on // a background goroutine, while also behaving like a local // internal/logging.Logger (same method surface, same stdout/stderr output). // A Shipper is safe for concurrent use. type Shipper struct { module string threshold Level logAll bool service string url string token string client *http.Client maxBatch int bufCap int mu sync.Mutex buffer []wireEntry flushSignal chan struct{} closeOnce sync.Once closeCh chan struct{} doneCh chan struct{} warnMu sync.Mutex lastWarn time.Time } // New creates a Shipper. It starts a background flush goroutine immediately; // call Close (or Flush, for a one-off synchronous flush) during shutdown to // avoid losing buffered entries. func New(cfg Config) *Shipper { module := cfg.Module if module == "" { module = cfg.Service } flushInterval := cfg.FlushInterval if flushInterval <= 0 { flushInterval = defaultFlushInterval } maxBatch := cfg.MaxBatchSize if maxBatch <= 0 { maxBatch = defaultMaxBatchSize } bufCap := cfg.BufferCapacity if bufCap <= 0 { bufCap = defaultBufferCapacity } client := cfg.HTTPClient if client == nil { client = &http.Client{Timeout: defaultHTTPTimeout} } s := &Shipper{ module: module, threshold: levelOf(cfg.Level), logAll: cfg.LogAll, service: cfg.Service, url: strings.TrimRight(cfg.BaseURL, "/") + "/api/logs", token: cfg.IngestToken, client: client, maxBatch: maxBatch, bufCap: bufCap, flushSignal: make(chan struct{}, 1), closeCh: make(chan struct{}), doneCh: make(chan struct{}), } go s.loop(flushInterval) return s } func (s *Shipper) loop(flushInterval time.Duration) { defer close(s.doneCh) ticker := time.NewTicker(flushInterval) defer ticker.Stop() for { select { case <-ticker.C: s.flush() case <-s.flushSignal: s.flush() case <-s.closeCh: s.flush() // final, best-effort flush of whatever is left return } } } // requestFlush asks the background loop to flush soon, without blocking the // caller: if a flush is already pending the request is simply dropped. func (s *Shipper) requestFlush() { select { case s.flushSignal <- struct{}{}: default: } } // enqueue appends one entry to the buffer, dropping the incoming entry // (rather than blocking the caller or evicting older entries) once the // buffer is full. This is the sole non-blocking guarantee this package // makes: a caller's Debug/Info/... call never waits on network I/O. func (s *Shipper) enqueue(entry wireEntry) { s.mu.Lock() full := len(s.buffer) >= s.bufCap if !full { s.buffer = append(s.buffer, entry) } atCap := len(s.buffer) >= s.maxBatch s.mu.Unlock() if full { s.warnOnce(fmt.Errorf("logshipper: buffer full (cap=%d), dropping log entries for service %q", s.bufCap, s.service)) return } if atCap { s.requestFlush() } } // flush sends every currently buffered entry to LoggingServer in one // request. Failures are swallowed (beyond a rate-limited local warning) by // design: a host application must never fail, panic, or slow down because // its log sink is unreachable. func (s *Shipper) flush() { s.mu.Lock() if len(s.buffer) == 0 { s.mu.Unlock() return } batch := s.buffer s.buffer = nil s.mu.Unlock() body, err := json.Marshal(batch) if err != nil { s.warnOnce(fmt.Errorf("logshipper: marshal batch: %w", err)) return } ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout) defer cancel() req, err := http.NewRequestWithContext(ctx, http.MethodPost, s.url, bytes.NewReader(body)) if err != nil { s.warnOnce(fmt.Errorf("logshipper: build request: %w", err)) return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+s.token) resp, err := s.client.Do(req) if err != nil { s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s: %w", len(batch), s.url, err)) return } defer resp.Body.Close() if resp.StatusCode < 200 || resp.StatusCode >= 300 { s.warnOnce(fmt.Errorf("logshipper: LoggingServer rejected %d entries: HTTP %d", len(batch), resp.StatusCode)) } } // warnOnce prints a local stderr warning at most once per minute, no matter // how many sends fail in that window, so an unreachable LoggingServer cannot // itself become a log-spam problem. func (s *Shipper) warnOnce(err error) { s.warnMu.Lock() defer s.warnMu.Unlock() if time.Since(s.lastWarn) < defaultWarnInterval { return } s.lastWarn = time.Now() fmt.Fprintf(os.Stderr, "[%s] [logshipper] %s\n", time.Now().Format("2006-01-02 15:04:05.000"), err.Error()) } // Flush synchronously sends any currently buffered entries. It never blocks // longer than the underlying HTTP client's timeout and never returns an // error to the caller (failures are reported via the same rate-limited // stderr warning as background flushes) — this mirrors the "never block or // panic the host app" guarantee the background path makes. func (s *Shipper) Flush() { s.flush() } // Close stops the background flush goroutine after performing one final // flush of any buffered entries, and waits for that flush to finish. Call it // during graceful shutdown so the last few log lines before exit are not // silently dropped. func (s *Shipper) Close() error { s.closeOnce.Do(func() { close(s.closeCh) }) <-s.doneCh return nil } // ---- Logger-shaped methods ------------------------------------------------- // // Everything below matches internal/logging.Logger's method surface // (Debug/Info/Warn/Error/Critical/Audit/*Ctx) so a Shipper can act as a // near drop-in replacement for a project's local logger. func (s *Shipper) emit(sev Level, ctx map[string]any, args ...any) { if sev < s.threshold { return } now := time.Now() msg := formatArgs(args) upper, lower := sevName(sev) line := fmt.Sprintf("[%s] [%s] [%s] [%s] %s", now.Format("2006-01-02"), now.Format("15:04:05.000"), upper, s.module, msg) switch sev { case LevelError, LevelCritical, LevelWarn: fmt.Fprintln(os.Stderr, line) default: fmt.Fprintln(os.Stdout, line) } if s.logAll && ctx != nil { if b, err := json.Marshal(scrubIDs(ctx)); err == nil { fmt.Fprintf(os.Stdout, "[%s] [%s] [DEBUG] [%s] [DETAILS] %s\n", now.Format("2006-01-02"), now.Format("15:04:05.000"), s.module, string(b)) } } // Unlike the local-only verbose dump above (which scrubs IDs for // readability), the context shipped to LoggingServer is sent unscrubbed: // the whole point of centralizing logs is cross-service correlation by // request/user/entity ID, so stripping IDs here would defeat that. var rawCtx json.RawMessage if ctx != nil { if b, err := json.Marshal(ctx); err == nil { rawCtx = b } } s.enqueue(wireEntry{ Service: s.service, Level: lower, Message: msg, Context: rawCtx, OccurredAt: now, }) } func formatArgs(args []any) string { parts := make([]string, 0, len(args)) for _, a := range args { switch v := a.(type) { case error: parts = append(parts, v.Error()) case string: parts = append(parts, v) default: if b, err := json.Marshal(v); err == nil { parts = append(parts, string(b)) } else { parts = append(parts, fmt.Sprintf("%v", v)) } } } return strings.Join(parts, " ") } // scrubIDs drops raw identifier fields from the verbose local-only context // dump, matching internal/logging.Logger's behavior. func scrubIDs(ctx map[string]any) map[string]any { out := make(map[string]any, len(ctx)) for k, v := range ctx { lower := strings.ToLower(k) if lower == "id" || strings.HasSuffix(lower, "id") || strings.HasSuffix(lower, "_id") { continue } out[k] = v } return out } func (s *Shipper) Debug(args ...any) { s.emit(LevelDebug, nil, args...) } func (s *Shipper) Info(args ...any) { s.emit(LevelInfo, nil, args...) } func (s *Shipper) Warn(args ...any) { s.emit(LevelWarn, nil, args...) } func (s *Shipper) Error(args ...any) { s.emit(LevelError, nil, args...) } func (s *Shipper) Critical(args ...any) { s.emit(LevelCritical, nil, args...) } // Audit logs a structured audit-trail event at info level, matching // internal/logging.Logger.Audit. func (s *Shipper) Audit(event string, details map[string]any) { s.emit(LevelInfo, details, "audit:"+event, details) } func (s *Shipper) DebugCtx(ctx map[string]any, args ...any) { s.emit(LevelDebug, ctx, args...) } func (s *Shipper) InfoCtx(ctx map[string]any, args ...any) { s.emit(LevelInfo, ctx, args...) } func (s *Shipper) WarnCtx(ctx map[string]any, args ...any) { s.emit(LevelWarn, ctx, args...) } func (s *Shipper) ErrorCtx(ctx map[string]any, args ...any) { s.emit(LevelError, ctx, args...) }