log

package module
v0.10.0 Latest Latest
Warning

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

Go to latest
Published: Nov 15, 2026 License: MIT Imports: 21 Imported by: 0

README

gas/log

Test Go Reference Go Version License

Part of the Gas monorepo · Documentation · All modules

Structured logging for the Gas framework: a log/slog backend, a zerolog backend, and batched shipping of records over HTTP, with an OTLP/JSON marshaler included.

Implements gas.Logger; ShippingLogger is also a gas.Service.

go get github.com/gasmod/gas/log
gas.WithSingletonService[gas.Logger](gaslog.NewSlogLogger()),

The constructors take no dependencies from the container. NewShippingLogger takes the endpoint and a Marshaler, such as gaslog.NewOTLPMarshaler().

Package Provides
github.com/gasmod/gas/log NewSlogLogger, NewShippingLogger, NewShippingHandler, NewOTLPMarshaler; standard library only
github.com/gasmod/gas/log/zerolog New, a logger over rs/zerolog
github.com/gasmod/gas/log/logtest RecordingLogger, a gas.Logger that records events for tests

Documentation

The full documentation is on the docs site. This README is deliberately a signpost: keeping a second copy here is how the docs drifted before.

License

MIT

Documentation

Overview

Package log provides gas.Logger implementations over log/slog, and ships log records in batches to an HTTP endpoint, encoded by a Marshaler such as the OTLP/JSON OTLPMarshaler.

It imports no third-party package: only the standard library and github.com/gasmod/gas. Two other packages complete it:

  • github.com/gasmod/gas/log/zerolog provides a gas.Logger over zerolog.
  • github.com/gasmod/gas/log/logtest provides a recording gas.Logger for tests.

Usage

In an app, the container builds the logger from NewShippingLogger, calls its Init, and its Close at shutdown. By hand:

logger, err := log.NewShippingLogger(
	"https://collector.example:4318/v1/logs",
	log.NewOTLPMarshaler(log.WithServiceName("shop")),
	log.WithHeader("Authorization", "Bearer "+token),
)()
if err != nil {
	return err
}
if err := logger.Init(ctx); err != nil {
	return err
}
defer logger.Close(ctx)

logger.Info("order placed").Str("order", "A-1").Int("items", 3).Send()

The event is written as JSON to standard error at once. It is posted to the endpoint as an OTLP logs request with the `order` and `items` attributes, at the latest by Close.

Backends

There are three backends:

  • SlogLogger, from NewSlogLogger, writes to a *slog.Logger, slog.Default() unless WithSlogLogger gives one. Trace is LevelTrace, below slog.LevelDebug, so a handler can filter it apart from Debug; Debug, Info, Warn and Error are slog's levels. Its Flush does nothing, since it buffers nothing.
  • ShippingLogger, from NewShippingLogger, is a SlogLogger over a ShippingHandler, with the same levels. Its Flush posts what is queued.
  • The zerolog backend writes each event at zerolog's own level, Trace included.

The ShippingHandler, from NewShippingHandler, is the same pipeline as a plain slog.Handler, for an app that logs with log/slog directly.

The constructors of the loggers return a constructor in the shape the gas container expects, func() (*T, error). Options only record their value. The constructor checks them and fails with an error, never later.

Events

A logger's Trace, Debug, Info, Warn and Error start an event. Its field methods add fields, and Send writes it. An event belongs to the goroutine that started it and is not safe for concurrent use.

An event is sent at most once. Every method called after Send, Send included, does nothing: it neither writes again nor reaches another event. An event at a level the logger does not enable is a shared no-op event, so its fields cost nothing.

A source or caller that the backend adds is the line that called Send: slog's AddSource reports it, as does zerolog's Caller.

Field values are taken on the caller's goroutine, by the time Send returns:

  • A scalar is taken when its method is called.
  • A value given to Any is held as it is until Send by slog, and encoded at once by zerolog. So a map or a slice given to Any must not change before Send returns.
  • Nothing reads a field value after Send returns: the shipping handler encodes the values it queues before Handle returns, as described under Records.

