LogFlux Go SDK

Go Logo

The official Go SDK for LogFlux. Send logs, metrics, traces, events, and audit entries directly to the LogFlux cloud with end-to-end encryption. The server never sees your plaintext data.

GitHub Repository ยท Release Notes

Key Features

  • End-to-end encryption – AES-256-GCM with RSA key exchange
  • 7 entry types – Log, Metric, Trace, Event, Audit, Telemetry, TelemetryManaged
  • Multipart binary transport – 33% less overhead than JSON + base64
  • Async by default – Non-blocking queue with background workers
  • Breadcrumbs – Automatic trail of recent events attached to error captures
  • Distributed tracing – Spans, child spans, HTTP context propagation
  • Scopes – Per-request context isolation
  • Failsafe – SDK errors never crash your application

Framework Middleware

Separate modules for automatic request tracing:

  • Gingo get github.com/logflux-io/logflux-go-sdk/v3/gin
  • Echogo get github.com/logflux-io/logflux-go-sdk/v3/echo
  • Fibergo get github.com/logflux-io/logflux-go-sdk/v3/fiber
  • Chigo get github.com/logflux-io/logflux-go-sdk/v3/chi
  • net/http – Built-in TracingMiddleware (no extra module)

Logger Adapters

Drop-in hooks for popular Go logging libraries:

  • logrus – Structured logger adapter
  • zap – High-performance logger integration
  • zerolog – Zero allocation JSON logger
  • standard log – Built-in Go logger replacement

Installation

1
go get github.com/logflux-io/logflux-go-sdk/v3@v3.0.1

Quick Start

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package main

import (
    "log"
    "time"

    logflux "github.com/logflux-io/logflux-go-sdk/v3"
)

func main() {
    err := logflux.Init(logflux.Options{
        APIKey:      "eu-lf_your_api_key",
        Source:      "my-service",
        Environment: "production",
        Release:     "v1.2.3",
    })
    if err != nil {
        log.Fatal(err)
    }
    defer logflux.Close()
    defer logflux.Flush(2 * time.Second)

    logflux.Info("server started")
    logflux.Warnf("high latency: %dms", 500)
}

Entry Types

Log (Type 1)

Standard application logs with 8 severity levels.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
logflux.Debug("cache miss for key users:123")
logflux.Info("request processed")
logflux.Warn("deprecated API called")
logflux.Error("database connection failed")

// With attributes
logflux.Log(logflux.LogLevelError, "query timeout", logflux.Fields{
    "db.host":     "primary.db.internal",
    "duration_ms": "5023",
})

// Printf-style
logflux.Infof("user %s logged in from %s", userID, ipAddr)

Metric (Type 2)

Counters, gauges, and distributions.

1
2
3
4
5
6
7
8
logflux.Counter("http.requests.total", 1, logflux.Fields{
    "method": "GET",
    "status": "200",
})

logflux.Gauge("system.cpu.usage", 85.2, logflux.Fields{
    "host": "web-01",
})

Event (Type 4)

Discrete application events.

1
2
3
4
logflux.Event("user.signup", logflux.Fields{
    "user_id": "usr_987",
    "plan":    "starter",
})

Audit (Type 5)

Immutable audit trail with Object Lock storage (365-day retention).

1
2
3
4
logflux.Audit("record.deleted", "usr_456", "invoice", "inv_789", logflux.Fields{
    "reason": "customer_request",
    "ip":     "10.0.1.42",
})

Trace (Type 3)

Distributed tracing with span helpers.

1
2
3
4
5
span := logflux.StartSpan("http.server", "GET /api/users")
defer span.End()

dbSpan := span.StartChild("db.query", "SELECT * FROM users")
dbSpan.End()

Telemetry (Types 6 and 7)

Device and sensor data. Type 6 is end-to-end encrypted, type 7 is server-side encrypted.

Error Capture

Capture Go errors with automatic stack traces and breadcrumb trail.

1
2
3
4
5
6
7
8
9
if err := db.Query(ctx, sql); err != nil {
    logflux.CaptureError(err)

    // With extra context
    logflux.CaptureErrorWithAttrs(err, logflux.Fields{
        "sql":     sql,
        "db.host": "primary",
    })
}

Error chain unwrapping: wrapped errors (fmt.Errorf("...: %w", err)) are captured up to 10 levels deep.

Breadcrumbs record a trail of events leading up to an error. They are automatically added for log and event calls, and attached to CaptureError.

1
2
3
4
5
6
7
8
logflux.Info("loading config")          // auto breadcrumb
logflux.Event("user.login", nil)        // auto breadcrumb

logflux.AddBreadcrumb("http", "GET /api/users", logflux.Fields{
    "status": "200",
})

logflux.CaptureError(err)  // includes breadcrumb trail

Scopes

Per-request context isolation. Attributes set on a scope are merged into every entry.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
logflux.WithScope(func(scope *logflux.Scope) {
    scope.SetUser("usr_456")
    scope.SetRequest("GET", "/api/users", "req_abc123")
    scope.SetAttribute("tenant", "acme-corp")

    scope.Info("processing request")

    if err != nil {
        scope.CaptureError(err)
    }
})

Trace Context Propagation

Propagate trace context across services via HTTP headers.

