Documentation
¶
Overview ¶
Package transport defines the Transport interface and BaseTransport helper used by all LogLayer transport implementations.
Index ¶
- func AssembleMessage(messages []any, sanitize func(string) string) string
- func FieldEstimate(p loglayer.TransportParams) int
- func JoinMessages(messages []any) string
- func JoinPrefixAndMessages(prefix string, messages []any) []any
- func MergeFieldsAndMetadata(p loglayer.TransportParams) map[string]any
- func MergeIntoMap(dst map[string]any, data map[string]any, metadata any, metadataKey string) map[string]any
- func MetadataAsMap(v any) map[string]any
- func MetadataAsRootMap(v any) (map[string]any, bool)
- func WriterOrStderr(w io.Writer) io.Writer
- func WriterOrStdout(w io.Writer) io.Writer
- type BaseConfig
- type BaseTransport
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func AssembleMessage ¶ added in v2.1.0
AssembleMessage flattens a message slice into a single string, applying sanitize to every authored chunk while preserving line boundaries inside *MultilineMessage values.
For each element in messages:
- string s -> sanitize(s)
- *MultilineMessage m -> per-line sanitize, joined with "\n"
- any other v -> sanitize(fmt.Sprintf("%v", v))
Adjacent elements are joined with " ". Empty messages produce "". Nil elements format as "<nil>" via the default branch (matching JoinMessages's behavior for non-string elements).
Used by terminal-style transports (cli, pretty, console). Wrapper transports and JSON sinks call JoinMessages instead; the *MultilineMessage.String method handles flattening transparently for them.
func FieldEstimate ¶
func FieldEstimate(p loglayer.TransportParams) int
FieldEstimate returns the expected number of fields a transport will emit for the given params. Use it to size pre-allocated slices/maps in transports that benefit from capacity hints (zap, charmlog).
func JoinMessages ¶
JoinMessages concatenates a slice of values into a single space-separated string. Strings are passed through; other types use fmt.Sprintf("%v", ...).
The single-string case is the dominant log shape, so it returns the value directly without allocating a slice.
func JoinPrefixAndMessages ¶
JoinPrefixAndMessages folds prefix into the first message so the rendered output reads as one blob (`"[prefix] message body"`). Returns messages unchanged when prefix is empty or messages[0] is not a string; otherwise returns a fresh slice whose first element is `prefix + " " + messages[0]`.
Most renderer / wrapper transports want this rendering and call the helper at the top of SendToLogger:
func (t *Transport) SendToLogger(p loglayer.TransportParams) {
if !t.ShouldProcess(p.LogLevel) { return }
p.Messages = transport.JoinPrefixAndMessages(p.Prefix, p.Messages)
// ... existing rendering logic ...
}
Transports that want to render the prefix differently (cli's dim-color treatment, a structured transport's separate JSON field, wrapper transports forwarding to the underlying logger's structured-field API) should NOT call this helper; instead consume p.Prefix directly and emit messages without the prefix folded in.
func MergeFieldsAndMetadata ¶
MergeFieldsAndMetadata combines params.Data (the assembled fields + error map) with the metadata value into a single map for transports that render to a flat structure. Returns nil when both inputs are empty so callers can short-circuit.
Metadata policy is driven by [loglayer.Schema.MetadataFieldName] on the params:
- Empty (default): map metadata merges at the root; non-map metadata is JSON-roundtripped via MetadataAsMap and spread at the root (or dropped if the roundtrip fails).
- Non-empty: the entire metadata value (map or non-map) nests under the configured key. No roundtrip; encoders downstream get the raw value.
For "nest non-map metadata under a fixed key" semantics in encoders without access to TransportParams, use MergeIntoMap with an explicit metadataKey.
Pretty has its own local variant that uses a richer metadata extractor (preserves a _metadata fallback for slices/scalars). Other transports should use this one.
func MergeIntoMap ¶
func MergeIntoMap(dst map[string]any, data map[string]any, metadata any, metadataKey string) map[string]any
MergeIntoMap copies data and metadata into dst (the same map; mutated in place) and returns dst for chaining convenience. Use it from encoders that have already seeded dst with their own protocol fields (level/time/msg, ddsource/...) and want to layer user data on top.
metadataKey controls placement: when non-empty, the entire metadata value nests under that key uniformly. When empty, map metadata merges at root and non-map nests under the literal "metadata" key without roundtrip. Callers with access to [loglayer.TransportParams] should pass params.Schema.MetadataFieldName.
Pretty has its own variant with an `_metadata` fallback for non-roundtrippable values (see transports/pretty/render.go); it doesn't use this helper.
func MetadataAsMap ¶
MetadataAsMap extracts a map[string]any from any metadata value. Maps (loglayer.Metadata or raw map[string]any) pass through directly; other types are converted via a JSON roundtrip so their exported fields land at the root of the log object.
Returns nil when the JSON roundtrip fails (cyclic structs, channels, functions, custom MarshalJSON returning a non-object). Callers that need to know about the failure should compare against nil; the helper itself doesn't surface an error to keep the dispatch path simple. Transports that want richer error reporting should call json.Marshal themselves and surface failures via OnError.
func MetadataAsRootMap ¶
MetadataAsRootMap returns metadata as a map[string]any if it's a "flatten at root" shape (loglayer.Metadata or raw map[string]any), false otherwise. Use this in transports that need to decide whether metadata flattens to individual attributes/fields (true) or nests under MetadataFieldName (false). Metadata and map[string]any share an underlying type but are distinct named types, so a single type assertion handles only one of them; this helper covers both.
func WriterOrStderr ¶
WriterOrStderr returns w if non-nil, otherwise os.Stderr. Used by wrapper transports to default the construction-time writer.
Types ¶
type BaseConfig ¶
type BaseConfig struct {
// ID uniquely identifies this transport. Optional: when empty,
// NewBaseTransport assigns an auto-generated identifier. Supply your
// own when you intend to call RemoveTransport / GetLoggerInstance by
// ID later.
ID string
// Disabled suppresses this transport from accepting log entries when true.
// Defaults to false (transport active). Equivalent to calling
// SetEnabled(false) after construction.
Disabled bool
// Level sets the minimum log level this transport will process.
// Defaults to LogLevelTrace so a transport accepts every level by
// default (the logger's own level state is the primary filter).
// Set this when you want a transport to receive only entries at or
// above a specific level, e.g. an error-only sink in a fan-out.
Level loglayer.LogLevel
}
BaseConfig holds the common configuration fields shared by all transports.
type BaseTransport ¶
type BaseTransport struct {
// contains filtered or unexported fields
}
BaseTransport provides common fields and level-filtering logic for transports. Concrete transports should embed *BaseTransport and implement ShipToLogger.
func NewBaseTransport ¶
func NewBaseTransport(cfg BaseConfig) BaseTransport
NewBaseTransport creates a BaseTransport from a BaseConfig. An empty cfg.ID is replaced with an auto-generated identifier.
func (*BaseTransport) ID ¶
func (b *BaseTransport) ID() string
ID returns the transport's unique identifier.
func (*BaseTransport) IsEnabled ¶
func (b *BaseTransport) IsEnabled() bool
IsEnabled returns whether the transport is currently enabled. Safe to call concurrently with SetEnabled.
func (*BaseTransport) MinLevel ¶
func (b *BaseTransport) MinLevel() loglayer.LogLevel
MinLevel returns the minimum log level this transport will process.
func (*BaseTransport) SetEnabled ¶
func (b *BaseTransport) SetEnabled(v bool)
SetEnabled enables or disables the transport. Safe to call concurrently with emission and IsEnabled.
func (*BaseTransport) ShouldProcess ¶
func (b *BaseTransport) ShouldProcess(level loglayer.LogLevel) bool
ShouldProcess returns true if the transport is enabled and the log level meets the minimum level threshold.
Directories
¶
| Path | Synopsis |
|---|---|
|
Package benchtest provides shared benchmark helpers for LogLayer transport and framework benchmarks.
|
Package benchtest provides shared benchmark helpers for LogLayer transport and framework benchmarks. |
|
Package transporttest provides helpers and a contract test suite for LogLayer transport implementations.
|
Package transporttest provides helpers and a contract test suite for LogLayer transport implementations. |