auditrail

package module
v0.0.4 Latest Latest
Warning

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

Go to latest
Published: Nov 7, 2024 License: MIT Imports: 15 Imported by: 0

README

Go Auditrail

go test golangci-lint

Provides a simple interface for logging audit events in Go with support for multiple backends such as file, Elasticsearch, and more.

Installation

go get github.com/auditrail/go-auditrail

Usage

package main

import (
    "context"
    "fmt"
    "os"

    "github.com/botchris/go-auditrail"
)

func main() {
    // Create a new client
    client := auditrail.NewFileLogger(os.Stdout)

    // Log a message
    entry := auditrail.NewEntry("john", "order.deleted", "ordersService")

    if err := client.Log(context.TODO(), entry); err != nil {
        fmt.Println(err.Error())
    }

}

Documentation

Overview

Package auditrail provides basic audit log functionality and definitions for logging actions and events.

Index

Constants

This section is empty.

Variables

View Source
var DefaultExponentialBackoffConfig = ExponentialBackoffConfig{
	Base:   time.Second,
	Factor: time.Second,
	Max:    20 * time.Second,
}

DefaultExponentialBackoffConfig provides a default configuration for exponential backoff.

View Source
var ErrTrailClosed = fmt.Errorf("trail is closed")

ErrTrailClosed is returned when the queue is closed.

Functions

This section is empty.

Types

type DropHandlerFunc

type DropHandlerFunc func(*Entry, error)

DropHandlerFunc is a function that will be called when a message is dropped from the queue.

type Entry

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

Entry represents an audit log event.

This struct is not safe for concurrent write access.

func NewEntry

func NewEntry(actor, action, module string) *Entry

NewEntry creates a new log entry with the given actor, action, and module.

By default, the following fields are set:

  • The time of the event is set to the current time, use Entry.WithOccurredAt to override it to a different value.
  • The IdempotencyID is set to randomly generated value, use Entry.WithIdempotency to override it to a different value.

func (*Entry) AppendDetails

func (e *Entry) AppendDetails(key string, value interface{}) *Entry

AppendDetails adds a key-value pair to the details of the event.

func (*Entry) GetAction added in v0.0.4

func (e *Entry) GetAction() string

GetAction returns the action of the event.

func (*Entry) GetActor added in v0.0.4

func (e *Entry) GetActor() string

GetActor returns the actor of the event.

func (*Entry) GetAuthMethod added in v0.0.4

func (e *Entry) GetAuthMethod() string

GetAuthMethod returns the authentication method of the event.

func (*Entry) GetCausationID added in v0.0.4

func (e *Entry) GetCausationID() string

GetCausationID returns the causation ID of the event.

func (*Entry) GetCorrelationID added in v0.0.4

func (e *Entry) GetCorrelationID() string

GetCorrelationID returns the correlation ID of the event.

func (*Entry) GetDetails added in v0.0.4

func (e *Entry) GetDetails() map[string]interface{}

GetDetails returns the details of the event.

func (*Entry) GetIdempotencyID added in v0.0.4

func (e *Entry) GetIdempotencyID() string

GetIdempotencyID returns the idempotency ID of the event.

func (*Entry) GetModule added in v0.0.4

func (e *Entry) GetModule() string

GetModule returns the module of the event.

func (*Entry) GetOccurredAt added in v0.0.4

func (e *Entry) GetOccurredAt() time.Time

GetOccurredAt returns the time of the event.

func (*Entry) MarshalJSON added in v0.0.4

func (e *Entry) MarshalJSON() ([]byte, error)

MarshalJSON marshals the log entry to JSON.

func (*Entry) UnmarshalJSON added in v0.0.4

func (e *Entry) UnmarshalJSON(data []byte) error

UnmarshalJSON unmarshals the log entry from JSON.

func (*Entry) WithAuthMethod

func (e *Entry) WithAuthMethod(method string) *Entry

WithAuthMethod sets the authentication method of the event.

func (*Entry) WithCausation

func (e *Entry) WithCausation(causationID string) *Entry

WithCausation sets the causation ID of the event.

func (*Entry) WithCorrelation

func (e *Entry) WithCorrelation(correlationID string) *Entry

WithCorrelation sets the correlation ID of the event.

func (*Entry) WithIdempotency

func (e *Entry) WithIdempotency(idempotencyID string) *Entry

WithIdempotency sets the idempotency ID of the event.

func (*Entry) WithOccurredAt

func (e *Entry) WithOccurredAt(when time.Time) *Entry

WithOccurredAt overrides the time of the event with the given time.

type ExponentialBackoffConfig

type ExponentialBackoffConfig struct {
	// Base is the minimum bound for backing off after failure.
	Base time.Duration

	// Factor sets the amount of time by which the backoff grows with each
	// failure.
	Factor time.Duration

	// Max is the absolute maximum bound for a single backoff.
	Max time.Duration
}

ExponentialBackoffConfig configures backoff parameters.

Note that these parameters operate on the upper bound for choosing a random value. For example, at Base=1s, a random value in [0,1s) will be chosen for the backoff value.

type KinesisAPI

type KinesisAPI interface {
	PutRecord(ctx context.Context, params *kinesis.PutRecordInput, optFns ...func(*kinesis.Options)) (*kinesis.PutRecordOutput, error)
}

KinesisAPI captures the kinesis client part that we need.

type Logger