A logger from With carries the fields added to its context, before each event's own; its parent is unchanged. Calling Logger again on the same context, after adding more fields, gives a second logger with them all; the first is unchanged. A key given twice is written twice, as the backend writes duplicates.

Send of a SlogLogger hands the record to the handler with the caller's program counter. It discards the handler's error, as slog.Logger does: gas.LogEvent's Send has no result. A ShippingHandler reports the error of its local handler, as described under Error reports.

Encodings by backend

Some fields are encoded differently by each backend:

  • Err with a nil error: slog writes the key with a null value, zerolog leaves the field out, shipping sends the key with the empty value.
  • Any with an error: all write its Error text. zerolog treats it as Err.
  • Duration: slog writes a slog duration, which slog's JSON handler writes in nanoseconds; zerolog writes zerolog's Dur, in zerolog.DurationFieldUnit, milliseconds unless changed; shipping sends its String text, such as `1.5s`.
  • Any with other values: slog writes them as the handler does; zerolog writes their JSON; shipping encodes them as described under Records.

Shipping

A ShippingHandler handles each record in two steps:

  1. It writes the record to its local handler, when that enables the record's level.
  2. It queues a Record of it for shipping, when the level is at least the shipping level: WithLevel, DefaultShippingLevel unless given.

The local handler is WithLocalHandler's, or a slog.JSONHandler on standard error at the shipping level. WithoutLocalHandler turns it off.

Records

The Record is built in Handle, on the logging goroutine, so nothing the caller holds is read later. Its attributes are the handler's, from WithAttrs, then the record's, flattened:

  • A group's attributes take its key joined to theirs by `.`.
  • A group with an empty key is inlined.
  • An empty group and an empty attribute are dropped.
  • LogValuers are resolved.

A value of kind slog.KindAny is encoded:

  • nil stays nil.
  • A []byte is copied.
  • An error becomes its Error text, and a fmt.Stringer its String text.
  • A value encoding/json encodes becomes its JSON text.
  • Anything else, such as a channel, a func, or a map, slice or pointer that refers to itself, becomes `!unencodable ` and the name of its type, such as `!unencodable map[string]interface {}`. Such a value is never formatted, so a cycle cannot overflow the stack.

A method that panics gives `<nil>` for a nil pointer, and otherwise `!PANIC: ` and the panic value, as slog's handlers write them. The time is kept as it is, zero included.

Batches

Records wait in a queue of at most WithQueueSize records, DefaultQueueSize unless given, and Handle never blocks on it. A goroutine of the sender posts them:

The queue and the batches are bounded by their count of records only: neither a record's size nor a request body's is bounded.

A batch is one request. The Marshaler encodes it, and the body is posted to the endpoint with the Content-Type the Marshaler names, then the headers given to WithHeader, which can replace it.

The Marshaler gets a batch it must not keep: the sender reuses its memory for the next one, and clears it after each post, so no record stays reachable from it.

A post runs on the sender goroutine, so a slow endpoint fills the queue. A post's context ends with the Flush or Close it belongs to. The HTTP client's timeout, DefaultHTTPTimeout for the default client, bounds it too.

The default client follows no redirect: a 3xx response is returned as it is, so the headers and the body never reach another URL, and the post fails with its status. A client given to WithHTTPClient is used as it is, redirect policy included.

The response body is read, up to 64 KiB, and discarded, so the connection is reused. A status outside 2xx is a failure. Delivery is best effort: a failed batch is not retried.

Dropped records

A record that is not delivered is dropped and counted. These are dropped:

  • A record logged when the queue is full, or while the sender is not running.
  • Every record of a batch the Marshaler fails or panics on, whose post fails, or whose response is not 2xx.
  • The records Close gives up on, as described under Flush and Close.

ShippingHandler.Dropped and ShippingLogger.Dropped return the count since the handler was made.

Flush and Close

