txnlog

package
v0.1.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Mar 25, 2026 License: MIT Imports: 9 Imported by: 0

Documentation

Overview

Package txnlog provides centralized transaction logging for the DS ecosystem.

All DS apps use this package to write structured transaction logs to a shared CloudWatch log group for monitoring, alerting, and auditing.

Basic usage:

config := txnlog.Config{
    LogGroup: "/ds/ecosystem/transactions",
    AppID:    "dskanban",
    AppName:  "DS Projects",
    Env:      "prod",
}
logger, err := txnlog.New(config)
if err != nil {
    // Handle error - will fallback to local logging
}

// Store in context for request handling
ctx = txnlog.WithLogger(ctx, logger)

// Later, in request handler:
logger := txnlog.FromContext(ctx)
logger.SetRequest("POST", "/api/issues", "1700")
defer logger.Complete()

// ... handle request ...

logger.SetResponse(201, "Issue", 1234)

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func WithLogger

func WithLogger(ctx context.Context, l *Logger) context.Context

WithLogger returns a new context with the Logger stored in it.

Types

type AppInfo

type AppInfo struct {
	ID   string `json:"id"`
	Name string `json:"name"`
}

AppInfo identifies the application.

type CloudWatchClient

type CloudWatchClient interface {
	WriteLog(entry *LogEntry) error
}

CloudWatchClient defines the interface for writing logs to CloudWatch. This allows for mocking in tests.

func NewCloudWatchClient

func NewCloudWatchClient(sess *session.Session, logGroup, logStream string) (CloudWatchClient, error)

NewCloudWatchClient creates a new CloudWatch client. If sess is nil, it attempts to create a default session.

func NewLocalFallbackClient

func NewLocalFallbackClient() CloudWatchClient

NewLocalFallbackClient creates a client that writes to local log.

func NewNoopClient

func NewNoopClient() CloudWatchClient

NewNoopClient creates a client that discards logs.

type Config

type Config struct {
	// LogGroup is the CloudWatch log group name (e.g., "/ds/ecosystem/transactions")
	LogGroup string

	// AppID is the application identifier (e.g., "dskanban")
	AppID string

	// AppName is the human-readable application name (e.g., "DS Projects")
	AppName string

	// Env is the environment (e.g., "prod", "dev", "staging")
	Env string

	// LambdaID is the Lambda function identifier (optional, auto-detected from AWS_LAMBDA_FUNCTION_NAME)
	LambdaID string

	// LambdaName is the Lambda function display name (optional)
	LambdaName string

	// Session is an optional AWS session. If nil, a default session is created.
	Session *session.Session

	// Client is an optional CloudWatch client. If set, Session is ignored.
	// Useful for testing with mock clients.
	Client CloudWatchClient

	// LocalFallback determines behavior when CloudWatch is unavailable.
	// If true (default), logs to stdout instead of failing.
	LocalFallback bool
}

Config holds configuration for the transaction logger.

type LambdaInfo

type LambdaInfo struct {
	ID   string `json:"id,omitempty"`
	Name string `json:"name,omitempty"`
}

LambdaInfo identifies the Lambda function (if applicable).

type LogEntry

type LogEntry struct {
	Version       int           `json:"v"`
	Timestamp     time.Time     `json:"ts"`
	App           AppInfo       `json:"app"`
	Lambda        *LambdaInfo   `json:"lambda,omitempty"`
	Env           string        `json:"env"`
	SessionID     string        `json:"session_id,omitempty"`
	CorrelationID string        `json:"correlation_id,omitempty"`
	TenantID      string        `json:"tenant_id,omitempty"`
	UserIDHash    string        `json:"user_id_hash,omitempty"`
	Request       RequestInfo   `json:"request"`
	Response      *ResponseInfo `json:"response,omitempty"`
	Perf          *PerfInfo     `json:"perf,omitempty"`
	Source        *SourceInfo   `json:"source,omitempty"`
}