type Logger interface {
	// Log writes the given log entry to the audit log, returning an error
	// indicates that the log entry could not be written and should be retried.
	Log(context.Context, *Entry) error

	// Close closes logger and releases any resources.
	Close() error

	// Closed returns a channel that is closed when the logger is closed.
	Closed() <-chan struct{}

	// IsClosed returns true if the logger is closed.
	IsClosed() bool
}

Logger trail logger to which audit logs are written.

func NewDiscardLogger

func NewDiscardLogger() Logger

NewDiscardLogger returns a logger that discards all log entries.

func NewElasticLogger

func NewElasticLogger(index string, client *elasticsearch.Client) Logger

NewElasticLogger creates a new ElasticSearch logger.

func NewFileLogger

func NewFileLogger(fd *os.File) (Logger, error)

NewFileLogger builds a new logger that writes log entries to the given file descriptor.

The file descriptor must be writable. If it is not, an error will be returned. You can use os.Stdout or os.Stderr as file descriptors.

The file descriptor must be closed by the caller.

func NewFilePathLogger

func NewFilePathLogger(path string) (Logger, error)

NewFilePathLogger builds a new logger that writes log entries to a file at the given path.

If the file does not exist, it will be created.

func NewKinesisLogger

func NewKinesisLogger(client KinesisAPI, streamName string) (Logger, error)

NewKinesisLogger builds a new logger that writes log entries to a Kinesis stream as JSON objects separated by newlines.

func NewQueue

func NewQueue(dst Logger, options ...QueueOption) Logger

NewQueue builds a new logger queue which provides a buffer for entries to be processed asynchronously. See options for configuration.

func NewRetryer

func NewRetryer(dst Logger, opts ...RetryerOption) Logger

NewRetryer creates a new retryer that will retry failed log writes using the provided strategy.

type MemoryLogger

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

MemoryLogger is a test spy that records all the logs it receives for later inspection. Useful for testing.

This logger is safe for concurrent use and can be shared across multiple goroutines.

func NewMemoryLogger

func NewMemoryLogger() *MemoryLogger

NewMemoryLogger creates a new MemoryLogger.

func (*MemoryLogger) Close

func (s *MemoryLogger) Close() error

func (*MemoryLogger) Closed

func (s *MemoryLogger) Closed() <-chan struct{}

func (*MemoryLogger) Flush

func (s *MemoryLogger) Flush()

Flush clears all the logs recorded.

func (*MemoryLogger) Has

func (s *MemoryLogger) Has(idempotencyID ...string) bool

Has whether the logger has recorded all the logs with the given idempotency IDs.

func (*MemoryLogger) IsClosed

func (s *MemoryLogger) IsClosed() bool

func (*MemoryLogger) Log

func (s *MemoryLogger) Log(_ context.Context, event *Entry) error

Log records the log event.

func (*MemoryLogger) Size

func (s *MemoryLogger) Size() int

Size returns the number of logs recorded.

func (*MemoryLogger) Trail

func (s *MemoryLogger) Trail() []*Entry

Trail returns all the logs recorded.

type QueueOption

type QueueOption func(options *queueOptions)

QueueOption is a function that configures a queue.

func WithQueueDropHandler

func WithQueueDropHandler(handler DropHandlerFunc) QueueOption

WithQueueDropHandler sets a function that will be called when a message is dropped. The function is called with the dropped message and the error that caused the drop.

func WithQueueThroughput

func WithQueueThroughput(throughput int) QueueOption

WithQueueThroughput controls the number of concurrent workers that will process messages from the queue. If throughput is less than or equal to zero, it will be set to 1.

func WithQueueTimeout

func WithQueueTimeout(timeout time.Duration) QueueOption

WithQueueTimeout controls the maximum amount of time a worker will wait for the target logger to process a message. If the timeout is exceeded, the message will be dropped. If the timeout is less than or equal to zero, it will be set to 3 seconds.

type RetryStrategy

type RetryStrategy interface {
	// Proceed is called before every message send. If proceed returns a
	// positive, non-zero integer, the retryer will back off by the provided
	// duration.
	//
	// A message is provided, by may be ignored.
	Proceed(*Entry) time.Duration

	// Failure reports a failure to the strategy. If this method returns true,
	// the message should be dropped.
	Failure(*Entry, error) bool

	// Success should be called when a message is sent successfully.
	Success(*Entry)
}

RetryStrategy defines a strategy for retrying trail writes.

All methods should be goroutine safe.

func NewBreakerStrategy

func NewBreakerStrategy(threshold int, backoff time.Duration) RetryStrategy

NewBreakerStrategy returns a breaker that will backoff after the threshold has been tripped. A Breaker is thread safe and may be shared by many goroutines.

func NewExponentialBackoff

func NewExponentialBackoff(config ExponentialBackoffConfig) RetryStrategy

NewExponentialBackoff returns an exponential backoff strategy with the desired config. If config is nil, the default is returned.

type RetryerOption

type RetryerOption func(options *retryer)

RetryerOption is a function that configures a retryer.

func WithRetryDropHandler

func WithRetryDropHandler(handler DropHandlerFunc) RetryerOption

WithRetryDropHandler configures the drop handler for the retryer. If handler is nil, a no-op handler is used.

func WithRetryStrategy

func WithRetryStrategy(strategy RetryStrategy) RetryerOption

WithRetryStrategy configures the retry strategy for the retryer. If strategy is nil, a default exponential backoff strategy is used.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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