ShippingHandler.Flush posts the records queued when it is called, in batches, and waits for them, within its context. It returns an error wrapping ErrNotDelivered:

  • When a post fails, with the number of records not delivered.
  • When its context ends first, with the number of records still queued or being posted, and the context's error.

When its context ends first, Flush drops nothing. The records it did not post stay queued for the next batch. A post its context cancels puts its batch back at the front of the queue, unless the queue has no room for it any more, in which case the batch is dropped. A Flush whose context has already ended posts nothing.

ShippingLogger.Flush, the Flush of gas.Logger, does the same within DefaultFlushTimeout, and reports its error. A logger from With flushes the same sender.

ShippingHandler.Close and ShippingLogger.Close stop accepting records, so a record logged after them is written locally and dropped for shipping. They then post what is queued, in batches, within their context. Close returns an error wrapping ErrNotDelivered:

  • When a post fails, with the number of records not delivered.
  • When the context ends first, with the number of records still queued or being posted, and the context's error. The post in flight is canceled, and those records are dropped.

Close returns without waiting for a post that ignores the cancellation, such as one whose Marshaler blocks. Close of a closed sender returns nil.

Starting the sender

NewShippingHandler starts the sender. NewShippingLogger does not: its Init starts it. A record logged before the first Init is written locally and dropped for shipping, as after Close.

Init after Close starts the sender again, so a ShippingLogger is restartable. The sender of the earlier Close may still run, because Close's context ended while a post went on, or because Close has not returned. Init then waits for it to stop, so two senders never post at once and Marshal is never called concurrently. When Init's context ends first, it returns an error wrapping ErrStillClosing and the context's error, and the sender is not started.

Each ShippingLogger is a gas.Service named by WithName, DefaultShippingName unless given. Two in one app need distinct names, or the container closes only one.

Error reports

Failures are reported to the error handler, WithErrorHandler. By default it writes the error and a newline to standard error, as os.Stderr was when the handler was made.

The error handler runs on a goroutine of its own, never on the logging goroutine or the sender's. So it may log through the same logger, and call Flush or Close, without a deadlock. A panic of the error handler is recovered and noted on standard error.

Reports are coalesced by class, the sentinel they wrap:

  • At most one report of a class is delivered per flush interval, the first at once.
  • The reports made meanwhile become one, the last error with the count, such as `(3 times)`, delivered when the interval has passed.
  • Reports made before the first is delivered join it.

An error handler that logs through the logger it reports for therefore makes at most one record per class per interval.

The reports:

Records dropped after Close, or because the context of a Flush or Close ended, are counted but not reported. Neither is a post that such a context canceled.

OTLP encoding

OTLPMarshaler encodes a batch as one OTLP/HTTP JSON logs request (Content-Type OTLPContentType). The request holds:

A log record has these fields:

  • `timeUnixNano`: the time in Unix nanoseconds, as a string, left out for a zero time, one before 1970, or one after 2262.
  • `severityNumber`: the floor of the level's band: TRACE (1) below slog.LevelDebug, DEBUG (5), INFO (9), WARN (13), ERROR (17).
  • `severityText`: `TRACE` for LevelTrace, else slog's name of the level, such as `INFO` or `DEBUG-2`.
  • `body`: the message, as `stringValue`.
  • `attributes`: the Record's attributes, flattened and encoded as a ShippingHandler does when the Record was built elsewhere.

An attribute's value is encoded by its type:

  • A string is `stringValue`.
  • An integer is `intValue`, a string, except a uint64 above the int64 range, which is the decimal `stringValue`.
  • A float is `doubleValue`, a number, or the string `NaN`, `Infinity` or `-Infinity`.
  • A bool is `boolValue`.
  • A []byte is `bytesValue`, in standard base64.
  • A duration is its String text, and a time its RFC 3339 text with nanoseconds, as `stringValue`.
  • nil is the empty value `{}`.

A record that fails to encode, because a method of one of its values panics, is sent as a record with its time and level and the body OTLPReplacedBody, and counted by OTLPMarshaler.Replaced. So one record cannot fail its batch.

