## Search

Page index: https://gasmod.dev/llms.txt. Add index.md to any page URL for its Markdown.

This site has a search endpoint: https://context7.com/api/v2/ask?siteKey=ask_b845b566cb63bd033e9c576d&query=<URL-encoded question>. It returns documentation that answers the question, with a source link for each part. No API key is needed. If nothing matches, it says so.

# log

> 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.

The Markdown of https://gasmod.dev/reference/log/ from the Gas documentation, whose index for LLMs is https://gasmod.dev/llms.txt

```go
import "github.com/gasmod/gas/log"
```

Package log provides gas.Logger implementations over log/slog, and ships
log records in batches to an HTTP endpoint, encoded by a [Marshaler](#Marshaler)
such as the OTLP/JSON [OTLPMarshaler](#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](#NewShippingLogger),
calls its Init, and its Close at shutdown. By hand:

```go
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](#SlogLogger), from [NewSlogLogger](#NewSlogLogger), writes to a \*slog.Logger,
slog.Default() unless [WithSlogLogger](#WithSlogLogger) gives one. Trace is
[LevelTrace](#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](#ShippingLogger), from [NewShippingLogger](#NewShippingLogger), is a SlogLogger over a
[ShippingHandler](#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](#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](#Record) of it for shipping, when the level is at least
the shipping level: [WithLevel](#WithLevel), [DefaultShippingLevel](#DefaultShippingLevel) unless given.

The local handler is [WithLocalHandler](#WithLocalHandler)'s, or a slog.JSONHandler on
standard error at the shipping level. [WithoutLocalHandler](#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](#WithQueueSize) records,
[DefaultQueueSize](#DefaultQueueSize) unless given, and Handle never blocks on it. A
goroutine of the sender posts them:

- As soon as the queue holds [WithBatchSize](#WithBatchSize) records,
[DefaultBatchSize](#DefaultBatchSize) unless given, it posts the oldest as a batch.
- Every [WithFlushInterval](#WithFlushInterval), [DefaultFlushInterval](#DefaultFlushInterval) unless given, it
posts all the records waiting, in batches.

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](#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](#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](#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](#ShippingHandler.Dropped) and [ShippingLogger.Dropped](#ShippingLogger.Dropped) return the count
since the handler was made.

## Flush and Close

[ShippingHandler.Flush](#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](#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](#ShippingLogger.Flush), the Flush of gas.Logger, does the same within
[DefaultFlushTimeout](#DefaultFlushTimeout), and reports its error. A logger from With flushes
the same sender.

[ShippingHandler.Close](#ShippingHandler.Close) and [ShippingLogger.Close](#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](#ErrStillClosing) and the context's
error, and the sender is not started.

Each ShippingLogger is a gas.Service named by [WithName](#WithName),
[DefaultShippingName](#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](#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:

- [ErrQueueFull](#ErrQueueFull): a record dropped on a full queue.
- [ErrLocalHandler](#ErrLocalHandler): the local handler's error, which Handle also
returns.
- [ErrMarshal](#ErrMarshal), [ErrMarshalPanic](#ErrMarshalPanic): a Marshaler's error or panic.
- [ErrPost](#ErrPost): a failed post.
- [ErrStatus](#ErrStatus): a status outside 2xx.
- [ErrNotDelivered](#ErrNotDelivered): the error of ShippingLogger.Flush.
- [ErrNotRunning](#ErrNotRunning): a record logged before the first Init of a
ShippingLogger, so a logger that is never started is not silent.

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](#OTLPMarshaler) encodes a batch as one OTLP/HTTP JSON logs request
(Content-Type [OTLPContentType](#OTLPContentType)). The request holds:

- One resource, with the attributes given to [WithServiceName](#WithServiceName),
[WithServiceVersion](#WithServiceVersion) and [WithResourceAttribute](#WithResourceAttribute), each replacing an
earlier value of its key.
- One scope, named by [WithScopeName](#WithScopeName) or else the service name.
- One log record per Record, following the OTLP JSON Protobuf
encoding.

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](#OTLPReplacedBody), and counted by [OTLPMarshaler.Replaced](#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](https://pkg.go.dev/errors#Is):

- [ErrNilLogger](#ErrNilLogger): WithSlogLogger was given nil.
- [ErrNilMarshaler](#ErrNilMarshaler): a shipping constructor was given a nil Marshaler.
- [ErrInvalidEndpoint](#ErrInvalidEndpoint): the endpoint is not an absolute http or https
URL.
- [ErrInvalidOption](#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](#ErrQueueFull), [ErrNotRunning](#ErrNotRunning), [ErrLocalHandler](#ErrLocalHandler), [ErrMarshal](#ErrMarshal),
[ErrMarshalPanic](#ErrMarshalPanic), [ErrPost](#ErrPost), [ErrStatus](#ErrStatus): reported to the error
handler, as described under Error reports. ErrLocalHandler,
ErrMarshal and ErrPost wrap the cause.
- [ErrNotDelivered](#ErrNotDelivered): Flush or Close returned with records not
delivered. It wraps the context's error when the context ended.
- [ErrStillClosing](#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:

```go
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
```


## API reference

### Constants

<a id="DefaultShippingName"></a><a id="DefaultBatchSize"></a><a id="DefaultQueueSize"></a><a id="DefaultFlushInterval"></a><a id="DefaultHTTPTimeout"></a><a id="DefaultFlushTimeout"></a><a id="DefaultShippingLevel"></a>

```go
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.

<a id="LevelTrace"></a>

```go
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`.

<a id="OTLPContentType"></a>

```go
const OTLPContentType = "application/json"
```

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

<a id="OTLPReplacedBody"></a>

```go
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

<a id="ErrNilLogger"></a><a id="ErrNilMarshaler"></a><a id="ErrInvalidEndpoint"></a><a id="ErrInvalidOption"></a><a id="ErrQueueFull"></a><a id="ErrMarshal"></a><a id="ErrMarshalPanic"></a><a id="ErrPost"></a><a id="ErrStatus"></a><a id="ErrNotDelivered"></a><a id="ErrLocalHandler"></a><a id="ErrNotRunning"></a><a id="ErrStillClosing"></a>

```go
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")
)
```

<a id="NewShippingLogger"></a>

#### func NewShippingLogger

```go
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.

<a id="NewSlogLogger"></a>

#### func NewSlogLogger

```go
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.

<a id="Marshaler"></a><a id="Marshaler.Marshal"></a><a id="Marshaler.ContentType"></a>

### type Marshaler

```go
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.

<a id="OTLPMarshaler"></a>

### type OTLPMarshaler

```go
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.

<a id="NewOTLPMarshaler"></a>

#### func NewOTLPMarshaler

```go
func NewOTLPMarshaler(opts ...OTLPOption) *OTLPMarshaler
```

NewOTLPMarshaler returns an OTLPMarshaler with opts applied.

<a id="OTLPMarshaler.ContentType"></a>

#### func (*OTLPMarshaler) ContentType

```go
func (*OTLPMarshaler) ContentType() string
```

ContentType returns OTLPContentType.

<a id="OTLPMarshaler.Marshal"></a>

#### func (*OTLPMarshaler) Marshal

```go
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.

<a id="OTLPMarshaler.Replaced"></a>

#### func (*OTLPMarshaler) Replaced

```go
func (m *OTLPMarshaler) Replaced() uint64
```

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

<a id="OTLPOption"></a>

### type OTLPOption

```go
type OTLPOption func(*OTLPMarshaler)
```

OTLPOption configures an OTLPMarshaler.

<a id="WithResourceAttribute"></a>

#### func WithResourceAttribute

```go
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.

<a id="WithScopeName"></a>

#### func WithScopeName

```go
func WithScopeName(name string) OTLPOption
```

WithScopeName sets the name of the instrumentation scope.

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

<a id="WithServiceName"></a>

#### func WithServiceName

```go
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.

<a id="WithServiceVersion"></a>

#### func WithServiceVersion

```go
func WithServiceVersion(version string) OTLPOption
```

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

<a id="Record"></a>

### type Record

```go
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.

<a id="ShippingHandler"></a>

### type ShippingHandler

```go
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.

<a id="NewShippingHandler"></a>

#### func NewShippingHandler

```go
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.

<a id="ShippingHandler.Close"></a>

#### func (*ShippingHandler) Close

```go
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.

<a id="ShippingHandler.Dropped"></a>

#### func (*ShippingHandler) Dropped

```go
func (h *ShippingHandler) Dropped() uint64
```

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

<a id="ShippingHandler.Enabled"></a>

#### func (*ShippingHandler) Enabled

```go
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.

<a id="ShippingHandler.Flush"></a>

#### func (*ShippingHandler) Flush

```go
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.

<a id="ShippingHandler.Handle"></a>

#### func (*ShippingHandler) Handle

```go
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.

<a id="ShippingHandler.WithAttrs"></a>

#### func (*ShippingHandler) WithAttrs

```go
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.

<a id="ShippingHandler.WithGroup"></a>

#### func (*ShippingHandler) WithGroup

```go
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.

<a id="ShippingLogger"></a>

### type ShippingLogger

```go
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.

<a id="ShippingLogger.Close"></a>

#### func (*ShippingLogger) Close

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

Close is ShippingHandler.Close.

<a id="ShippingLogger.Debug"></a>

#### func (*ShippingLogger) Debug

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

Debug starts an event at slog.LevelDebug.

<a id="ShippingLogger.Dropped"></a>

#### func (*ShippingLogger) Dropped

```go
func (l *ShippingLogger) Dropped() uint64
```

Dropped is ShippingHandler.Dropped.

<a id="ShippingLogger.Error"></a>

#### func (*ShippingLogger) Error

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

Error starts an event at slog.LevelError.

<a id="ShippingLogger.Flush"></a>

#### func (*ShippingLogger) Flush

```go
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.

<a id="ShippingLogger.Info"></a>

#### func (*ShippingLogger) Info

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

Info starts an event at slog.LevelInfo.

<a id="ShippingLogger.Init"></a>

#### func (*ShippingLogger) Init

```go
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.

<a id="ShippingLogger.Name"></a>

#### func (*ShippingLogger) Name

```go
func (l *ShippingLogger) Name() string
```

Name returns the name given to WithName, or DefaultShippingName.

<a id="ShippingLogger.Trace"></a>

#### func (*ShippingLogger) Trace

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

Trace starts an event at LevelTrace.

<a id="ShippingLogger.Warn"></a>

#### func (*ShippingLogger) Warn

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

Warn starts an event at slog.LevelWarn.

<a id="ShippingLogger.With"></a>

#### func (*ShippingLogger) With

```go
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.

<a id="ShippingOption"></a>

### type ShippingOption

```go
type ShippingOption func(*shippingConfig)
```

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

<a id="WithBatchSize"></a>

#### func WithBatchSize

```go
func WithBatchSize(n int) ShippingOption
```

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

Default: DefaultBatchSize.

<a id="WithErrorHandler"></a>

#### func WithErrorHandler

```go
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.

<a id="WithFlushInterval"></a>

#### func WithFlushInterval

```go
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.

<a id="WithHTTPClient"></a>

#### func WithHTTPClient

```go
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.

<a id="WithHeader"></a>

#### func WithHeader

```go
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.

<a id="WithLevel"></a>

#### func WithLevel

```go
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.

<a id="WithLocalHandler"></a>

#### func WithLocalHandler

```go
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.

<a id="WithName"></a>

#### func WithName

```go
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.

<a id="WithQueueSize"></a>

#### func WithQueueSize

```go
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.

<a id="WithoutLocalHandler"></a>

#### func WithoutLocalHandler

```go
func WithoutLocalHandler() ShippingOption
```

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

<a id="SlogLogger"></a>

### type SlogLogger

```go
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.

<a id="SlogLogger.Debug"></a>

#### func (*SlogLogger) Debug

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

Debug starts an event at slog.LevelDebug.

<a id="SlogLogger.Error"></a>

#### func (*SlogLogger) Error

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

Error starts an event at slog.LevelError.

<a id="SlogLogger.Flush"></a>

#### func (*SlogLogger) Flush

```go
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.

<a id="SlogLogger.Info"></a>

#### func (*SlogLogger) Info

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

Info starts an event at slog.LevelInfo.

<a id="SlogLogger.Trace"></a>

#### func (*SlogLogger) Trace

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

Trace starts an event at LevelTrace.

<a id="SlogLogger.Warn"></a>

#### func (*SlogLogger) Warn

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

Warn starts an event at slog.LevelWarn.

<a id="SlogLogger.With"></a>

#### func (*SlogLogger) With

```go
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.

<a id="SlogOption"></a>

### type SlogOption

```go
type SlogOption func(*SlogLogger)
```

SlogOption configures a SlogLogger.

<a id="WithSlogLogger"></a>

#### func WithSlogLogger

```go
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.
