2026-09-06 22:50:38 +02:00
|
|
|
// Package logshipper is the client-side adapter for OmniLogger
|
|
|
|
|
// (Web/OmniLogger), the workspace's centralized log sink. It is the
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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.
|
|
|
|
|
//
|
2026-09-06 22:50:38 +02:00
|
|
|
// No project imports this yet — see OmniLogger/README.md's "Migration
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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
|
2026-09-06 22:50:38 +02:00
|
|
|
// OmniLogger. Nothing is lost if OmniLogger is never wired up, never
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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"
|
2026-11-21 00:23:35 +01:00
|
|
|
"io"
|
2026-09-01 08:43:25 +02:00
|
|
|
"net/http"
|
|
|
|
|
"os"
|
2026-11-21 00:23:35 +01:00
|
|
|
"regexp"
|
2026-09-01 08:43:25 +02:00
|
|
|
"strings"
|
|
|
|
|
"sync"
|
|
|
|
|
"time"
|
2026-11-21 00:23:35 +01:00
|
|
|
"unicode/utf8"
|
|
|
|
|
|
|
|
|
|
"repos.gfranz.ch/Gabriel20xx/shared/backend/coreconfig"
|
2026-09-01 08:43:25 +02:00
|
|
|
)
|
|
|
|
|
|
|
|
|
|
// 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
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// sevName is the canonical, lowercase level name OmniLogger's ingest API
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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 {
|
2026-09-06 22:50:38 +02:00
|
|
|
// BaseURL is OmniLogger's base URL, e.g. "http://omnilogger:8090".
|
2026-09-01 08:43:25 +02:00
|
|
|
// Required.
|
|
|
|
|
BaseURL string
|
2026-11-21 00:23:35 +01:00
|
|
|
// IngestToken is this service's OmniLogger ingest token: a per-service
|
|
|
|
|
// bearer secret an administrator creates in OmniLogger and bound to
|
|
|
|
|
// Service (see OmniLogger/README.md). OmniLogger rejects entries whose
|
|
|
|
|
// service differs from the token's bound service. Required.
|
2026-09-01 08:43:25 +02:00
|
|
|
IngestToken string
|
2026-09-06 22:50:38 +02:00
|
|
|
// Service is this process's service name as reported to OmniLogger,
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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
|
2026-09-06 22:50:38 +02:00
|
|
|
// dump is also printed locally (never sent to OmniLogger differently
|
2026-09-01 08:43:25 +02:00
|
|
|
// than normal — see Debug/InfoCtx doc comments).
|
|
|
|
|
LogAll bool
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// FlushInterval is how often buffered entries are sent to OmniLogger.
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// HTTPClient overrides the client used to POST to OmniLogger.
|
2026-09-01 08:43:25 +02:00
|
|
|
// Defaults to a client with a 5s timeout.
|
|
|
|
|
HTTPClient *http.Client
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// wireEntry mirrors OmniLogger's POST /api/logs request shape
|
|
|
|
|
// (OmniLogger/internal/httpapi.LogEntryInput) field-for-field.
|
2026-09-01 08:43:25 +02:00
|
|
|
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"`
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// Shipper batches log entries in memory and flushes them to OmniLogger on
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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
|
|
|
|
|
client *http.Client
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
// credMu guards url and token, which SetCredentials can replace while the Shipper runs. An empty
|
|
|
|
|
// url means shipping is disabled.
|
|
|
|
|
credMu sync.RWMutex
|
|
|
|
|
url string
|
|
|
|
|
token string
|
|
|
|
|
|
2026-09-01 08:43:25 +02:00
|
|
|
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,
|
|
|
|
|
client: client,
|
|
|
|
|
maxBatch: maxBatch,
|
|
|
|
|
bufCap: bufCap,
|
|
|
|
|
flushSignal: make(chan struct{}, 1),
|
|
|
|
|
closeCh: make(chan struct{}),
|
|
|
|
|
doneCh: make(chan struct{}),
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
s.SetCredentials(cfg.BaseURL, cfg.IngestToken)
|
2026-09-01 08:43:25 +02:00
|
|
|
go s.loop(flushInterval)
|
|
|
|
|
return s
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
// SetCredentials sets where, and as which ingest token, the Shipper sends entries. It can be called at
|
|
|
|
|
// any time, for example when ProjectConfigurator pushes a new token, and takes effect from the next
|
|
|
|
|
// flush. An empty baseURL or token disables shipping: entries are no longer buffered, anything already
|
|
|
|
|
// buffered is discarded, and the local console output carries on as before.
|
|
|
|
|
func (s *Shipper) SetCredentials(baseURL, token string) {
|
|
|
|
|
token = strings.TrimSpace(token)
|
|
|
|
|
url := ""
|
|
|
|
|
if base := strings.TrimRight(strings.TrimSpace(baseURL), "/"); base != "" && token != "" {
|
|
|
|
|
url = base + "/api/logs"
|
|
|
|
|
}
|
|
|
|
|
s.credMu.Lock()
|
|
|
|
|
s.url = url
|
|
|
|
|
s.token = token
|
|
|
|
|
s.credMu.Unlock()
|
|
|
|
|
if url == "" {
|
|
|
|
|
s.mu.Lock()
|
|
|
|
|
s.buffer = nil
|
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Follow keeps the Shipper's endpoint and ingest token in step with ProjectConfigurator's pushes. A
|
|
|
|
|
// push that carries both an OmniLogger URL and an ingest token replaces the endpoint and token. Any other
|
|
|
|
|
// push, including the first one after a restart, leaves the current settings alone, so a service that was
|
|
|
|
|
// configured from its environment keeps shipping until ProjectConfigurator supplies both values.
|
|
|
|
|
func (s *Shipper) Follow(store *coreconfig.Store) {
|
|
|
|
|
apply := func(info coreconfig.Info) {
|
|
|
|
|
if info.OmniLoggerURL != "" && info.OmniLoggerIngestToken != "" {
|
|
|
|
|
s.SetCredentials(info.OmniLoggerURL, info.OmniLoggerIngestToken)
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
apply(store.Get())
|
|
|
|
|
store.Subscribe(apply)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// credentials returns the current endpoint and token.
|
|
|
|
|
func (s *Shipper) credentials() (url, token string) {
|
|
|
|
|
s.credMu.RLock()
|
|
|
|
|
defer s.credMu.RUnlock()
|
|
|
|
|
return s.url, s.token
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-01 08:43:25 +02:00
|
|
|
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:
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
// OmniLogger rejects a whole POST /api/logs batch when any one entry breaks its limits, so every
|
|
|
|
|
// entry is clamped to them before it is buffered. These mirror OmniLogger's MaxMessageBytes and
|
|
|
|
|
// MaxContextBytes; a message is cut with a marker, and an oversized or unshippable context is dropped
|
|
|
|
|
// and replaced with a marker object, so the entry itself still reaches OmniLogger.
|
|
|
|
|
const (
|
|
|
|
|
maxMessageBytes = 8 * 1024
|
|
|
|
|
maxContextBytes = 16 * 1024
|
|
|
|
|
truncatedMarker = " [truncated]"
|
|
|
|
|
droppedContext = `{"context_dropped":true}`
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
func clampEntry(e wireEntry) wireEntry {
|
|
|
|
|
if len(e.Message) > maxMessageBytes {
|
|
|
|
|
cut := maxMessageBytes - len(truncatedMarker)
|
|
|
|
|
for cut > 0 && !utf8.RuneStart(e.Message[cut]) {
|
|
|
|
|
cut--
|
|
|
|
|
}
|
|
|
|
|
e.Message = e.Message[:cut] + truncatedMarker
|
|
|
|
|
}
|
|
|
|
|
// OmniLogger refuses a NUL in context, which json.Marshal writes as \u0000.
|
|
|
|
|
if len(e.Context) > maxContextBytes || bytes.Contains(e.Context, []byte(`\u0000`)) {
|
|
|
|
|
e.Context = json.RawMessage(droppedContext)
|
|
|
|
|
}
|
|
|
|
|
return e
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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) {
|
2026-11-21 00:23:35 +01:00
|
|
|
if url, _ := s.credentials(); url == "" {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
entry = clampEntry(entry)
|
2026-09-01 08:43:25 +02:00
|
|
|
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()
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-06 22:50:38 +02:00
|
|
|
// flush sends every currently buffered entry to OmniLogger in one
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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() {
|
2026-11-21 00:23:35 +01:00
|
|
|
url, token := s.credentials()
|
2026-09-01 08:43:25 +02:00
|
|
|
s.mu.Lock()
|
|
|
|
|
if len(s.buffer) == 0 {
|
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
batch := s.buffer
|
|
|
|
|
s.buffer = nil
|
|
|
|
|
s.mu.Unlock()
|
2026-11-21 00:23:35 +01:00
|
|
|
if url == "" {
|
2026-09-01 08:43:25 +02:00
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
// A backlog can hold up to bufCap entries, far more than OmniLogger accepts in one request, so the
|
|
|
|
|
// buffer is sent as several requests, each within maxRequestEntries and maxRequestBytes. When a request
|
|
|
|
|
// fails for a reason that may pass (no connection, a server error, or too many requests), the failed
|
|
|
|
|
// entries and everything after them go back to the buffer and are sent again on the next flush. A request
|
|
|
|
|
// OmniLogger rejects outright is dropped, because sending it again would fail the same way.
|
|
|
|
|
for _, chunk := range encodeBatches(batch) {
|
|
|
|
|
if s.send(url, token, chunk.payload, chunk.entries) {
|
|
|
|
|
s.requeue(batch[chunk.start:])
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Request limits for one POST /api/logs. OmniLogger refuses a request with more than 1000 entries or a
|
|
|
|
|
// body over 2 MiB, and it refuses the whole request when one entry is out of bounds, so every request
|
|
|
|
|
// stays well inside both.
|
|
|
|
|
const (
|
|
|
|
|
maxRequestEntries = 100
|
|
|
|
|
maxRequestBytes = 1 << 20
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
type encodedBatch struct {
|
|
|
|
|
payload []byte
|
|
|
|
|
entries int
|
|
|
|
|
// start is the index in the flushed batch of this request's first entry.
|
|
|
|
|
start int
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// encodeBatches marshals each entry once and packs the results into JSON array bodies, starting a new
|
|
|
|
|
// body when the current one reaches maxRequestEntries or would pass maxRequestBytes. An entry that
|
|
|
|
|
// cannot be marshaled is dropped, so one bad entry never blocks the rest.
|
|
|
|
|
func encodeBatches(batch []wireEntry) []encodedBatch {
|
|
|
|
|
var out []encodedBatch
|
|
|
|
|
var body bytes.Buffer
|
|
|
|
|
count := 0
|
|
|
|
|
start := 0
|
|
|
|
|
closeBody := func() {
|
|
|
|
|
if count == 0 {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
body.WriteByte(']')
|
|
|
|
|
out = append(out, encodedBatch{payload: append([]byte(nil), body.Bytes()...), entries: count, start: start})
|
|
|
|
|
body.Reset()
|
|
|
|
|
count = 0
|
|
|
|
|
}
|
|
|
|
|
for i, entry := range batch {
|
|
|
|
|
raw, err := json.Marshal(entry)
|
|
|
|
|
if err != nil {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
if count > 0 && (count >= maxRequestEntries || body.Len()+len(raw)+2 > maxRequestBytes) {
|
|
|
|
|
closeBody()
|
|
|
|
|
}
|
|
|
|
|
if count == 0 {
|
|
|
|
|
body.WriteByte('[')
|
|
|
|
|
start = i
|
|
|
|
|
} else {
|
|
|
|
|
body.WriteByte(',')
|
|
|
|
|
}
|
|
|
|
|
body.Write(raw)
|
|
|
|
|
count++
|
|
|
|
|
}
|
|
|
|
|
closeBody()
|
|
|
|
|
return out
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// requeue puts entries that failed to send back at the front of the buffer, so the next flush sends them
|
|
|
|
|
// before newer entries. The buffer stays within bufCap: when the requeued entries and the buffer do not all
|
|
|
|
|
// fit, the newest entries are dropped, as enqueue drops them when the buffer is full.
|
|
|
|
|
func (s *Shipper) requeue(entries []wireEntry) {
|
|
|
|
|
s.mu.Lock()
|
|
|
|
|
combined := make([]wireEntry, 0, len(entries)+len(s.buffer))
|
|
|
|
|
combined = append(combined, entries...)
|
|
|
|
|
combined = append(combined, s.buffer...)
|
|
|
|
|
dropped := 0
|
|
|
|
|
if len(combined) > s.bufCap {
|
|
|
|
|
dropped = len(combined) - s.bufCap
|
|
|
|
|
combined = combined[:s.bufCap]
|
|
|
|
|
}
|
|
|
|
|
s.buffer = combined
|
|
|
|
|
s.mu.Unlock()
|
|
|
|
|
if dropped > 0 {
|
|
|
|
|
s.warnOnce(fmt.Errorf("logshipper: buffer full while retrying, dropping %d log entries for service %q", dropped, s.service))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// send posts one encoded batch and reports whether it failed for a reason that may pass, in which case the
|
|
|
|
|
// caller keeps the entries for a later retry. A request OmniLogger rejects is reported and dropped. Failures are
|
|
|
|
|
// otherwise swallowed by design: a host application must never fail, panic, or slow down because its log sink
|
|
|
|
|
// is unreachable.
|
|
|
|
|
func (s *Shipper) send(url, token string, body []byte, entries int) (retry bool) {
|
2026-09-01 08:43:25 +02:00
|
|
|
ctx, cancel := context.WithTimeout(context.Background(), defaultHTTPTimeout)
|
|
|
|
|
defer cancel()
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
req, err := http.NewRequestWithContext(ctx, http.MethodPost, url, bytes.NewReader(body))
|
2026-09-01 08:43:25 +02:00
|
|
|
if err != nil {
|
|
|
|
|
s.warnOnce(fmt.Errorf("logshipper: build request: %w", err))
|
2026-11-21 00:23:35 +01:00
|
|
|
return false
|
2026-09-01 08:43:25 +02:00
|
|
|
}
|
|
|
|
|
req.Header.Set("Content-Type", "application/json")
|
2026-11-21 00:23:35 +01:00
|
|
|
req.Header.Set("Authorization", "Bearer "+token)
|
2026-09-01 08:43:25 +02:00
|
|
|
|
|
|
|
|
resp, err := s.client.Do(req)
|
|
|
|
|
if err != nil {
|
2026-11-21 00:23:35 +01:00
|
|
|
s.warnOnce(fmt.Errorf("logshipper: send %d entries to %s, will retry: %w", entries, url, err))
|
|
|
|
|
return true
|
2026-09-01 08:43:25 +02:00
|
|
|
}
|
|
|
|
|
defer resp.Body.Close()
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
if resp.StatusCode >= 200 && resp.StatusCode < 300 {
|
|
|
|
|
return false
|
2026-09-01 08:43:25 +02:00
|
|
|
}
|
2026-11-21 00:23:35 +01:00
|
|
|
retry = resp.StatusCode == http.StatusTooManyRequests || resp.StatusCode >= 500
|
|
|
|
|
if retry {
|
|
|
|
|
s.warnOnce(fmt.Errorf("logshipper: OmniLogger answered HTTP %d for %d entries, will retry", resp.StatusCode, entries))
|
|
|
|
|
} else {
|
|
|
|
|
s.warnOnce(fmt.Errorf("logshipper: OmniLogger rejected %d entries: HTTP %d", entries, resp.StatusCode))
|
|
|
|
|
}
|
|
|
|
|
return retry
|
2026-09-01 08:43:25 +02:00
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// warnOnce prints a local stderr warning at most once per minute, no matter
|
2026-09-06 22:50:38 +02:00
|
|
|
// how many sends fail in that window, so an unreachable OmniLogger cannot
|
2026-09-01 08:43:25 +02:00
|
|
|
// 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)
|
2026-11-21 00:23:35 +01:00
|
|
|
upper, _ := sevName(sev)
|
2026-09-01 08:43:25 +02:00
|
|
|
|
|
|
|
|
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))
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
s.shipEntry(sev, ctx, msg, now)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Ship queues one entry for OmniLogger at severity sev without printing it locally. Use it where the host
|
|
|
|
|
// already prints its own lines, such as a zap or slog core that tees to OmniLogger: the console is not
|
|
|
|
|
// doubled, and the entry keeps its real severity, where Writer ships everything as info. The threshold
|
|
|
|
|
// applies. Context is sent unscrubbed, as in emit.
|
|
|
|
|
func (s *Shipper) Ship(sev Level, ctx map[string]any, args ...any) {
|
|
|
|
|
if sev < s.threshold {
|
|
|
|
|
return
|
|
|
|
|
}
|
|
|
|
|
s.shipEntry(sev, ctx, formatArgs(args), time.Now())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// shipEntry buffers one already-formatted entry for OmniLogger.
|
|
|
|
|
func (s *Shipper) shipEntry(sev Level, ctx map[string]any, msg string, now time.Time) {
|
|
|
|
|
_, lower := sevName(sev)
|
|
|
|
|
// The context shipped to OmniLogger 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. Only
|
|
|
|
|
// the local verbose dump scrubs them.
|
2026-09-01 08:43:25 +02:00
|
|
|
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,
|
2026-11-21 00:23:35 +01:00
|
|
|
OccurredAt: now.UTC().Truncate(time.Millisecond),
|
2026-09-01 08:43:25 +02:00
|
|
|
})
|
|
|
|
|
}
|
|
|
|
|
|
2026-11-21 00:23:35 +01:00
|
|
|
// Writer returns an io.Writer that ships every non-empty line written to it to OmniLogger for this
|
|
|
|
|
// Shipper's service. It prints nothing locally, so it is meant to be paired with the console writer, e.g.
|
|
|
|
|
// log.SetOutput(io.MultiWriter(os.Stderr, shipper.Writer())), which keeps the existing stdout/stderr
|
|
|
|
|
// output and mirrors the lines to OmniLogger. The standard library log package carries no severity, so
|
|
|
|
|
// each line's level comes from InferLevel. Where a host knows the real level, use Ship instead.
|
|
|
|
|
func (s *Shipper) Writer() io.Writer {
|
|
|
|
|
return lineWriter{s: s}
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type lineWriter struct {
|
|
|
|
|
s *Shipper
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
func (w lineWriter) Write(p []byte) (int, error) {
|
|
|
|
|
now := time.Now()
|
|
|
|
|
for _, line := range strings.Split(string(p), "\n") {
|
|
|
|
|
line = strings.TrimRight(line, "\r")
|
|
|
|
|
if strings.TrimSpace(line) == "" {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
sev := InferLevel(line)
|
|
|
|
|
if sev < w.s.threshold {
|
|
|
|
|
continue
|
|
|
|
|
}
|
|
|
|
|
w.s.shipEntry(sev, nil, line, now)
|
|
|
|
|
}
|
|
|
|
|
return len(p), nil
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// severityRules are checked in order, and the first rule whose words appear in a line sets its level.
|
|
|
|
|
// Each word matches as a whole word, case-insensitively.
|
|
|
|
|
var severityRules = []struct {
|
|
|
|
|
level Level
|
|
|
|
|
pattern *regexp.Regexp
|
|
|
|
|
}{
|
|
|
|
|
{LevelCritical, regexp.MustCompile(`(?i)\b(panic|fatal|critical)\b`)},
|
|
|
|
|
{LevelError, regexp.MustCompile(`(?i)\b(error|errors|failed|failure|failures|could not|cannot|unable to)\b`)},
|
|
|
|
|
{LevelWarn, regexp.MustCompile(`(?i)\b(warn|warning|skipped|unavailable|retry|retrying|timed out|timeout)\b`)},
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// InferLevel guesses the severity of a plain text line from its wording, for hosts whose logging carries no
|
|
|
|
|
// level, such as the standard library log package. Words such as "panic" or "fatal" give critical; "error",
|
|
|
|
|
// "failed", "could not", and "cannot" give error; "warning", "skipped", "unavailable", "retry", and "timeout"
|
|
|
|
|
// give warn; any other line is info. A line that mentions an error without failing, such as "no errors
|
|
|
|
|
// found", is classified as an error too. Use Ship where the real level is known.
|
|
|
|
|
func InferLevel(line string) Level {
|
|
|
|
|
for _, rule := range severityRules {
|
|
|
|
|
if rule.pattern.MatchString(line) {
|
|
|
|
|
return rule.level
|
|
|
|
|
}
|
|
|
|
|
}
|
|
|
|
|
return LevelInfo
|
|
|
|
|
}
|
|
|
|
|
|
2026-09-01 08:43:25 +02:00
|
|
|
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...) }
|