Concurrency

The loggers, the ShippingHandler and the OTLPMarshaler are safe for concurrent use; events and the contexts from With are not.

A ShippingHandler queues under a read lock. Close takes the write lock to stop the sender, so no record enters a closing queue.

One goroutine per running sender posts the batches, and Marshal is called on it, one batch at a time. Init waits for the goroutine of the last Close to end, so there is never more than one. A Close whose context ended returns without waiting for the sender goroutine, which ends once its canceled posts return.

The error handler runs on a goroutine that exists only while a report waits.

Errors

The sentinel errors, to be tested with errors.Is:

  • ErrNilLogger: WithSlogLogger was given nil.
  • ErrNilMarshaler: a shipping constructor was given a nil Marshaler.
  • ErrInvalidEndpoint: the endpoint is not an absolute http or https URL.
  • ErrInvalidOption: a ShippingOption was given a value it does not accept. The constructor checks WithBatchSize, WithQueueSize, WithFlushInterval, WithHTTPClient, WithLevel, WithLocalHandler, WithErrorHandler, WithName and WithHeader, in this order, after the Marshaler and the endpoint. A WithHeader name must be a token, and its value must hold no control character but a horizontal tab, as RFC 9110 says; the error names neither.
  • ErrQueueFull, ErrNotRunning, ErrLocalHandler, ErrMarshal, ErrMarshalPanic, ErrPost, ErrStatus: reported to the error handler, as described under Error reports. ErrLocalHandler, ErrMarshal and ErrPost wrap the cause.
  • ErrNotDelivered: Flush or Close returned with records not delivered. It wraps the context's error when the context ended.
  • ErrStillClosing: Init's context ended while the sender of an earlier Close still ran. It wraps the context's error.

Every error starts with `gas/log: `.

No error names the endpoint's user info, path, query or fragment, or a header name or value. An error names the endpoint by its scheme and host only, such as `https://collector.example:4318`, and a parse error of the endpoint is replaced, not wrapped. The panic value of a Marshaler is left out of its report, since it can hold the records.

The errors, as returned or reported:

gas/log: logger is nil
gas/log: marshaler is nil
gas/log: invalid endpoint: must be an absolute http or https URL
gas/log: invalid option: WithBatchSize must be positive
gas/log: invalid option: WithQueueSize must be positive
gas/log: invalid option: WithFlushInterval must be positive
gas/log: invalid option: WithHTTPClient requires a client
gas/log: invalid option: WithLevel requires a level
gas/log: invalid option: WithLocalHandler requires a handler
gas/log: invalid option: WithErrorHandler requires a function
gas/log: invalid option: WithName requires a name
gas/log: invalid option: WithHeader requires a token as the name
gas/log: invalid option: WithHeader requires a value without control characters
gas/log: queue full: record dropped
gas/log: queue full: record dropped (3 times)
gas/log: not running: record dropped
gas/log: local handler failed: disk full
gas/log: marshal failed: unsupported value
gas/log: marshaler panicked
gas/log: post failed: Post "https://collector.example:4318": connection refused
gas/log: unexpected status 503 from https://collector.example:4318
gas/log: not delivered: 1 record
gas/log: not delivered: 2 records: context deadline exceeded
gas/log: still closing: context deadline exceeded

Index

Constants

View Source
const (
	// DefaultShippingName is the gas.Service name of a ShippingLogger.
	DefaultShippingName = "gas/log-shipping"
	// DefaultBatchSize is the most records in one request.
	DefaultBatchSize = 100
	// DefaultQueueSize is the most records waiting to be sent.
	DefaultQueueSize = 1024
	// DefaultFlushInterval is the longest a record waits for its batch to
	// fill, and the shortest time between two error reports of a class.
	DefaultFlushInterval = 2 * time.Second
	// DefaultHTTPTimeout is the timeout of the default HTTP client.
	DefaultHTTPTimeout = 10 * time.Second
	// DefaultFlushTimeout bounds ShippingLogger.Flush.
	DefaultFlushTimeout = 10 * time.Second
	// DefaultShippingLevel is the lowest level shipped.
	DefaultShippingLevel = slog.LevelInfo
)

The shipping defaults.

View Source
const LevelTrace = slog.LevelDebug - 4

LevelTrace is the slog level of the Trace events of a SlogLogger and a ShippingLogger, below slog.LevelDebug. The slog handlers print it as `DEBUG-4`.

View Source
const OTLPContentType = "application/json"

OTLPContentType is the Content-Type of an OTLPMarshaler's bodies.

View Source
const OTLPReplacedBody = "gas/log: record could not be encoded"

OTLPReplacedBody is the body of the record an OTLPMarshaler sends in place of one it could not encode.

Variables

View Source
var (
	// ErrNilLogger indicates that a constructor was given a nil logger.
	ErrNilLogger = errors.New("logger is nil")
	// ErrNilMarshaler indicates that a shipping constructor was given a nil
	// Marshaler.
	ErrNilMarshaler = errors.New("marshaler is nil")
	// ErrInvalidEndpoint indicates that a shipping endpoint is not an
	// absolute http or https URL.
	ErrInvalidEndpoint = errors.New("invalid endpoint")
	// ErrInvalidOption indicates that a ShippingOption was given a value it
	// does not accept.
	ErrInvalidOption = errors.New("invalid option")
	// ErrQueueFull indicates that a record was dropped because the shipping
	// queue was full.
	ErrQueueFull = errors.New("queue full")
	// ErrMarshal indicates that the Marshaler returned an error for a batch.
	ErrMarshal = errors.New("marshal failed")
	// ErrMarshalPanic indicates that the Marshaler panicked on a batch.
	ErrMarshalPanic = errors.New("marshaler panicked")
	// ErrPost indicates that posting a batch failed before a response
	// arrived.
	ErrPost = errors.New("post failed")
	// ErrStatus indicates that the endpoint answered a batch with a status
	// outside 2xx.
	ErrStatus = errors.New("unexpected status")
	// ErrNotDelivered indicates that a Flush or a Close returned with
	// records that were not delivered.
	ErrNotDelivered = errors.New("not delivered")
	// ErrLocalHandler indicates that the local handler of a shipping
	// handler returned an error.
	ErrLocalHandler = errors.New("local handler failed")
	// ErrNotRunning indicates that a record was dropped because it was
	// logged before the first Init of a ShippingLogger.
	ErrNotRunning = errors.New("not running")
	// ErrStillClosing indicates that Init returned because its context
	// ended while the sender of an earlier Close was still running.
	ErrStillClosing = errors.New("still closing")
)

Functions

func NewShippingLogger

func NewShippingLogger(
	endpoint string,
	m Marshaler,
	opts ...ShippingOption,
) func() (*ShippingLogger, error)

NewShippingLogger returns the constructor of a ShippingLogger that posts the records to endpoint, encoded by m, with opts applied, in the shape the gas container expects. The constructor checks what NewShippingHandler checks, in the same order, and does not start the sender: Init does.

func NewSlogLogger

func NewSlogLogger(opts ...SlogOption) func() (*SlogLogger, error)

NewSlogLogger returns the constructor of a SlogLogger with opts applied, in the shape the gas container expects. The constructor returns an error wrapping ErrNilLogger when WithSlogLogger was given nil.

Types

type Marshaler

type Marshaler interface {
	// Marshal encodes the batch into one request body.
	Marshal(records []Record) ([]byte, error)
	// ContentType is the value of the request's Content-Type header.
	ContentType() string
}

Marshaler encodes a batch of records into one request body. The batch is only valid during the call: the sender reuses its memory, so a Marshaler must not keep the slice. Marshal runs on the sender goroutine, one batch at a time.

type OTLPMarshaler

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

OTLPMarshaler encodes records as one OTLP/HTTP JSON logs request, as described in the package documentation. It is safe for concurrent use.

func NewOTLPMarshaler

