feat(clients): add Python, Go, and Java client libraries (BIT-14250)
Zero-dependency clients for errors.bitreport.pt following the same patterns as clients/node and clients/php: batch size 25, 5 s flush interval, 8 s HTTP timeout, fire-and-forget, env-var config. Each client ships with unit tests backed by an embedded HTTP server (no mocks), an example file, and a build manifest (pyproject.toml, go.mod, pom.xml). Co-Authored-By: Claude Sonnet 4.6 <[email protected]>
This commit is contained in:
1 parent
8bb49ce32b
commit
da57d2a444
12 files changed
+1653
No files matched your search
@@ -0,0 +1,326 @@
|
||||
// Package errorreporter is a lightweight client for errors.bitreport.pt.
|
||||
//
|
||||
// Drop this file (and go.mod) into any Go 1.21+ project. Zero external dependencies.
|
||||
//
|
||||
// Usage:
|
||||
//
|
||||
// import errorreporter "pt.bitreport/errors-go"
|
||||
//
|
||||
// func main() {
|
||||
// errorreporter.Init(errorreporter.Config{Token: os.Getenv("ERROR_REPORTING_TOKEN")})
|
||||
// defer errorreporter.Flush()
|
||||
// ...
|
||||
// if err := doSomething(); err != nil {
|
||||
// errorreporter.ReportError(err, nil)
|
||||
// }
|
||||
// }
|
||||
//
|
||||
// Environment variables:
|
||||
//
|
||||
// ERROR_REPORTING_TOKEN — ingest API key (required)
|
||||
// ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
|
||||
// ERROR_REPORTING_DISABLED — set to "1" to disable
|
||||
// ERROR_REPORTING_PROJECT_NAME — display name (optional)
|
||||
// ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
|
||||
// ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
|
||||
package errorreporter
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"os"
|
||||
"runtime"
|
||||
"strings"
|
||||
"sync"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
defaultEndpoint = "https://errors.bitreport.pt"
|
||||
batchSize = 25
|
||||
flushInterval = 5 * time.Second
|
||||
httpTimeout = 8 * time.Second
|
||||
)
|
||||
|
||||
// Config holds reporter configuration. All fields are optional; unset fields
|
||||
// fall back to the corresponding environment variable.
|
||||
type Config struct {
|
||||
Token string
|
||||
Endpoint string
|
||||
Disabled bool
|
||||
ProjectName string
|
||||
ProjectSlug string
|
||||
GiteaRepo string
|
||||
}
|
||||
|
||||
type ingestEvent struct {
|
||||
SchemaVersion int `json:"schema_version"`
|
||||
OccurredAt string `json:"occurred_at"`
|
||||
Level string `json:"level"`
|
||||
Message string `json:"message"`
|
||||
Stacktrace string `json:"stacktrace,omitempty"`
|
||||
Context map[string]interface{} `json:"context,omitempty"`
|
||||
}
|
||||
|
||||
var (
|
||||
mu sync.Mutex
|
||||
cfg Config
|
||||
queue []ingestEvent
|
||||
flushTimer *time.Timer
|
||||
httpClient = &http.Client{Timeout: httpTimeout}
|
||||
)
|
||||
|
||||
// Init initialises the reporter. Call once at startup before any Report* calls.
|
||||
func Init(c Config) {
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
|
||||
cfg.Token = coalesce(c.Token, os.Getenv("ERROR_REPORTING_TOKEN"))
|
||||
ep := coalesce(c.Endpoint, os.Getenv("ERROR_REPORTING_ENDPOINT"), defaultEndpoint)
|
||||
cfg.Endpoint = strings.TrimRight(ep, "/")
|
||||
cfg.Disabled = c.Disabled || os.Getenv("ERROR_REPORTING_DISABLED") == "1"
|
||||
cfg.ProjectName = coalesce(c.ProjectName, os.Getenv("ERROR_REPORTING_PROJECT_NAME"))
|
||||
cfg.ProjectSlug = coalesce(c.ProjectSlug, os.Getenv("ERROR_REPORTING_PROJECT_SLUG"))
|
||||
cfg.GiteaRepo = coalesce(c.GiteaRepo, os.Getenv("ERROR_REPORTING_GITEA_REPO"))
|
||||
}
|
||||
|
||||
// ReportError reports an error with an optional context map.
|
||||
func ReportError(err error, ctx map[string]interface{}) {
|
||||
mu.Lock()
|
||||
tok, dis, pn, ps, gr, ep := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo, cfg.Endpoint
|
||||
mu.Unlock()
|
||||
|
||||
if dis || tok == "" || err == nil {
|
||||
return
|
||||
}
|
||||
_ = ep // used via snapshot; referenced in send
|
||||
|
||||
buf := make([]byte, 8192)
|
||||
n := runtime.Stack(buf, false)
|
||||
stack := string(buf[:n])
|
||||
|
||||
filePath, lineNum := callerInfo()
|
||||
|
||||
c := map[string]interface{}{
|
||||
"error_type": typeName(err),
|
||||
}
|
||||
if filePath != "" {
|
||||
c["file_path"] = filePath
|
||||
}
|
||||
if lineNum > 0 {
|
||||
c["line_number"] = lineNum
|
||||
}
|
||||
if pn != "" {
|
||||
c["project_name"] = pn
|
||||
}
|
||||
if ps != "" {
|
||||
c["project_slug"] = ps
|
||||
}
|
||||
if gr != "" {
|
||||
c["gitea_repo"] = gr
|
||||
}
|
||||
for k, v := range ctx {
|
||||
c[k] = v
|
||||
}
|
||||
|
||||
enqueue(ingestEvent{
|
||||
SchemaVersion: 1,
|
||||
OccurredAt: nowISO(),
|
||||
Level: "error",
|
||||
Message: err.Error(),
|
||||
Stacktrace: stack,
|
||||
Context: c,
|
||||
})
|
||||
}
|
||||
|
||||
// ReportMessage reports a plain string message at the given level.
|
||||
// level must be one of: "error", "warning", "info", "critical".
|
||||
func ReportMessage(message, level string, ctx map[string]interface{}) {
|
||||
mu.Lock()
|
||||
tok, dis, pn, ps, gr := cfg.Token, cfg.Disabled, cfg.ProjectName, cfg.ProjectSlug, cfg.GiteaRepo
|
||||
mu.Unlock()
|
||||
|
||||
if dis || tok == "" {
|
||||
return
|
||||
}
|
||||
if level == "" {
|
||||
level = "error"
|
||||
}
|
||||
|
||||
c := map[string]interface{}{}
|
||||
if pn != "" {
|
||||
c["project_name"] = pn
|
||||
}
|
||||
if ps != "" {
|
||||
c["project_slug"] = ps
|
||||
}
|
||||
if gr != "" {
|
||||
c["gitea_repo"] = gr
|
||||
}
|
||||
for k, v := range ctx {
|
||||
c[k] = v
|
||||
}
|
||||
|
||||
ev := ingestEvent{
|
||||
SchemaVersion: 1,
|
||||
OccurredAt: nowISO(),
|
||||
Level: level,
|
||||
Message: message,
|
||||
}
|
||||
if len(c) > 0 {
|
||||
ev.Context = c
|
||||
}
|
||||
enqueue(ev)
|
||||
}
|
||||
|
||||
// Flush sends all queued events synchronously. Call before process exit (e.g. via defer).
|
||||
func Flush() {
|
||||
mu.Lock()
|
||||
if flushTimer != nil {
|
||||
flushTimer.Stop()
|
||||
flushTimer = nil
|
||||
}
|
||||
batch := make([]ingestEvent, len(queue))
|
||||
copy(batch, queue)
|
||||
queue = queue[:0]
|
||||
mu.Unlock()
|
||||
|
||||
send(batch)
|
||||
}
|
||||
|
||||
// RecoverAndReport is a deferred helper that catches a panic, reports it, flushes,
|
||||
// then re-panics so the runtime still terminates the goroutine normally.
|
||||
//
|
||||
// defer errorreporter.RecoverAndReport(nil)
|
||||
func RecoverAndReport(ctx map[string]interface{}) {
|
||||
if r := recover(); r != nil {
|
||||
var err error
|
||||
switch v := r.(type) {
|
||||
case error:
|
||||
err = v
|
||||
default:
|
||||
err = fmt.Errorf("%v", v)
|
||||
}
|
||||
ReportError(err, ctx)
|
||||
Flush()
|
||||
panic(r)
|
||||
}
|
||||
}
|
||||
|
||||
// --- internals ---
|
||||
|
||||
func enqueue(ev ingestEvent) {
|
||||
var toSend []ingestEvent
|
||||
|
||||
mu.Lock()
|
||||
queue = append(queue, ev)
|
||||
if len(queue) >= batchSize {
|
||||
toSend = make([]ingestEvent, len(queue))
|
||||
copy(toSend, queue)
|
||||
queue = queue[:0]
|
||||
} else if flushTimer == nil {
|
||||
flushTimer = time.AfterFunc(flushInterval, flushAsync)
|
||||
}
|
||||
mu.Unlock()
|
||||
|
||||
if toSend != nil {
|
||||
go send(toSend)
|
||||
}
|
||||
}
|
||||
|
||||
func flushAsync() {
|
||||
mu.Lock()
|
||||
flushTimer = nil
|
||||
if len(queue) == 0 {
|
||||
mu.Unlock()
|
||||
return
|
||||
}
|
||||
batch := make([]ingestEvent, len(queue))
|
||||
copy(batch, queue)
|
||||
queue = queue[:0]
|
||||
mu.Unlock()
|
||||
|
||||
send(batch)
|
||||
}
|
||||
|
||||
func send(events []ingestEvent) {
|
||||
if len(events) == 0 {
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
tok := cfg.Token
|
||||
ep := cfg.Endpoint
|
||||
mu.Unlock()
|
||||
|
||||
for i := 0; i < len(events); i += batchSize {
|
||||
end := i + batchSize
|
||||
if end > len(events) {
|
||||
end = len(events)
|
||||
}
|
||||
sendBatch(tok, ep, events[i:end])
|
||||
}
|
||||
}
|
||||
|
||||
func sendBatch(token, endpoint string, events []ingestEvent) {
|
||||
body, err := json.Marshal(map[string]interface{}{"events": events})
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, endpoint+"/v1/ingest/events", bytes.NewReader(body))
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("Authorization", "Bearer "+token)
|
||||
resp, err := httpClient.Do(req)
|
||||
if err != nil {
|
||||
return
|
||||
}
|
||||
resp.Body.Close()
|
||||
}
|
||||
|
||||
func nowISO() string {
|
||||
t := time.Now().UTC()
|
||||
ms := t.Nanosecond() / 1e6
|
||||
return fmt.Sprintf("%04d-%02d-%02dT%02d:%02d:%02d.%03dZ",
|
||||
t.Year(), t.Month(), t.Day(), t.Hour(), t.Minute(), t.Second(), ms)
|
||||
}
|
||||
|
||||
func callerInfo() (string, int) {
|
||||
pcs := make([]uintptr, 16)
|
||||
// skip: runtime.Callers, callerInfo, ReportError/ReportMessage
|
||||
n := runtime.Callers(3, pcs)
|
||||
frames := runtime.CallersFrames(pcs[:n])
|
||||
for {
|
||||
f, more := frames.Next()
|
||||
if !strings.HasSuffix(f.File, "error_reporter.go") {
|
||||
return f.File, f.Line
|
||||
}
|
||||
if !more {
|
||||
break
|
||||
}
|
||||
}
|
||||
return "", 0
|
||||
}
|
||||
|
||||
func typeName(err error) string {
|
||||
if err == nil {
|
||||
return ""
|
||||
}
|
||||
t := fmt.Sprintf("%T", err)
|
||||
if idx := strings.LastIndex(t, "."); idx >= 0 {
|
||||
return t[idx+1:]
|
||||
}
|
||||
return t
|
||||
}
|
||||
|
||||
func coalesce(vals ...string) string {
|
||||
for _, v := range vals {
|
||||
if v != "" {
|
||||
return v
|
||||
}
|
||||
}
|
||||
return ""
|
||||
}
|
||||
@@ -0,0 +1,187 @@
|
||||
package errorreporter_test
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
errorreporter "pt.bitreport/errors-go"
|
||||
)
|
||||
|
||||
// captureServer starts a test HTTP server that collects posted request bodies.
|
||||
func captureServer(t *testing.T) (*httptest.Server, *[]map[string]interface{}, *sync.Mutex) {
|
||||
t.Helper()
|
||||
var mu sync.Mutex
|
||||
var bodies []map[string]interface{}
|
||||
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]interface{}
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Logf("decode error: %v", err)
|
||||
return
|
||||
}
|
||||
mu.Lock()
|
||||
bodies = append(bodies, body)
|
||||
mu.Unlock()
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, &bodies, &mu
|
||||
}
|
||||
|
||||
func TestReportError(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
|
||||
errorreporter.ReportError(errors.New("something failed"), nil)
|
||||
errorreporter.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(*bodies) != 1 {
|
||||
t.Fatalf("expected 1 request, got %d", len(*bodies))
|
||||
}
|
||||
events := (*bodies)[0]["events"].([]interface{})
|
||||
if len(events) != 1 {
|
||||
t.Fatalf("expected 1 event, got %d", len(events))
|
||||
}
|
||||
ev := events[0].(map[string]interface{})
|
||||
if ev["level"] != "error" {
|
||||
t.Errorf("level = %v, want error", ev["level"])
|
||||
}
|
||||
if ev["message"] != "something failed" {
|
||||
t.Errorf("message = %v, want 'something failed'", ev["message"])
|
||||
}
|
||||
if ev["schema_version"].(float64) != 1 {
|
||||
t.Errorf("schema_version = %v, want 1", ev["schema_version"])
|
||||
}
|
||||
if ev["stacktrace"] == "" {
|
||||
t.Error("expected non-empty stacktrace")
|
||||
}
|
||||
ctx := ev["context"].(map[string]interface{})
|
||||
if ctx["error_type"] == "" {
|
||||
t.Error("expected non-empty error_type in context")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReportMessage(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
|
||||
errorreporter.ReportMessage("disk nearly full", "warning", map[string]interface{}{"used_pct": 95})
|
||||
errorreporter.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(*bodies) != 1 {
|
||||
t.Fatalf("expected 1 request, got %d", len(*bodies))
|
||||
}
|
||||
ev := (*bodies)[0]["events"].([]interface{})[0].(map[string]interface{})
|
||||
if ev["level"] != "warning" {
|
||||
t.Errorf("level = %v, want warning", ev["level"])
|
||||
}
|
||||
if ev["message"] != "disk nearly full" {
|
||||
t.Errorf("message = %v, want 'disk nearly full'", ev["message"])
|
||||
}
|
||||
ctx := ev["context"].(map[string]interface{})
|
||||
if ctx["used_pct"].(float64) != 95 {
|
||||
t.Errorf("used_pct = %v, want 95", ctx["used_pct"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestProjectContext(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{
|
||||
Token: "test-tok",
|
||||
Endpoint: srv.URL,
|
||||
ProjectName: "Test App",
|
||||
ProjectSlug: "test-app",
|
||||
GiteaRepo: "org/test-app",
|
||||
})
|
||||
errorreporter.ReportMessage("hello", "info", nil)
|
||||
errorreporter.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
ctx := (*bodies)[0]["events"].([]interface{})[0].(map[string]interface{})["context"].(map[string]interface{})
|
||||
if ctx["project_name"] != "Test App" {
|
||||
t.Errorf("project_name = %v", ctx["project_name"])
|
||||
}
|
||||
if ctx["project_slug"] != "test-app" {
|
||||
t.Errorf("project_slug = %v", ctx["project_slug"])
|
||||
}
|
||||
if ctx["gitea_repo"] != "org/test-app" {
|
||||
t.Errorf("gitea_repo = %v", ctx["gitea_repo"])
|
||||
}
|
||||
}
|
||||
|
||||
func TestDisabledSkipsRequests(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL, Disabled: true})
|
||||
errorreporter.ReportMessage("should not send", "error", nil)
|
||||
errorreporter.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(*bodies) != 0 {
|
||||
t.Errorf("expected 0 requests when disabled, got %d", len(*bodies))
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoTokenSkipsRequests(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "", Endpoint: srv.URL})
|
||||
errorreporter.ReportMessage("no token", "error", nil)
|
||||
errorreporter.Flush()
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
if len(*bodies) != 0 {
|
||||
t.Errorf("expected 0 requests without token, got %d", len(*bodies))
|
||||
}
|
||||
}
|
||||
|
||||
func TestAuthorizationHeader(t *testing.T) {
|
||||
var capturedAuth string
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
capturedAuth = r.Header.Get("Authorization")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}))
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "my-secret-token", Endpoint: srv.URL})
|
||||
errorreporter.ReportMessage("auth check", "info", nil)
|
||||
errorreporter.Flush()
|
||||
|
||||
if capturedAuth != "Bearer my-secret-token" {
|
||||
t.Errorf("Authorization = %q, want 'Bearer my-secret-token'", capturedAuth)
|
||||
}
|
||||
}
|
||||
|
||||
func TestBatchFlushOnSize(t *testing.T) {
|
||||
srv, bodies, mu := captureServer(t)
|
||||
|
||||
errorreporter.Init(errorreporter.Config{Token: "test-tok", Endpoint: srv.URL})
|
||||
for i := 0; i < 25; i++ {
|
||||
errorreporter.ReportMessage("msg", "info", nil)
|
||||
}
|
||||
// Allow time for background goroutine triggered by batch overflow
|
||||
time.Sleep(200 * time.Millisecond)
|
||||
|
||||
mu.Lock()
|
||||
defer mu.Unlock()
|
||||
total := 0
|
||||
for _, b := range *bodies {
|
||||
total += len(b["events"].([]interface{}))
|
||||
}
|
||||
if total != 25 {
|
||||
t.Errorf("expected 25 events total across batches, got %d", total)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
//go:build ignore
|
||||
|
||||
// Basic usage example for the BitReport Go error reporter.
|
||||
//
|
||||
// Run with:
|
||||
//
|
||||
// ERROR_REPORTING_TOKEN=your_token go run basic_usage.go
|
||||
package main
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
errorreporter "pt.bitreport/errors-go"
|
||||
)
|
||||
|
||||
func main() {
|
||||
errorreporter.Init(errorreporter.Config{
|
||||
Token: os.Getenv("ERROR_REPORTING_TOKEN"),
|
||||
ProjectName: "My Go App",
|
||||
ProjectSlug: "my-go-app",
|
||||
})
|
||||
defer errorreporter.Flush()
|
||||
|
||||
// Report a plain message
|
||||
errorreporter.ReportMessage("Application started", "info", nil)
|
||||
|
||||
// Report a warning with extra context
|
||||
errorreporter.ReportMessage("Cache miss", "warning", map[string]interface{}{
|
||||
"cache_key": "user:42",
|
||||
})
|
||||
|
||||
// Report an error
|
||||
if err := riskyOperation(); err != nil {
|
||||
errorreporter.ReportError(err, map[string]interface{}{
|
||||
"operation": "riskyOperation",
|
||||
})
|
||||
}
|
||||
|
||||
fmt.Println("Events sent. Check your errors.bitreport.pt dashboard.")
|
||||
}
|
||||
|
||||
func riskyOperation() error {
|
||||
return errors.New("something went wrong")
|
||||
}
|
||||
@@ -0,0 +1,3 @@
|
||||
module pt.bitreport/errors-go
|
||||
|
||||
go 1.21
|
||||
@@ -0,0 +1,40 @@
|
||||
import pt.bitreport.errors.ErrorReporter;
|
||||
|
||||
import java.util.Map;
|
||||
|
||||
/**
|
||||
* Basic usage example for the BitReport Java error reporter.
|
||||
*
|
||||
* Compile and run:
|
||||
* javac -cp path/to/bitreport-errors-1.0.0.jar BasicUsage.java
|
||||
* ERROR_REPORTING_TOKEN=your_token java -cp .:path/to/bitreport-errors-1.0.0.jar BasicUsage
|
||||
*/
|
||||
public class BasicUsage {
|
||||
public static void main(String[] args) {
|
||||
ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
.token(System.getenv("ERROR_REPORTING_TOKEN"))
|
||||
.projectName("My Java App")
|
||||
.projectSlug("my-java-app")
|
||||
.build());
|
||||
|
||||
// Always flush before the JVM exits
|
||||
Runtime.getRuntime().addShutdownHook(new Thread(ErrorReporter::flush));
|
||||
|
||||
// Report a plain message
|
||||
ErrorReporter.reportMessage("Application started", "info", null);
|
||||
|
||||
// Report a warning with context
|
||||
ErrorReporter.reportMessage("Cache miss", "warning", Map.of("cache_key", "user:42"));
|
||||
|
||||
// Report a caught exception
|
||||
try {
|
||||
int result = Integer.parseInt("not-a-number");
|
||||
} catch (NumberFormatException e) {
|
||||
ErrorReporter.reportError(e, Map.of("input", "not-a-number"));
|
||||
}
|
||||
|
||||
// Flush synchronously so the example does not exit with pending events
|
||||
ErrorReporter.flush();
|
||||
System.out.println("Events sent. Check your errors.bitreport.pt dashboard.");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project xmlns="http://maven.apache.org/POM/4.0.0"
|
||||
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
|
||||
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0
|
||||
https://maven.apache.org/xsd/maven-4.0.0.xsd">
|
||||
<modelVersion>4.0.0</modelVersion>
|
||||
|
||||
<groupId>pt.bitreport</groupId>
|
||||
<artifactId>bitreport-errors</artifactId>
|
||||
<version>1.0.0</version>
|
||||
<packaging>jar</packaging>
|
||||
|
||||
<name>BitReport Error Reporter</name>
|
||||
<description>Lightweight Java client for errors.bitreport.pt</description>
|
||||
<url>https://errors.bitreport.pt</url>
|
||||
|
||||
<properties>
|
||||
<java.version>11</java.version>
|
||||
<maven.compiler.source>${java.version}</maven.compiler.source>
|
||||
<maven.compiler.target>${java.version}</maven.compiler.target>
|
||||
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
|
||||
<junit.version>5.10.2</junit.version>
|
||||
</properties>
|
||||
|
||||
<dependencies>
|
||||
<!-- No runtime dependencies — zero external deps is a design constraint -->
|
||||
|
||||
<!-- Test-only -->
|
||||
<dependency>
|
||||
<groupId>org.junit.jupiter</groupId>
|
||||
<artifactId>junit-jupiter</artifactId>
|
||||
<version>${junit.version}</version>
|
||||
<scope>test</scope>
|
||||
</dependency>
|
||||
</dependencies>
|
||||
|
||||
<build>
|
||||
<plugins>
|
||||
<plugin>
|
||||
<groupId>org.apache.maven.plugins</groupId>
|
||||
<artifactId>maven-surefire-plugin</artifactId>
|
||||
<version>3.2.5</version>
|
||||
</plugin>
|
||||
</plugins>
|
||||
</build>
|
||||
</project>
|
||||
@@ -0,0 +1,366 @@
|
||||
package pt.bitreport.errors;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.OutputStream;
|
||||
import java.net.HttpURLConnection;
|
||||
import java.net.URL;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.time.Instant;
|
||||
import java.time.ZoneOffset;
|
||||
import java.time.format.DateTimeFormatter;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.*;
|
||||
import java.util.concurrent.atomic.AtomicBoolean;
|
||||
import java.util.concurrent.atomic.AtomicReference;
|
||||
|
||||
/**
|
||||
* BitReport Error Reporter — Java client for errors.bitreport.pt ingest API.
|
||||
*
|
||||
* <p>Drop this file into any Java 11+ project. Zero external dependencies.
|
||||
*
|
||||
* <p>Usage:
|
||||
* <pre>{@code
|
||||
* ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
* .token(System.getenv("ERROR_REPORTING_TOKEN"))
|
||||
* .projectSlug("my-java-app")
|
||||
* .build());
|
||||
*
|
||||
* try {
|
||||
* riskyOperation();
|
||||
* } catch (Exception e) {
|
||||
* ErrorReporter.reportError(e, Map.of("operation", "riskyOperation"));
|
||||
* }
|
||||
*
|
||||
* // Before shutdown:
|
||||
* ErrorReporter.flush();
|
||||
* }</pre>
|
||||
*
|
||||
* <p>Environment variables:
|
||||
* <ul>
|
||||
* <li>{@code ERROR_REPORTING_TOKEN} — ingest API key (required)</li>
|
||||
* <li>{@code ERROR_REPORTING_ENDPOINT} — base URL (default: https://errors.bitreport.pt)</li>
|
||||
* <li>{@code ERROR_REPORTING_DISABLED} — set to "1" to disable</li>
|
||||
* <li>{@code ERROR_REPORTING_PROJECT_NAME} — display name (optional)</li>
|
||||
* <li>{@code ERROR_REPORTING_PROJECT_SLUG} — stable product slug (optional)</li>
|
||||
* <li>{@code ERROR_REPORTING_GITEA_REPO} — canonical owner/repo on Gitea (optional)</li>
|
||||
* </ul>
|
||||
*/
|
||||
public final class ErrorReporter {
|
||||
|
||||
private static final String DEFAULT_ENDPOINT = "https://errors.bitreport.pt";
|
||||
private static final int BATCH_SIZE = 25;
|
||||
private static final long FLUSH_MS = 5_000L;
|
||||
private static final int TIMEOUT_MS = 8_000;
|
||||
private static final DateTimeFormatter ISO_FMT =
|
||||
DateTimeFormatter.ofPattern("yyyy-MM-dd'T'HH:mm:ss.SSS'Z'").withZone(ZoneOffset.UTC);
|
||||
|
||||
// --- Config ---
|
||||
|
||||
public static final class Config {
|
||||
final String token;
|
||||
final String endpoint;
|
||||
final boolean disabled;
|
||||
final String projectName;
|
||||
final String projectSlug;
|
||||
final String giteaRepo;
|
||||
|
||||
private Config(Builder b) {
|
||||
this.token = coalesce(b.token, env("ERROR_REPORTING_TOKEN"));
|
||||
this.endpoint = stripTrailingSlash(
|
||||
coalesce(b.endpoint, env("ERROR_REPORTING_ENDPOINT"), DEFAULT_ENDPOINT));
|
||||
this.disabled = b.disabled || "1".equals(env("ERROR_REPORTING_DISABLED"));
|
||||
this.projectName = coalesce(b.projectName, env("ERROR_REPORTING_PROJECT_NAME"));
|
||||
this.projectSlug = coalesce(b.projectSlug, env("ERROR_REPORTING_PROJECT_SLUG"));
|
||||
this.giteaRepo = coalesce(b.giteaRepo, env("ERROR_REPORTING_GITEA_REPO"));
|
||||
}
|
||||
|
||||
public static Builder builder() { return new Builder(); }
|
||||
|
||||
public static final class Builder {
|
||||
private String token = "";
|
||||
private String endpoint = "";
|
||||
private boolean disabled = false;
|
||||
private String projectName = "";
|
||||
private String projectSlug = "";
|
||||
private String giteaRepo = "";
|
||||
|
||||
public Builder token(String v) { this.token = v != null ? v : ""; return this; }
|
||||
public Builder endpoint(String v) { this.endpoint = v != null ? v : ""; return this; }
|
||||
public Builder disabled(boolean v) { this.disabled = v; return this; }
|
||||
public Builder projectName(String v) { this.projectName = v != null ? v : ""; return this; }
|
||||
public Builder projectSlug(String v) { this.projectSlug = v != null ? v : ""; return this; }
|
||||
public Builder giteaRepo(String v) { this.giteaRepo = v != null ? v : ""; return this; }
|
||||
public Config build() { return new Config(this); }
|
||||
}
|
||||
}
|
||||
|
||||
// --- Shared state ---
|
||||
|
||||
private static final AtomicReference<Config> CONFIG = new AtomicReference<>(
|
||||
Config.builder().build());
|
||||
|
||||
private static final List<Map<String, Object>> QUEUE =
|
||||
Collections.synchronizedList(new ArrayList<>());
|
||||
|
||||
private static final ScheduledExecutorService SCHEDULER =
|
||||
Executors.newSingleThreadScheduledExecutor(r -> {
|
||||
Thread t = new Thread(r, "bitreport-flush");
|
||||
t.setDaemon(true);
|
||||
return t;
|
||||
});
|
||||
|
||||
private static final AtomicBoolean TIMER_RUNNING = new AtomicBoolean(false);
|
||||
private static volatile ScheduledFuture<?> FLUSH_TASK = null;
|
||||
|
||||
// prevent instantiation
|
||||
private ErrorReporter() {}
|
||||
|
||||
// --- Public API ---
|
||||
|
||||
/** Initialise the reporter. Call once at startup. */
|
||||
public static void init(Config config) {
|
||||
CONFIG.set(config);
|
||||
}
|
||||
|
||||
/** Report a {@link Throwable} with optional extra context. */
|
||||
public static void reportError(Throwable t, Map<String, Object> extraContext) {
|
||||
Config c = CONFIG.get();
|
||||
if (c.disabled || c.token.isEmpty() || t == null) return;
|
||||
|
||||
Map<String, Object> ctx = new LinkedHashMap<>();
|
||||
ctx.put("error_type", t.getClass().getSimpleName());
|
||||
|
||||
// Extract deepest stack frame outside this class
|
||||
StackTraceElement caller = findCaller(t.getStackTrace());
|
||||
if (caller != null) {
|
||||
ctx.put("file_path", caller.getFileName() != null ? caller.getFileName() : "");
|
||||
ctx.put("line_number", caller.getLineNumber());
|
||||
}
|
||||
|
||||
addProjectFields(ctx, c);
|
||||
if (extraContext != null) ctx.putAll(extraContext);
|
||||
|
||||
String stack = stackTraceString(t);
|
||||
|
||||
Map<String, Object> event = new LinkedHashMap<>();
|
||||
event.put("schema_version", 1);
|
||||
event.put("occurred_at", nowISO());
|
||||
event.put("level", "error");
|
||||
event.put("message", t.getMessage() != null ? t.getMessage() : t.toString());
|
||||
event.put("stacktrace", stack);
|
||||
event.put("context", ctx);
|
||||
|
||||
enqueue(event);
|
||||
}
|
||||
|
||||
/**
|
||||
* Report a plain message.
|
||||
*
|
||||
* @param message the message text
|
||||
* @param level one of: "error", "warning", "info", "critical"
|
||||
* @param context optional key-value pairs (may be null)
|
||||
*/
|
||||
public static void reportMessage(String message, String level, Map<String, Object> context) {
|
||||
Config c = CONFIG.get();
|
||||
if (c.disabled || c.token.isEmpty()) return;
|
||||
|
||||
Map<String, Object> ctx = new LinkedHashMap<>();
|
||||
addProjectFields(ctx, c);
|
||||
if (context != null) ctx.putAll(context);
|
||||
|
||||
Map<String, Object> event = new LinkedHashMap<>();
|
||||
event.put("schema_version", 1);
|
||||
event.put("occurred_at", nowISO());
|
||||
event.put("level", level != null && !level.isEmpty() ? level : "error");
|
||||
event.put("message", message);
|
||||
if (!ctx.isEmpty()) event.put("context", ctx);
|
||||
|
||||
enqueue(event);
|
||||
}
|
||||
|
||||
/** Flush all queued events synchronously. Call before JVM shutdown. */
|
||||
public static void flush() {
|
||||
cancelTimer();
|
||||
List<Map<String, Object>> snapshot;
|
||||
synchronized (QUEUE) {
|
||||
snapshot = new ArrayList<>(QUEUE);
|
||||
QUEUE.clear();
|
||||
}
|
||||
sendInBatches(snapshot);
|
||||
}
|
||||
|
||||
// --- internals ---
|
||||
|
||||
private static void enqueue(Map<String, Object> event) {
|
||||
List<Map<String, Object>> batch = null;
|
||||
synchronized (QUEUE) {
|
||||
QUEUE.add(event);
|
||||
if (QUEUE.size() >= BATCH_SIZE) {
|
||||
batch = new ArrayList<>(QUEUE);
|
||||
QUEUE.clear();
|
||||
}
|
||||
}
|
||||
if (batch != null) {
|
||||
final List<Map<String, Object>> toSend = batch;
|
||||
SCHEDULER.submit(() -> sendInBatches(toSend));
|
||||
} else {
|
||||
scheduleFlushTimer();
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized void scheduleFlushTimer() {
|
||||
if (FLUSH_TASK == null || FLUSH_TASK.isDone()) {
|
||||
FLUSH_TASK = SCHEDULER.schedule(() -> {
|
||||
List<Map<String, Object>> batch;
|
||||
synchronized (QUEUE) {
|
||||
batch = new ArrayList<>(QUEUE);
|
||||
QUEUE.clear();
|
||||
}
|
||||
sendInBatches(batch);
|
||||
}, FLUSH_MS, TimeUnit.MILLISECONDS);
|
||||
}
|
||||
}
|
||||
|
||||
private static synchronized void cancelTimer() {
|
||||
if (FLUSH_TASK != null) {
|
||||
FLUSH_TASK.cancel(false);
|
||||
FLUSH_TASK = null;
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendInBatches(List<Map<String, Object>> events) {
|
||||
if (events.isEmpty()) return;
|
||||
for (int i = 0; i < events.size(); i += BATCH_SIZE) {
|
||||
int end = Math.min(i + BATCH_SIZE, events.size());
|
||||
sendBatch(events.subList(i, end));
|
||||
}
|
||||
}
|
||||
|
||||
private static void sendBatch(List<Map<String, Object>> events) {
|
||||
if (events.isEmpty()) return;
|
||||
Config c = CONFIG.get();
|
||||
try {
|
||||
String body = toJson(Map.of("events", events));
|
||||
byte[] payload = body.getBytes(StandardCharsets.UTF_8);
|
||||
|
||||
URL url = new URL(c.endpoint + "/v1/ingest/events");
|
||||
HttpURLConnection conn = (HttpURLConnection) url.openConnection();
|
||||
conn.setRequestMethod("POST");
|
||||
conn.setRequestProperty("Content-Type", "application/json");
|
||||
conn.setRequestProperty("Authorization", "Bearer " + c.token);
|
||||
conn.setConnectTimeout(TIMEOUT_MS);
|
||||
conn.setReadTimeout(TIMEOUT_MS);
|
||||
conn.setDoOutput(true);
|
||||
|
||||
try (OutputStream os = conn.getOutputStream()) {
|
||||
os.write(payload);
|
||||
}
|
||||
conn.getResponseCode(); // consume response so the connection is reusable
|
||||
conn.disconnect();
|
||||
} catch (Exception ignored) {
|
||||
// fire-and-forget: never crash the host app
|
||||
}
|
||||
}
|
||||
|
||||
// --- helpers ---
|
||||
|
||||
private static void addProjectFields(Map<String, Object> ctx, Config c) {
|
||||
if (!c.projectName.isEmpty()) ctx.put("project_name", c.projectName);
|
||||
if (!c.projectSlug.isEmpty()) ctx.put("project_slug", c.projectSlug);
|
||||
if (!c.giteaRepo.isEmpty()) ctx.put("gitea_repo", c.giteaRepo);
|
||||
}
|
||||
|
||||
private static StackTraceElement findCaller(StackTraceElement[] frames) {
|
||||
String thisClass = ErrorReporter.class.getName();
|
||||
for (StackTraceElement f : frames) {
|
||||
if (!f.getClassName().equals(thisClass)) return f;
|
||||
}
|
||||
return frames.length > 0 ? frames[0] : null;
|
||||
}
|
||||
|
||||
private static String stackTraceString(Throwable t) {
|
||||
StringBuilder sb = new StringBuilder();
|
||||
sb.append(t.toString()).append('\n');
|
||||
for (StackTraceElement e : t.getStackTrace()) {
|
||||
sb.append("\tat ").append(e).append('\n');
|
||||
}
|
||||
Throwable cause = t.getCause();
|
||||
if (cause != null) {
|
||||
sb.append("Caused by: ").append(stackTraceString(cause));
|
||||
}
|
||||
return sb.toString().trim();
|
||||
}
|
||||
|
||||
private static String nowISO() {
|
||||
return ISO_FMT.format(Instant.now());
|
||||
}
|
||||
|
||||
private static String env(String key) {
|
||||
String v = System.getenv(key);
|
||||
return v != null ? v.trim() : "";
|
||||
}
|
||||
|
||||
private static String coalesce(String... vals) {
|
||||
for (String v : vals) {
|
||||
if (v != null && !v.isEmpty()) return v;
|
||||
}
|
||||
return "";
|
||||
}
|
||||
|
||||
private static String stripTrailingSlash(String s) {
|
||||
return s.endsWith("/") ? s.substring(0, s.length() - 1) : s;
|
||||
}
|
||||
|
||||
// Minimal JSON serialiser — supports: String, Number, Boolean, null, Map, List
|
||||
@SuppressWarnings("unchecked")
|
||||
static String toJson(Object value) {
|
||||
if (value == null) return "null";
|
||||
if (value instanceof Boolean) return value.toString();
|
||||
if (value instanceof Number) return value.toString();
|
||||
if (value instanceof String) return jsonString((String) value);
|
||||
if (value instanceof Map) {
|
||||
Map<String, Object> map = (Map<String, Object>) value;
|
||||
StringBuilder sb = new StringBuilder("{");
|
||||
boolean first = true;
|
||||
for (Map.Entry<String, Object> entry : map.entrySet()) {
|
||||
if (!first) sb.append(',');
|
||||
sb.append(jsonString(entry.getKey())).append(':').append(toJson(entry.getValue()));
|
||||
first = false;
|
||||
}
|
||||
return sb.append('}').toString();
|
||||
}
|
||||
if (value instanceof List) {
|
||||
List<Object> list = (List<Object>) value;
|
||||
StringBuilder sb = new StringBuilder("[");
|
||||
for (int i = 0; i < list.size(); i++) {
|
||||
if (i > 0) sb.append(',');
|
||||
sb.append(toJson(list.get(i)));
|
||||
}
|
||||
return sb.append(']').toString();
|
||||
}
|
||||
return jsonString(value.toString());
|
||||
}
|
||||
|
||||
private static String jsonString(String s) {
|
||||
StringBuilder sb = new StringBuilder("\"");
|
||||
for (int i = 0; i < s.length(); i++) {
|
||||
char ch = s.charAt(i);
|
||||
if (ch == '"') {
|
||||
sb.append("\\\"");
|
||||
} else if (ch == '\\') {
|
||||
sb.append("\\\\");
|
||||
} else if (ch == '\n') {
|
||||
sb.append("\\n");
|
||||
} else if (ch == '\r') {
|
||||
sb.append("\\r");
|
||||
} else if (ch == '\t') {
|
||||
sb.append("\\t");
|
||||
} else if (ch < 0x20) {
|
||||
sb.append(String.format("\\u%04x", (int) ch));
|
||||
} else {
|
||||
sb.append(ch);
|
||||
}
|
||||
}
|
||||
return sb.append('"').toString();
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,184 @@
|
||||
package pt.bitreport.errors;
|
||||
|
||||
import com.sun.net.httpserver.HttpServer;
|
||||
import org.junit.jupiter.api.*;
|
||||
|
||||
import java.io.IOException;
|
||||
import java.io.InputStream;
|
||||
import java.net.InetSocketAddress;
|
||||
import java.nio.charset.StandardCharsets;
|
||||
import java.util.*;
|
||||
import java.util.concurrent.CopyOnWriteArrayList;
|
||||
|
||||
import static org.junit.jupiter.api.Assertions.*;
|
||||
|
||||
class ErrorReporterTest {
|
||||
|
||||
/** Minimal embedded HTTP server that records raw request bodies. */
|
||||
static HttpServer httpServer;
|
||||
static int port;
|
||||
static final List<String> RECEIVED = new CopyOnWriteArrayList<>();
|
||||
|
||||
@BeforeAll
|
||||
static void startServer() throws IOException {
|
||||
httpServer = HttpServer.create(new InetSocketAddress("127.0.0.1", 0), 0);
|
||||
port = httpServer.getAddress().getPort();
|
||||
httpServer.createContext("/v1/ingest/events", exchange -> {
|
||||
try (InputStream is = exchange.getRequestBody()) {
|
||||
RECEIVED.add(new String(is.readAllBytes(), StandardCharsets.UTF_8));
|
||||
}
|
||||
exchange.sendResponseHeaders(200, 0);
|
||||
exchange.close();
|
||||
});
|
||||
httpServer.start();
|
||||
}
|
||||
|
||||
@AfterAll
|
||||
static void stopServer() {
|
||||
httpServer.stop(0);
|
||||
}
|
||||
|
||||
@BeforeEach
|
||||
void reset() {
|
||||
RECEIVED.clear();
|
||||
ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
.token("test-token")
|
||||
.endpoint("http://127.0.0.1:" + port)
|
||||
.build());
|
||||
}
|
||||
|
||||
// --- reportError ---
|
||||
|
||||
@Test
|
||||
void reportError_sendsOneEvent() throws Exception {
|
||||
ErrorReporter.reportError(new IllegalArgumentException("bad arg"), null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
assertEquals(1, RECEIVED.size());
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"level\":\"error\""), "level should be error");
|
||||
assertTrue(body.contains("\"message\":\"bad arg\""), "message should be present");
|
||||
assertTrue(body.contains("\"schema_version\":1"), "schema_version should be 1");
|
||||
assertTrue(body.contains("\"stacktrace\""), "stacktrace should be present");
|
||||
assertTrue(body.contains("IllegalArgumentException"), "error_type should be in context");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportError_includesFileAndLine() throws Exception {
|
||||
ErrorReporter.reportError(new RuntimeException("loc"), null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"file_path\""), "file_path should be in context");
|
||||
assertTrue(body.contains("\"line_number\""), "line_number should be in context");
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportError_mergesExtraContext() throws Exception {
|
||||
Map<String, Object> ctx = new LinkedHashMap<>();
|
||||
ctx.put("request_id", "req-abc");
|
||||
ctx.put("user_id", 42);
|
||||
ErrorReporter.reportError(new RuntimeException("ctx test"), ctx);
|
||||
ErrorReporter.flush();
|
||||
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"request_id\":\"req-abc\""), "request_id should be present");
|
||||
assertTrue(body.contains("\"user_id\":42"), "user_id should be present");
|
||||
}
|
||||
|
||||
// --- reportMessage ---
|
||||
|
||||
@Test
|
||||
void reportMessage_defaultLevel() throws Exception {
|
||||
ErrorReporter.reportMessage("something happened", null, null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"level\":\"error\""), "default level should be error");
|
||||
assertTrue(body.contains("\"message\":\"something happened\""));
|
||||
}
|
||||
|
||||
@Test
|
||||
void reportMessage_customLevel() throws Exception {
|
||||
ErrorReporter.reportMessage("disk usage high", "warning", Map.of("used_pct", 91));
|
||||
ErrorReporter.flush();
|
||||
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"level\":\"warning\""));
|
||||
assertTrue(body.contains("\"used_pct\":91"));
|
||||
}
|
||||
|
||||
// --- project context ---
|
||||
|
||||
@Test
|
||||
void projectFields_addedToContext() throws Exception {
|
||||
ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
.token("test-token")
|
||||
.endpoint("http://127.0.0.1:" + port)
|
||||
.projectName("Test App")
|
||||
.projectSlug("test-app")
|
||||
.giteaRepo("org/test-app")
|
||||
.build());
|
||||
|
||||
ErrorReporter.reportMessage("test", "info", null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
String body = RECEIVED.get(0);
|
||||
assertTrue(body.contains("\"project_name\":\"Test App\""));
|
||||
assertTrue(body.contains("\"project_slug\":\"test-app\""));
|
||||
assertTrue(body.contains("\"gitea_repo\":\"org/test-app\""));
|
||||
}
|
||||
|
||||
// --- disabled / no token ---
|
||||
|
||||
@Test
|
||||
void disabled_skipsRequests() throws Exception {
|
||||
ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
.token("test-token")
|
||||
.endpoint("http://127.0.0.1:" + port)
|
||||
.disabled(true)
|
||||
.build());
|
||||
ErrorReporter.reportMessage("nope", "error", null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
assertEquals(0, RECEIVED.size());
|
||||
}
|
||||
|
||||
@Test
|
||||
void noToken_skipsRequests() throws Exception {
|
||||
ErrorReporter.init(ErrorReporter.Config.builder()
|
||||
.token("")
|
||||
.endpoint("http://127.0.0.1:" + port)
|
||||
.build());
|
||||
ErrorReporter.reportMessage("nope", "error", null);
|
||||
ErrorReporter.flush();
|
||||
|
||||
assertEquals(0, RECEIVED.size());
|
||||
}
|
||||
|
||||
// --- JSON serialiser ---
|
||||
|
||||
@Test
|
||||
void toJson_escapesSpecialCharacters() {
|
||||
String result = ErrorReporter.toJson("hello\nworld\t\"quotes\"");
|
||||
assertEquals("\"hello\\nworld\\t\\\"quotes\\\"\"", result);
|
||||
}
|
||||
|
||||
@Test
|
||||
void toJson_handlesNestedMap() {
|
||||
Map<String, Object> inner = new LinkedHashMap<>();
|
||||
inner.put("a", 1);
|
||||
inner.put("b", true);
|
||||
Map<String, Object> outer = new LinkedHashMap<>();
|
||||
outer.put("key", inner);
|
||||
String json = ErrorReporter.toJson(outer);
|
||||
assertEquals("{\"key\":{\"a\":1,\"b\":true}}", json);
|
||||
}
|
||||
|
||||
@Test
|
||||
void toJson_handlesNullValue() {
|
||||
Map<String, Object> m = new LinkedHashMap<>();
|
||||
m.put("x", null);
|
||||
assertEquals("{\"x\":null}", ErrorReporter.toJson(m));
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,223 @@
|
||||
"""
|
||||
BitReport Error Reporter — Python client for errors.bitreport.pt ingest API.
|
||||
|
||||
Drop this file into any Python 3.8+ project. Zero dependencies (uses urllib).
|
||||
|
||||
Usage:
|
||||
from error_reporter import init_reporter, report_error, report_message, flush
|
||||
init_reporter(token=os.environ['ERROR_REPORTING_TOKEN'])
|
||||
|
||||
try:
|
||||
risky_operation()
|
||||
except Exception as e:
|
||||
report_error(e, {'url': '/api/foo'})
|
||||
|
||||
Environment variables:
|
||||
ERROR_REPORTING_TOKEN — ingest API key (required)
|
||||
ERROR_REPORTING_ENDPOINT — base URL (default: https://errors.bitreport.pt)
|
||||
ERROR_REPORTING_DISABLED — set to "1" to disable
|
||||
ERROR_REPORTING_PROJECT_NAME — display name in ingest context (optional)
|
||||
ERROR_REPORTING_PROJECT_SLUG — stable product slug (optional)
|
||||
ERROR_REPORTING_GITEA_REPO — canonical owner/repo on Gitea (optional)
|
||||
"""
|
||||
|
||||
import json
|
||||
import os
|
||||
import sys
|
||||
import threading
|
||||
import traceback
|
||||
import urllib.request
|
||||
from datetime import datetime, timezone
|
||||
from typing import Any, Dict, List, Optional
|
||||
|
||||
_token: str = ""
|
||||
_endpoint: str = "https://errors.bitreport.pt"
|
||||
_disabled: bool = False
|
||||
_project_name: str = os.environ.get("ERROR_REPORTING_PROJECT_NAME", "")
|
||||
_project_slug: str = os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "")
|
||||
_gitea_repo: str = os.environ.get("ERROR_REPORTING_GITEA_REPO", "")
|
||||
|
||||
_queue: List[Dict[str, Any]] = []
|
||||
_lock = threading.Lock()
|
||||
_flush_timer: Optional[threading.Timer] = None
|
||||
|
||||
BATCH_SIZE = 25
|
||||
FLUSH_SECS = 5.0
|
||||
TIMEOUT_SECS = 8.0
|
||||
|
||||
|
||||
def init_reporter(
|
||||
token: str = "",
|
||||
endpoint: str = "",
|
||||
disabled: Optional[bool] = None,
|
||||
project_name: str = "",
|
||||
project_slug: str = "",
|
||||
gitea_repo: str = "",
|
||||
) -> None:
|
||||
"""Initialise the reporter. Call once at startup."""
|
||||
global _token, _endpoint, _disabled, _project_name, _project_slug, _gitea_repo
|
||||
|
||||
_token = token or os.environ.get("ERROR_REPORTING_TOKEN", "")
|
||||
_endpoint = (
|
||||
endpoint
|
||||
or os.environ.get("ERROR_REPORTING_ENDPOINT", "")
|
||||
or "https://errors.bitreport.pt"
|
||||
).rstrip("/")
|
||||
_disabled = disabled if disabled is not None else os.environ.get("ERROR_REPORTING_DISABLED") == "1"
|
||||
_project_name = project_name or os.environ.get("ERROR_REPORTING_PROJECT_NAME", "") or _project_name
|
||||
_project_slug = project_slug or os.environ.get("ERROR_REPORTING_PROJECT_SLUG", "") or _project_slug
|
||||
_gitea_repo = gitea_repo or os.environ.get("ERROR_REPORTING_GITEA_REPO", "") or _gitea_repo
|
||||
|
||||
if not _disabled and _token:
|
||||
_orig_excepthook = sys.excepthook
|
||||
|
||||
def _excepthook(exc_type, exc_value, exc_tb):
|
||||
report_error(exc_value, {"uncaught": True})
|
||||
_orig_excepthook(exc_type, exc_value, exc_tb)
|
||||
|
||||
sys.excepthook = _excepthook
|
||||
|
||||
|
||||
def report_error(exc: BaseException, context: Optional[Dict[str, Any]] = None) -> None:
|
||||
"""Report an exception with an optional extra context dict."""
|
||||
if _disabled or not _token:
|
||||
return
|
||||
if context is None:
|
||||
context = {}
|
||||
|
||||
tb_lines = traceback.format_exception(type(exc), exc, exc.__traceback__)
|
||||
stack = "".join(tb_lines).strip()
|
||||
|
||||
file_path = ""
|
||||
line_number: Optional[int] = None
|
||||
if exc.__traceback__:
|
||||
tb = exc.__traceback__
|
||||
while tb.tb_next:
|
||||
tb = tb.tb_next
|
||||
file_path = tb.tb_frame.f_code.co_filename
|
||||
line_number = tb.tb_lineno
|
||||
|
||||
ctx: Dict[str, Any] = {"error_type": type(exc).__name__}
|
||||
if file_path:
|
||||
ctx["file_path"] = file_path
|
||||
if line_number is not None:
|
||||
ctx["line_number"] = line_number
|
||||
if _project_name:
|
||||
ctx["project_name"] = _project_name
|
||||
if _project_slug:
|
||||
ctx["project_slug"] = _project_slug
|
||||
if _gitea_repo:
|
||||
ctx["gitea_repo"] = _gitea_repo
|
||||
ctx.update(context)
|
||||
|
||||
_enqueue({
|
||||
"schema_version": 1,
|
||||
"occurred_at": _now_iso(),
|
||||
"level": "error",
|
||||
"message": str(exc),
|
||||
"stacktrace": stack,
|
||||
"context": ctx,
|
||||
})
|
||||
|
||||
|
||||
def report_message(
|
||||
message: str,
|
||||
level: str = "error",
|
||||
context: Optional[Dict[str, Any]] = None,
|
||||
) -> None:
|
||||
"""Report a plain message (warning, info, etc.)."""
|
||||
if _disabled or not _token:
|
||||
return
|
||||
if context is None:
|
||||
context = {}
|
||||
|
||||
ctx: Dict[str, Any] = {}
|
||||
if _project_name:
|
||||
ctx["project_name"] = _project_name
|
||||
if _project_slug:
|
||||
ctx["project_slug"] = _project_slug
|
||||
if _gitea_repo:
|
||||
ctx["gitea_repo"] = _gitea_repo
|
||||
ctx.update(context)
|
||||
|
||||
event: Dict[str, Any] = {
|
||||
"schema_version": 1,
|
||||
"occurred_at": _now_iso(),
|
||||
"level": level,
|
||||
"message": message,
|
||||
}
|
||||
if ctx:
|
||||
event["context"] = ctx
|
||||
_enqueue(event)
|
||||
|
||||
|
||||
def flush() -> None:
|
||||
"""Flush all queued events synchronously. Call before process exit."""
|
||||
global _flush_timer
|
||||
with _lock:
|
||||
if _flush_timer is not None:
|
||||
_flush_timer.cancel()
|
||||
_flush_timer = None
|
||||
to_send = list(_queue)
|
||||
del _queue[:]
|
||||
|
||||
for i in range(0, max(len(to_send), 1), BATCH_SIZE):
|
||||
batch = to_send[i : i + BATCH_SIZE]
|
||||
if batch:
|
||||
_send(batch)
|
||||
|
||||
|
||||
# --- internals ---
|
||||
|
||||
def _now_iso() -> str:
|
||||
now = datetime.now(timezone.utc)
|
||||
return now.strftime(f"%Y-%m-%dT%H:%M:%S.{now.microsecond // 1000:03d}Z")
|
||||
|
||||
|
||||
def _enqueue(event: Dict[str, Any]) -> None:
|
||||
global _flush_timer
|
||||
batch_to_send: Optional[List[Dict[str, Any]]] = None
|
||||
|
||||
with _lock:
|
||||
_queue.append(event)
|
||||
if len(_queue) >= BATCH_SIZE:
|
||||
batch_to_send = _queue[:BATCH_SIZE]
|
||||
del _queue[:BATCH_SIZE]
|
||||
elif _flush_timer is None:
|
||||
_flush_timer = threading.Timer(FLUSH_SECS, _flush_timer_cb)
|
||||
_flush_timer.daemon = True
|
||||
_flush_timer.start()
|
||||
|
||||
if batch_to_send is not None:
|
||||
threading.Thread(target=_send, args=(batch_to_send,), daemon=True).start()
|
||||
|
||||
|
||||
def _flush_timer_cb() -> None:
|
||||
global _flush_timer
|
||||
with _lock:
|
||||
_flush_timer = None
|
||||
if not _queue:
|
||||
return
|
||||
batch = _queue[:BATCH_SIZE]
|
||||
del _queue[:BATCH_SIZE]
|
||||
if batch:
|
||||
threading.Thread(target=_send, args=(batch,), daemon=True).start()
|
||||
|
||||
|
||||
def _send(events: List[Dict[str, Any]]) -> None:
|
||||
if not events:
|
||||
return
|
||||
try:
|
||||
payload = json.dumps({"events": events}).encode("utf-8")
|
||||
req = urllib.request.Request(
|
||||
f"{_endpoint}/v1/ingest/events",
|
||||
data=payload,
|
||||
headers={
|
||||
"Content-Type": "application/json",
|
||||
"Authorization": f"Bearer {_token}",
|
||||
},
|
||||
method="POST",
|
||||
)
|
||||
urllib.request.urlopen(req, timeout=TIMEOUT_SECS)
|
||||
except Exception:
|
||||
pass # fire-and-forget: never crash the host app
|
||||
@@ -0,0 +1,36 @@
|
||||
"""
|
||||
Basic usage example for the BitReport Python error reporter.
|
||||
|
||||
Run with:
|
||||
ERROR_REPORTING_TOKEN=your_token python basic_usage.py
|
||||
"""
|
||||
|
||||
import atexit
|
||||
import os
|
||||
|
||||
from error_reporter import flush, init_reporter, report_error, report_message
|
||||
|
||||
init_reporter(
|
||||
token=os.environ.get("ERROR_REPORTING_TOKEN", ""),
|
||||
project_name="My Python App",
|
||||
project_slug="my-python-app",
|
||||
)
|
||||
|
||||
# Flush before the process exits so queued events are not lost
|
||||
atexit.register(flush)
|
||||
|
||||
# Report a plain message
|
||||
report_message("Application started", level="info")
|
||||
|
||||
# Report a warning with extra context
|
||||
report_message("Cache miss", level="warning", context={"cache_key": "user:42"})
|
||||
|
||||
# Report an exception caught in a try/except
|
||||
try:
|
||||
result = 1 / 0
|
||||
except ZeroDivisionError as e:
|
||||
report_error(e, {"operation": "divide", "numerator": 1, "denominator": 0})
|
||||
|
||||
# Flush immediately so the example does not exit before events are sent
|
||||
flush()
|
||||
print("Events sent. Check your errors.bitreport.pt dashboard.")
|
||||
@@ -0,0 +1,32 @@
|
||||
[build-system]
|
||||
requires = ["setuptools>=68"]
|
||||
build-backend = "setuptools.backends.legacy:build"
|
||||
|
||||
[project]
|
||||
name = "bitreport-errors"
|
||||
version = "1.0.0"
|
||||
description = "Lightweight error reporting client for errors.bitreport.pt"
|
||||
readme = "README.md"
|
||||
requires-python = ">=3.8"
|
||||
license = { text = "MIT" }
|
||||
keywords = ["error-reporting", "monitoring", "bitreport"]
|
||||
classifiers = [
|
||||
"Programming Language :: Python :: 3",
|
||||
"Programming Language :: Python :: 3.8",
|
||||
"Programming Language :: Python :: 3.9",
|
||||
"Programming Language :: Python :: 3.10",
|
||||
"Programming Language :: Python :: 3.11",
|
||||
"Programming Language :: Python :: 3.12",
|
||||
"License :: OSI Approved :: MIT License",
|
||||
"Operating System :: OS Independent",
|
||||
"Topic :: System :: Monitoring",
|
||||
]
|
||||
|
||||
[project.urls]
|
||||
Homepage = "https://errors.bitreport.pt"
|
||||
|
||||
[tool.setuptools]
|
||||
py-modules = ["error_reporter"]
|
||||
|
||||
[tool.pytest.ini_options]
|
||||
testpaths = ["tests"]
|
||||
@@ -0,0 +1,164 @@
|
||||
"""Unit tests for error_reporter.py — uses an embedded HTTP server, no mocks."""
|
||||
|
||||
import json
|
||||
import threading
|
||||
import time
|
||||
import unittest
|
||||
from http.server import BaseHTTPRequestHandler, HTTPServer
|
||||
|
||||
import error_reporter as er
|
||||
|
||||
|
||||
class _CapturingHandler(BaseHTTPRequestHandler):
|
||||
bodies: list = []
|
||||
|
||||
def do_POST(self):
|
||||
length = int(self.headers.get("Content-Length", 0))
|
||||
body = self.rfile.read(length)
|
||||
_CapturingHandler.bodies.append(json.loads(body))
|
||||
self.send_response(200)
|
||||
self.end_headers()
|
||||
|
||||
def log_message(self, *_):
|
||||
pass
|
||||
|
||||
|
||||
class TestErrorReporter(unittest.TestCase):
|
||||
@classmethod
|
||||
def setUpClass(cls):
|
||||
cls.server = HTTPServer(("127.0.0.1", 0), _CapturingHandler)
|
||||
cls.server_thread = threading.Thread(target=cls.server.serve_forever, daemon=True)
|
||||
cls.server_thread.start()
|
||||
cls.port = cls.server.server_address[1]
|
||||
|
||||
@classmethod
|
||||
def tearDownClass(cls):
|
||||
cls.server.shutdown()
|
||||
|
||||
def setUp(self):
|
||||
_CapturingHandler.bodies = []
|
||||
er._token = "test-token"
|
||||
er._endpoint = f"http://127.0.0.1:{self.port}"
|
||||
er._disabled = False
|
||||
er._project_name = ""
|
||||
er._project_slug = ""
|
||||
er._gitea_repo = ""
|
||||
with er._lock:
|
||||
er._queue.clear()
|
||||
if er._flush_timer is not None:
|
||||
er._flush_timer.cancel()
|
||||
er._flush_timer = None
|
||||
|
||||
# --- report_error ---
|
||||
|
||||
def test_report_error_sends_event(self):
|
||||
try:
|
||||
raise ValueError("boom")
|
||||
except ValueError as exc:
|
||||
er.report_error(exc)
|
||||
er.flush()
|
||||
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 1)
|
||||
events = _CapturingHandler.bodies[0]["events"]
|
||||
self.assertEqual(len(events), 1)
|
||||
ev = events[0]
|
||||
self.assertEqual(ev["schema_version"], 1)
|
||||
self.assertEqual(ev["level"], "error")
|
||||
self.assertEqual(ev["message"], "boom")
|
||||
self.assertIn("stacktrace", ev)
|
||||
self.assertEqual(ev["context"]["error_type"], "ValueError")
|
||||
|
||||
def test_report_error_extracts_file_line(self):
|
||||
try:
|
||||
raise RuntimeError("loc test")
|
||||
except RuntimeError as exc:
|
||||
er.report_error(exc)
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertIn("file_path", ctx)
|
||||
self.assertIn("line_number", ctx)
|
||||
self.assertIsInstance(ctx["line_number"], int)
|
||||
|
||||
def test_report_error_with_extra_context(self):
|
||||
try:
|
||||
raise KeyError("key")
|
||||
except KeyError as exc:
|
||||
er.report_error(exc, {"request_id": "abc123"})
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertEqual(ctx["request_id"], "abc123")
|
||||
|
||||
# --- report_message ---
|
||||
|
||||
def test_report_message_default_level(self):
|
||||
er.report_message("something bad")
|
||||
er.flush()
|
||||
ev = _CapturingHandler.bodies[0]["events"][0]
|
||||
self.assertEqual(ev["level"], "error")
|
||||
self.assertEqual(ev["message"], "something bad")
|
||||
|
||||
def test_report_message_warning(self):
|
||||
er.report_message("heads up", "warning", {"foo": "bar"})
|
||||
er.flush()
|
||||
ev = _CapturingHandler.bodies[0]["events"][0]
|
||||
self.assertEqual(ev["level"], "warning")
|
||||
self.assertEqual(ev["context"]["foo"], "bar")
|
||||
|
||||
# --- project context ---
|
||||
|
||||
def test_project_fields_added(self):
|
||||
er._project_name = "My App"
|
||||
er._project_slug = "my-app"
|
||||
er._gitea_repo = "org/my-app"
|
||||
er.report_message("test")
|
||||
er.flush()
|
||||
ctx = _CapturingHandler.bodies[0]["events"][0]["context"]
|
||||
self.assertEqual(ctx["project_name"], "My App")
|
||||
self.assertEqual(ctx["project_slug"], "my-app")
|
||||
self.assertEqual(ctx["gitea_repo"], "org/my-app")
|
||||
|
||||
# --- disabled / no token ---
|
||||
|
||||
def test_disabled_skips(self):
|
||||
er._disabled = True
|
||||
er.report_message("nope")
|
||||
er.flush()
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 0)
|
||||
|
||||
def test_no_token_skips(self):
|
||||
er._token = ""
|
||||
er.report_message("nope")
|
||||
er.flush()
|
||||
self.assertEqual(len(_CapturingHandler.bodies), 0)
|
||||
|
||||
# --- batching ---
|
||||
|
||||
def test_batch_flushed_on_size(self):
|
||||
for i in range(25):
|
||||
er.report_message(f"msg {i}")
|
||||
time.sleep(0.2) # allow background send thread to complete
|
||||
self.assertGreaterEqual(len(_CapturingHandler.bodies), 1)
|
||||
total_events = sum(len(b["events"]) for b in _CapturingHandler.bodies)
|
||||
self.assertEqual(total_events, 25)
|
||||
|
||||
def test_authorization_header(self):
|
||||
# Capture headers by extending the server handler temporarily
|
||||
captured_headers = {}
|
||||
|
||||
class HeaderHandler(_CapturingHandler):
|
||||
def do_POST(self):
|
||||
captured_headers["auth"] = self.headers.get("Authorization")
|
||||
super().do_POST()
|
||||
|
||||
self.server.RequestHandlerClass = HeaderHandler
|
||||
try:
|
||||
er.report_message("check auth")
|
||||
er.flush()
|
||||
finally:
|
||||
self.server.RequestHandlerClass = _CapturingHandler
|
||||
|
||||
self.assertEqual(captured_headers.get("auth"), "Bearer test-token")
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
Reference in new issue
Block a user