1
2
3
4
5
6
// Client: inject into outgoing request
logflux.InjectTraceContext(outgoingReq, span)

// Server: continue from incoming request
span := logflux.ContinueFromRequest(req, "http.server", "GET /api")
defer span.End()

Framework Middleware

Auto-creates spans for every HTTP request with panic recovery.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
// Gin
import logfluxgin "github.com/logflux-io/logflux-go-sdk/v3/gin"
r.Use(logfluxgin.Middleware())

// Echo
import logfluxecho "github.com/logflux-io/logflux-go-sdk/v3/echo"
e.Use(logfluxecho.Middleware())

// Fiber
import logfluxfiber "github.com/logflux-io/logflux-go-sdk/v3/fiber"
app.Use(logfluxfiber.Middleware())

// Chi
import logfluxchi "github.com/logflux-io/logflux-go-sdk/v3/chi"
r.Use(logfluxchi.Middleware)

// stdlib net/http
handler := logflux.TracingMiddleware(mux)

Configuration

Init Options

OptionTypeDefaultDescription
APIKeystringrequiredAPI key (<region>-lf_<key>)
SourcestringNodeService name
EnvironmentstringAttached to meta.environment
ReleasestringAttached to meta.release
QueueSizeint1000In-memory buffer capacity
BatchSizeint100Entries per HTTP request
WorkerCountint2Background goroutines
MaxRetriesint3Max retry attempts
SampleRatefloat641.00.0-1.0, send probability
MaxBreadcrumbsint100Ring buffer size
FailsafebooltrueNever crash host app
EnableCompressionbooltrueGzip before encryption

Environment Variables

All options can be set via LOGFLUX_* environment variables:

1
logflux.InitFromEnv("my-node")
VariableDescription
LOGFLUX_API_KEYAPI key (required)
LOGFLUX_ENVIRONMENTDeployment environment
LOGFLUX_NODEHost identifier
LOGFLUX_QUEUE_SIZEQueue capacity
LOGFLUX_BATCH_SIZEEntries per request
LOGFLUX_WORKER_COUNTBackground workers
LOGFLUX_ENABLE_COMPRESSIONGzip compression
LOGFLUX_DEBUGSDK diagnostic logging
LOGFLUX_KEY_PERSISTENCEEnable/disable key persistence
LOGFLUX_KEY_PERSISTENCE_PATHCustom directory for session files
LOGFLUX_KEY_ROTATION_DAYSRotate key after N days

Key Persistence

The SDK persists AES encryption keys to disk by default, reusing them across restarts instead of performing a new handshake each time. This reduces key proliferation in the database and speeds up initialization.

OptionTypeDefaultDescription
KeyPersistence*booltrue (nil = true)Enable/disable key persistence
KeyPersistencePathstring~/.logflux/sessions/Custom directory for session files
KeyRotationIntervaltime.Duration0 (never)Rotate key after this duration

Session files are stored at ~/.logflux/sessions/<hash>.json with 0600 permissions. If the cached key is rejected by the server (401/403), the SDK automatically re-handshakes and saves the new key.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
// Disable persistence (for ephemeral containers)
f := false
logflux.Init(logflux.Options{
    APIKey:         "eu-lf_your_key",
    KeyPersistence: &f,
})

// Custom path and 30-day rotation
logflux.Init(logflux.Options{
    APIKey:              "eu-lf_your_key",
    KeyPersistencePath:  "/var/lib/myapp/logflux/",
    KeyRotationInterval: 30 * 24 * time.Hour,
})

BeforeSend Hooks

Filter or modify entries before they are sent. Return nil to drop.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
logflux.Init(logflux.Options{
    BeforeSendLog: func(p *payload.Log) *payload.Log {
        if p.Level == logflux.LogLevelDebug {
            return nil  // drop debug logs
        }
        return p
    },
    BeforeSendAudit: func(p *payload.Audit) *payload.Audit {
        delete(p.Attributes, "ip")  // scrub PII
        return p
    },
})

Per-type hooks: BeforeSendLog, BeforeSendError, BeforeSendMetric, BeforeSendEvent, BeforeSendAudit, BeforeSendTrace, BeforeSendTelemetry.

Sampling

1
2
3
logflux.Init(logflux.Options{
    SampleRate: 0.1, // send 10% of entries
})

Audit entries (type 5) are never sampled.

Serverless (Lambda)

1
2
3
4
5
func handler(ctx context.Context, event events.APIGatewayProxyRequest) (Response, error) {
    defer logflux.Flush(2 * time.Second)
    logflux.Info("processing request")
    // ...
}

Security

  • Zero-knowledge: All payloads encrypted client-side with AES-256-GCM
  • RSA key exchange: AES keys negotiated via RSA-2048 OAEP handshake
  • Key safety: AES keys zeroed from memory on Close()
  • Bounded reads: All HTTP responses size-limited
  • Failsafe: SDK errors never crash the host application

Requirements

  • Go 1.23 or later
  • LogFlux account with API key

License

Elastic License 2.0 (ELv2) – free for all use except offering as a hosted or managed service to third parties.

Support

Disclaimer

The Go logo and trademarks are the property of Google LLC. LogFlux is not affiliated with, endorsed by, or sponsored by Google LLC. The Go logo is used solely for identification purposes to indicate compatibility and integration capabilities.