LogEntry represents a single transaction log entry (schema v1). Optional fields use omitempty to reduce log size. Pointer types are used for optional struct fields to enable proper omitempty behavior.

func (*LogEntry) IsEmpty

func (e *LogEntry) IsEmpty() bool

IsEmpty returns true if the LogEntry has no meaningful data set.

type Logger

type Logger struct {
	// contains filtered or unexported fields
}

Logger handles transaction logging.

func FromContext

func FromContext(ctx context.Context) *Logger

FromContext extracts the Logger from the context. Returns nil if no Logger is present.

func MustFromContext

func MustFromContext(ctx context.Context) *Logger

MustFromContext extracts the Logger from the context. Panics if no Logger is present. Use only when a Logger is guaranteed.

func New

func New(config Config) (*Logger, error)

New creates a new Logger with the given configuration. If CloudWatch is unavailable and LocalFallback is true (default), it falls back to local logging.

func NewWithClient

func NewWithClient(config Config, client CloudWatchClient) *Logger

NewWithClient creates a Logger with a specific CloudWatch client. Useful for testing or custom implementations.

func (*Logger) Clone

func (l *Logger) Clone() *Logger

Clone creates a new Logger with the same config but fresh entry. Useful for creating per-request loggers from a shared config.

func (*Logger) Complete

func (l *Logger) Complete()

Complete calculates duration and writes the log entry. This should be called at the end of request processing, typically via defer.

func (*Logger) Entry

func (l *Logger) Entry() *LogEntry

Entry returns the current log entry for inspection or modification.

func (*Logger) SetColdStart

func (l *Logger) SetColdStart(coldStart bool)

SetColdStart marks this as a cold start request.

func (*Logger) SetEventType

func (l *Logger) SetEventType(eventType string)

SetEventType sets the event type for non-HTTP transactions.

func (*Logger) SetPerf

func (l *Logger) SetPerf(coldStart bool, initMs, dbQueryMs, externalMs int64)

SetPerf sets performance metrics.

func (*Logger) SetRequest

func (l *Logger) SetRequest(method, path, resourceID string)

SetRequest sets request information.

func (*Logger) SetResponse

func (l *Logger) SetResponse(status int, dataType string, bytes int)

SetResponse sets response information.

func (*Logger) SetSession

func (l *Logger) SetSession(sessionID, correlationID string)

SetSession sets session and correlation IDs.

func (*Logger) SetSource

func (l *Logger) SetSource(ip, userAgent, referer string)

SetSource sets source information (IP, user agent, etc.).

func (*Logger) SetTenant

func (l *Logger) SetTenant(tenantID string)

SetTenant sets tenant information.

func (*Logger) SetUser

func (l *Logger) SetUser(userIDHash string)

SetUser sets user information (hashed).

type PerfInfo

type PerfInfo struct {
	ColdStart  bool  `json:"cold_start,omitempty"`
	InitMs     int64 `json:"init_ms,omitempty"`
	DBQueryMs  int64 `json:"db_query_ms,omitempty"`
	ExternalMs int64 `json:"external_ms,omitempty"`
}

PerfInfo contains performance metrics.

type RequestInfo

type RequestInfo struct {
	Method     string `json:"method,omitempty"`
	Path       string `json:"path,omitempty"`
	ResourceID string `json:"resource_id,omitempty"`
	EventType  string `json:"event_type,omitempty"`
}

RequestInfo describes the incoming request.

type ResponseInfo

type ResponseInfo struct {
	Status     int    `json:"status,omitempty"`
	Type       string `json:"type,omitempty"`
	Bytes      int    `json:"bytes,omitempty"`
	DurationMs int64  `json:"duration_ms,omitempty"`
}

ResponseInfo describes the response.

type SourceInfo

type SourceInfo struct {
	IP        string `json:"ip,omitempty"`
	UserAgent string `json:"user_agent,omitempty"`
	Referer   string `json:"referer,omitempty"`
}

SourceInfo contains optional source context.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL