Guides / Platforms & Tools

Real-Time Event Logging from a Go Backend

4 min read·Platforms & Tools

Setup: A Minimal LogIt Client

go
// internal/logit/client.go
package logit

import (
	"bytes"
	"context"
	"encoding/json"
	"fmt"
	"net/http"
	"os"
	"time"
)

const endpoint = "https://api.logit.now/api/ingest"

type Event struct {
	Channel     string            `json:"channel"`
	Event       string            `json:"event"`
	Description string            `json:"description"`
	Icon        string            `json:"icon,omitempty"`
	Notify      bool              `json:"notify"`
	Tags        map[string]string `json:"tags,omitempty"`
	Metadata    map[string]any    `json:"metadata,omitempty"`
}

var client = &http.Client{Timeout: 5 * time.Second}

func Log(ctx context.Context, e Event) error {
	body, err := json.Marshal(e)
	if err != nil {
		return err
	}

	req, err := http.NewRequestWithContext(ctx, http.MethodPost, endpoint, bytes.NewReader(body))
	if err != nil {
		return err
	}
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer "+os.Getenv("LOGIT_API_KEY"))

	resp, err := client.Do(req)
	if err != nil {
		return err
	}
	defer resp.Body.Close()

	if resp.StatusCode >= 400 {
		return fmt.Errorf("logit: unexpected status %d", resp.StatusCode)
	}
	return nil
}

// Fire logs an event without blocking the caller.
func Fire(e Event) {
	go func() {
		ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
		defer cancel()
		if err := Log(ctx, e); err != nil {
			fmt.Fprintf(os.Stderr, "logit: %v\n", err)
		}
	}()
}

Log a Signup

go
// handlers/auth.go
import "yourapp/internal/logit"

func handleSignup(w http.ResponseWriter, r *http.Request) {
	user, err := createUser(r.Context(), r.Body)
	if err != nil {
		http.Error(w, err.Error(), http.StatusInternalServerError)
		return
	}

	logit.Fire(logit.Event{
		Channel:     "signups",
		Event:       "New user signed up",
		Description: user.Email,
		Icon:        "👤",
		Notify:      true,
		Tags:        map[string]string{"plan": user.Plan, "source": r.URL.Query().Get("utm_source")},
		Metadata:    map[string]any{"userId": user.ID, "email": user.Email},
	})

	w.WriteHeader(http.StatusCreated)
	json.NewEncoder(w).Encode(user)
}

Log a Payment Failure

go
// services/billing.go
func chargeCustomer(ctx context.Context, customerID string, amount int64, currency string) error {
	_, err := stripe.ChargeCustomer(customerID, amount, currency)
	if err != nil {
		logit.Fire(logit.Event{
			Channel:     "payments",
			Event:       "Payment failed",
			Description: fmt.Sprintf("customer %s — %v", customerID, err),
			Icon:        "❌",
			Notify:      false,
			Tags:        map[string]string{"currency": currency},
			Metadata:    map[string]any{"customerId": customerID, "amount": amount, "error": err.Error()},
		})
		return err
	}
	return nil
}

Tips

  • Use Fire() (goroutine-based) for non-blocking logging in HTTP handlers.
  • Use Log(ctx, e) when you need to know if logging succeeded (e.g. in a critical audit path).
  • Set LOGIT_API_KEY via environment variable — never hardcode it.

Try LogIt free

7-day trial. No credit card required.

Start free