func NewOTLPMarshaler(opts ...OTLPOption) *OTLPMarshaler

NewOTLPMarshaler returns an OTLPMarshaler with opts applied.

func (*OTLPMarshaler) ContentType

func (*OTLPMarshaler) ContentType() string

ContentType returns OTLPContentType.

func (*OTLPMarshaler) Marshal

func (m *OTLPMarshaler) Marshal(records []Record) ([]byte, error)

Marshal encodes the batch as one OTLP logs request. A record that fails to encode is replaced by the placeholder record and counted in Replaced, so it cannot fail the batch.

func (*OTLPMarshaler) Replaced added in v0.6.0

func (m *OTLPMarshaler) Replaced() uint64

Replaced returns how many records the marshaler has sent as the placeholder record, since it was made.

type OTLPOption

type OTLPOption func(*OTLPMarshaler)

OTLPOption configures an OTLPMarshaler.

func WithResourceAttribute

func WithResourceAttribute(key, value string) OTLPOption

WithResourceAttribute sets a string resource attribute, such as `host.name`. Given again for a key, it replaces the value. It has no default.

func WithScopeName

func WithScopeName(name string) OTLPOption

WithScopeName sets the name of the instrumentation scope.

Default: the `service.name` resource attribute, or no name without it.

func WithServiceName

func WithServiceName(name string) OTLPOption

WithServiceName sets the resource attribute `service.name`. Given again, it replaces the name. It also names the scope when WithScopeName is not given. It has no default.

func WithServiceVersion

func WithServiceVersion(version string) OTLPOption

WithServiceVersion sets the resource attribute `service.version`. Given again, it replaces the version. It has no default.

type Record

type Record struct {
	// Time is the record's time, zero when the record has none.
	Time time.Time
	// Message is the record's message.
	Message string
	// Attrs are the record's attributes, the handler's own first.
	Attrs []slog.Attr
	// Level is the record's level.
	Level slog.Level
}

Record is one log record handed to a Marshaler, as described in the package documentation under Records. A shipping handler builds it on the logging goroutine: its attributes are flat, with group names joined by `.`, LogValuers are resolved, and every slog.KindAny value is a string, a []byte the record owns, or nil.

type ShippingHandler added in v0.6.0

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

ShippingHandler is a slog.Handler that writes each record to a local handler and ships it to an HTTP endpoint, as described in the package documentation. The handlers from WithAttrs and WithGroup share its sender, so Flush, Close and Dropped on any of them act on all. It is safe for concurrent use.

func NewShippingHandler

func NewShippingHandler(
	endpoint string,
	m Marshaler,
	opts ...ShippingOption,
) (*ShippingHandler, error)

NewShippingHandler returns a ShippingHandler that posts the records to endpoint, encoded by m, with opts applied, and starts its sender. The constructor checks, in this order: m is not nil (ErrNilMarshaler), the endpoint is an absolute http or https URL (ErrInvalidEndpoint), and each option (ErrInvalidOption). Close stops the sender.

func (*ShippingHandler) Close added in v0.6.0

func (h *ShippingHandler) Close(ctx context.Context) error

Close stops accepting records and posts what is queued, in batches, within ctx, as described in the package documentation. It returns what Flush would for those records. Close on a closed handler returns nil.

func (*ShippingHandler) Dropped added in v0.6.0

func (h *ShippingHandler) Dropped() uint64

Dropped returns how many records were not delivered since the handler was made, as described in the package documentation.

func (*ShippingHandler) Enabled added in v0.6.0

func (h *ShippingHandler) Enabled(ctx context.Context, level slog.Level) bool

Enabled reports whether the local handler enables level, or level is at least the shipping level.

func (*ShippingHandler) Flush added in v0.6.0

func (h *ShippingHandler) Flush(ctx context.Context) error

Flush posts the records queued when it is called, in batches, and waits for them. It returns nil when they were delivered, or when the sender is not running. Otherwise it returns an error wrapping ErrNotDelivered with the count; when ctx ended first, the error wraps ctx.Err() too, and the count is what was still queued or being posted.

