gas/log
log
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 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.
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
Section titled “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
Section titled “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
Section titled “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
Section titled “Shipping”A ShippingHandler handles each record in two steps:
- It writes the record to its local handler, when that enables the record’s level.
- 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
Section titled “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
!unencodableand 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
Section titled “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:
- As soon as the queue holds WithBatchSize records, DefaultBatchSize unless given, it posts the oldest as a batch.
- Every WithFlushInterval, 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, 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
Section titled “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
Section titled “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
Section titled “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
Section titled “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:
- ErrQueueFull: a record dropped on a full queue.
- ErrLocalHandler: the local handler’s error, which Handle also returns.
- ErrMarshal, ErrMarshalPanic: a Marshaler’s error or panic.
- ErrPost: a failed post.
- ErrStatus: a status outside 2xx.
- ErrNotDelivered: the error of ShippingLogger.Flush.
- 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
Section titled “OTLP encoding”OTLPMarshaler encodes a batch as one OTLP/HTTP JSON logs request (Content-Type OTLPContentType). The request holds:
- One resource, with the attributes given to WithServiceName, WithServiceVersion and WithResourceAttribute, each replacing an earlier value of its key.
- One scope, named by 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:TRACEfor LevelTrace, else slog’s name of the level, such asINFOorDEBUG-2.body: the message, asstringValue.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 decimalstringValue. - A float is
doubleValue, a number, or the stringNaN,Infinityor-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
Section titled “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
Section titled “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 nilgas/log: marshaler is nilgas/log: invalid endpoint: must be an absolute http or https URLgas/log: invalid option: WithBatchSize must be positivegas/log: invalid option: WithQueueSize must be positivegas/log: invalid option: WithFlushInterval must be positivegas/log: invalid option: WithHTTPClient requires a clientgas/log: invalid option: WithLevel requires a levelgas/log: invalid option: WithLocalHandler requires a handlergas/log: invalid option: WithErrorHandler requires a functiongas/log: invalid option: WithName requires a namegas/log: invalid option: WithHeader requires a token as the namegas/log: invalid option: WithHeader requires a value without control charactersgas/log: queue full: record droppedgas/log: queue full: record dropped (3 times)gas/log: not running: record droppedgas/log: local handler failed: disk fullgas/log: marshal failed: unsupported valuegas/log: marshaler panickedgas/log: post failed: Post "https://collector.example:4318": connection refusedgas/log: unexpected status 503 from https://collector.example:4318gas/log: not delivered: 1 recordgas/log: not delivered: 2 records: context deadline exceededgas/log: still closing: context deadline exceededAPI reference
Section titled “API reference”Constants
Section titled “Constants”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.
const LevelTrace = slog.LevelDebug - 4LevelTrace 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.
const OTLPContentType = "application/json"OTLPContentType is the Content-Type of an OTLPMarshaler’s bodies.
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
Section titled “Variables”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"))func NewShippingLogger
Section titled “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
Section titled “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.
type Marshaler
Section titled “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
Section titled “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
Section titled “func NewOTLPMarshaler”func NewOTLPMarshaler(opts ...OTLPOption) *OTLPMarshalerNewOTLPMarshaler returns an OTLPMarshaler with opts applied.
func (*OTLPMarshaler) ContentType
Section titled “func (*OTLPMarshaler) ContentType”func (*OTLPMarshaler) ContentType() stringContentType returns OTLPContentType.
func (*OTLPMarshaler) Marshal
Section titled “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
Section titled “func (*OTLPMarshaler) Replaced”func (m *OTLPMarshaler) Replaced() uint64Replaced returns how many records the marshaler has sent as the placeholder record, since it was made.
type OTLPOption
Section titled “type OTLPOption”type OTLPOption func(*OTLPMarshaler)OTLPOption configures an OTLPMarshaler.
func WithResourceAttribute
Section titled “func WithResourceAttribute”func WithResourceAttribute(key, value string) OTLPOptionWithResourceAttribute sets a string resource attribute, such as
host.name. Given again for a key, it replaces the value. It has no
default.
func WithScopeName
Section titled “func WithScopeName”func WithScopeName(name string) OTLPOptionWithScopeName sets the name of the instrumentation scope.
Default: the service.name resource attribute, or no name without it.
func WithServiceName
Section titled “func WithServiceName”func WithServiceName(name string) OTLPOptionWithServiceName 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
Section titled “func WithServiceVersion”func WithServiceVersion(version string) OTLPOptionWithServiceVersion sets the resource attribute service.version. Given
again, it replaces the version. It has no default.
type Record
Section titled “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
Section titled “type ShippingHandler”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
Section titled “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
Section titled “func (*ShippingHandler) Close”func (h *ShippingHandler) Close(ctx context.Context) errorClose 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
Section titled “func (*ShippingHandler) Dropped”func (h *ShippingHandler) Dropped() uint64Dropped returns how many records were not delivered since the handler was made, as described in the package documentation.
func (*ShippingHandler) Enabled
Section titled “func (*ShippingHandler) Enabled”func (h *ShippingHandler) Enabled(ctx context.Context, level slog.Level) boolEnabled reports whether the local handler enables level, or level is at least the shipping level.
func (*ShippingHandler) Flush
Section titled “func (*ShippingHandler) Flush”func (h *ShippingHandler) Flush(ctx context.Context) errorFlush 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
Section titled “func (*ShippingHandler) Handle”func (h *ShippingHandler) Handle(ctx context.Context, r slog.Record) errorHandle 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
Section titled “func (*ShippingHandler) WithAttrs”func (h *ShippingHandler) WithAttrs(attrs []slog.Attr) slog.HandlerWithAttrs returns a handler that adds attrs to every record, after the attributes of h, in h’s group.
func (*ShippingHandler) WithGroup
Section titled “func (*ShippingHandler) WithGroup”func (h *ShippingHandler) WithGroup(name string) slog.HandlerWithGroup returns a handler that puts the attributes of every record after it in the group name. An empty name returns h.
type ShippingLogger
Section titled “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
Section titled “func (*ShippingLogger) Close”func (l *ShippingLogger) Close(ctx context.Context) errorClose is ShippingHandler.Close.
func (*ShippingLogger) Debug
Section titled “func (*ShippingLogger) Debug”func (l *ShippingLogger) Debug(msg string) gas.LogEventDebug starts an event at slog.LevelDebug.
func (*ShippingLogger) Dropped
Section titled “func (*ShippingLogger) Dropped”func (l *ShippingLogger) Dropped() uint64Dropped is ShippingHandler.Dropped.
func (*ShippingLogger) Error
Section titled “func (*ShippingLogger) Error”func (l *ShippingLogger) Error(msg string) gas.LogEventError starts an event at slog.LevelError.
func (*ShippingLogger) Flush
Section titled “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
Section titled “func (*ShippingLogger) Info”func (l *ShippingLogger) Info(msg string) gas.LogEventInfo starts an event at slog.LevelInfo.
func (*ShippingLogger) Init
Section titled “func (*ShippingLogger) Init”func (l *ShippingLogger) Init(ctx context.Context) errorInit 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
Section titled “func (*ShippingLogger) Name”func (l *ShippingLogger) Name() stringName returns the name given to WithName, or DefaultShippingName.
func (*ShippingLogger) Trace
Section titled “func (*ShippingLogger) Trace”func (l *ShippingLogger) Trace(msg string) gas.LogEventTrace starts an event at LevelTrace.
func (*ShippingLogger) Warn
Section titled “func (*ShippingLogger) Warn”func (l *ShippingLogger) Warn(msg string) gas.LogEventWarn starts an event at slog.LevelWarn.
func (*ShippingLogger) With
Section titled “func (*ShippingLogger) With”func (l *ShippingLogger) With() gas.LoggerContextWith 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
Section titled “type ShippingOption”type ShippingOption func(*shippingConfig)ShippingOption configures a ShippingLogger or a ShippingHandler. Options only record their value; the constructor checks them.
func WithBatchSize
Section titled “func WithBatchSize”func WithBatchSize(n int) ShippingOptionWithBatchSize sets the most records in one request. It must be positive.
Default: DefaultBatchSize.
func WithErrorHandler
Section titled “func WithErrorHandler”func WithErrorHandler(fn func(error)) ShippingOptionWithErrorHandler 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
Section titled “func WithFlushInterval”func WithFlushInterval(d time.Duration) ShippingOptionWithFlushInterval 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
Section titled “func WithHTTPClient”func WithHTTPClient(client *http.Client) ShippingOptionWithHTTPClient 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
Section titled “func WithHeader”func WithHeader(key, value string) ShippingOptionWithHeader 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
Section titled “func WithLevel”func WithLevel(level slog.Leveler) ShippingOptionWithLevel 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
Section titled “func WithLocalHandler”func WithLocalHandler(h slog.Handler) ShippingOptionWithLocalHandler 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
Section titled “func WithName”func WithName(name string) ShippingOptionWithName 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
Section titled “func WithQueueSize”func WithQueueSize(n int) ShippingOptionWithQueueSize 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
Section titled “func WithoutLocalHandler”func WithoutLocalHandler() ShippingOptionWithoutLocalHandler turns local logging off, so records are only shipped. It wins over WithLocalHandler.
type SlogLogger
Section titled “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
Section titled “func (*SlogLogger) Debug”func (l *SlogLogger) Debug(msg string) gas.LogEventDebug starts an event at slog.LevelDebug.
func (*SlogLogger) Error
Section titled “func (*SlogLogger) Error”func (l *SlogLogger) Error(msg string) gas.LogEventError starts an event at slog.LevelError.
func (*SlogLogger) Flush
Section titled “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
Section titled “func (*SlogLogger) Info”func (l *SlogLogger) Info(msg string) gas.LogEventInfo starts an event at slog.LevelInfo.
func (*SlogLogger) Trace
Section titled “func (*SlogLogger) Trace”func (l *SlogLogger) Trace(msg string) gas.LogEventTrace starts an event at LevelTrace.
func (*SlogLogger) Warn
Section titled “func (*SlogLogger) Warn”func (l *SlogLogger) Warn(msg string) gas.LogEventWarn starts an event at slog.LevelWarn.
func (*SlogLogger) With
Section titled “func (*SlogLogger) With”func (l *SlogLogger) With() gas.LoggerContextWith returns a context for a logger that writes to the same handler with the fields added to the context.
type SlogOption
Section titled “type SlogOption”type SlogOption func(*SlogLogger)SlogOption configures a SlogLogger.
func WithSlogLogger
Section titled “func WithSlogLogger”func WithSlogLogger(logger *slog.Logger) SlogOptionWithSlogLogger sets the *slog.Logger the SlogLogger writes to. A nil logger fails the constructor with ErrNilLogger.
Default: slog.Default() when the constructor runs.