func (*ShippingHandler) Handle added in v0.6.0

func (h *ShippingHandler) Handle(ctx context.Context, r slog.Record) error

Handle writes r to the local handler when it enables r's level, then queues a Record of r for shipping when r's level is at least the shipping level. The Record is built here, on the caller's goroutine, as described in the package documentation. The local handler's error is reported and returned, wrapping ErrLocalHandler; r is shipped anyway.

func (*ShippingHandler) WithAttrs added in v0.6.0

func (h *ShippingHandler) WithAttrs(attrs []slog.Attr) slog.Handler

WithAttrs returns a handler that adds attrs to every record, after the attributes of h, in h's group.

func (*ShippingHandler) WithGroup added in v0.6.0

func (h *ShippingHandler) WithGroup(name string) slog.Handler

WithGroup returns a handler that puts the attributes of every record after it in the group name. An empty name returns h.

type ShippingLogger

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

ShippingLogger is a gas.Logger that writes each record locally and ships it to an HTTP endpoint, through a ShippingHandler, as described in the package documentation. It is a gas.Service: Init starts its sender and Close stops it. It is safe for concurrent use.

func (*ShippingLogger) Close

func (l *ShippingLogger) Close(ctx context.Context) error

Close is ShippingHandler.Close.

func (*ShippingLogger) Debug added in v0.6.0

func (l *ShippingLogger) Debug(msg string) gas.LogEvent

Debug starts an event at slog.LevelDebug.

func (*ShippingLogger) Dropped added in v0.6.0

func (l *ShippingLogger) Dropped() uint64

Dropped is ShippingHandler.Dropped.

func (*ShippingLogger) Error added in v0.6.0

func (l *ShippingLogger) Error(msg string) gas.LogEvent

Error starts an event at slog.LevelError.

func (*ShippingLogger) Flush

func (l *ShippingLogger) Flush()

Flush is ShippingHandler.Flush bounded by DefaultFlushTimeout. Its error, if any, goes to the error handler, in the class of ErrNotDelivered.

func (*ShippingLogger) Info added in v0.6.0

func (l *ShippingLogger) Info(msg string) gas.LogEvent

Info starts an event at slog.LevelInfo.

func (*ShippingLogger) Init

func (l *ShippingLogger) Init(ctx context.Context) error

Init starts the sender unless it runs, so a ShippingLogger closed by Close ships again after Init. When the sender of an earlier Close is still posting, because Close's context ended first or Close has not returned, Init waits for it to stop; it returns an error wrapping ErrStillClosing and ctx's error when ctx ends first. Otherwise it returns nil.

func (*ShippingLogger) Name

func (l *ShippingLogger) Name() string

Name returns the name given to WithName, or DefaultShippingName.

func (*ShippingLogger) Trace added in v0.6.0

func (l *ShippingLogger) Trace(msg string) gas.LogEvent

Trace starts an event at LevelTrace.

func (*ShippingLogger) Warn added in v0.6.0

func (l *ShippingLogger) Warn(msg string) gas.LogEvent

Warn starts an event at slog.LevelWarn.

func (*ShippingLogger) With added in v0.6.0

func (l *ShippingLogger) With() gas.LoggerContext

With returns a context for a logger that ships through the same sender with the fields added to the context. Its Flush is l's.

type ShippingOption

type ShippingOption func(*shippingConfig)

ShippingOption configures a ShippingLogger or a ShippingHandler. Options only record their value; the constructor checks them.

func WithBatchSize

func WithBatchSize(n int) ShippingOption

WithBatchSize sets the most records in one request. It must be positive.

Default: DefaultBatchSize.

func WithErrorHandler

func WithErrorHandler(fn func(error)) ShippingOption

WithErrorHandler sets the function that receives the error reports, as described in the package documentation. It must not be nil.

Default: a function that writes the error and a newline to standard error.

func WithFlushInterval

func WithFlushInterval(d time.Duration) ShippingOption

WithFlushInterval sets the longest a record waits for its batch to fill, which is also the shortest time between two error reports of a class. It must be positive.

Default: DefaultFlushInterval.

func WithHTTPClient

func WithHTTPClient(client *http.Client) ShippingOption

WithHTTPClient sets the HTTP client that posts the batches, used as it is, redirect policy included. It must not be nil.

Default: a client with the timeout DefaultHTTPTimeout that follows no redirect, so a 3xx response is a failed post.

func WithHeader

func WithHeader(key, value string) ShippingOption

WithHeader adds a header sent with every request, such as an API key. Given again for a key, it replaces the value. It can replace the Content-Type the Marshaler names. The key must be a token and the value must hold no control character but a horizontal tab, as RFC 9110 says. Header names and values never appear in an error. It has no default.

func WithLevel

func WithLevel(level slog.Leveler) ShippingOption

WithLevel sets the lowest level shipped. It is read on every record, so a *slog.LevelVar changes it at run time. It must not be nil.

Default: DefaultShippingLevel.

func WithLocalHandler

func WithLocalHandler(h slog.Handler) ShippingOption

WithLocalHandler sets the handler that also receives every record it enables, before it is shipped. It must not be nil; WithoutLocalHandler turns local logging off.

Default: a slog.JSONHandler on standard error at the shipping level.

func WithName

func WithName(name string) ShippingOption

WithName sets the gas.Service name of a ShippingLogger. Two shipping loggers in one app need distinct names. It must not be empty.

Default: DefaultShippingName.

func WithQueueSize

func WithQueueSize(n int) ShippingOption

WithQueueSize sets the most records waiting to be sent; a record logged when the queue is full is dropped. It must be positive.

Default: DefaultQueueSize.

func WithoutLocalHandler

func WithoutLocalHandler() ShippingOption

WithoutLocalHandler turns local logging off, so records are only shipped. It wins over WithLocalHandler.

type SlogLogger

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

SlogLogger is a gas.Logger over a *slog.Logger, as described in the package documentation. It is safe for concurrent use; its events are not.

func (*SlogLogger) Debug

func (l *SlogLogger) Debug(msg string) gas.LogEvent

Debug starts an event at slog.LevelDebug.

func (*SlogLogger) Error

func (l *SlogLogger) Error(msg string) gas.LogEvent

Error starts an event at slog.LevelError.

func (*SlogLogger) Flush

func (l *SlogLogger) Flush()

Flush does nothing for a SlogLogger of its own, which buffers nothing. For a logger from a ShippingLogger it is the ShippingLogger's Flush.

func (*SlogLogger) Info

func (l *SlogLogger) Info(msg string) gas.LogEvent

Info starts an event at slog.LevelInfo.

func (*SlogLogger) Trace

func (l *SlogLogger) Trace(msg string) gas.LogEvent

Trace starts an event at LevelTrace.

func (*SlogLogger) Warn

func (l *SlogLogger) Warn(msg string) gas.LogEvent

Warn starts an event at slog.LevelWarn.

func (*SlogLogger) With

func (l *SlogLogger) With() gas.LoggerContext

With returns a context for a logger that writes to the same handler with the fields added to the context.

type SlogOption added in v0.6.0

type SlogOption func(*SlogLogger)

SlogOption configures a SlogLogger.

func WithSlogLogger added in v0.6.0

func WithSlogLogger(logger *slog.Logger) SlogOption

WithSlogLogger sets the *slog.Logger the SlogLogger writes to. A nil logger fails the constructor with ErrNilLogger.

Default: slog.Default() when the constructor runs.

Directories

Path Synopsis
Package logtest provides RecordingLogger, a gas.Logger for tests that keeps every event it sends, with its level, message and fields.
Package logtest provides RecordingLogger, a gas.Logger for tests that keeps every event it sends, with its level, message and fields.
Package zerolog provides a gas.Logger over a zerolog.Logger.
Package zerolog provides a gas.Logger over a zerolog.Logger.

Jump to

Keyboard shortcuts

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