heterolog

package module
v0.4.0 Latest Latest
Warning

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

Go to latest
Published: Oct 27, 2026 License: MIT Imports: 23 Imported by: 1 module, 0 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

heterolog

日本語版

heterolog is a Go logging library that writes to several destinations at once, rotates and compresses log files, and keeps and replays logs that could not be delivered. It can also be used through the standard log/slog package.

  • Module path: github.com/go-jappe/heterolog
  • Requires Go 1.27.3 or later
  • License: MIT License

The other documents in this repository, including the comments in .env.example, are written in Japanese.

Contents

Features

  • Destinations: stdout, file, Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse, several at once.
  • Three loggers: synchronous (returns errors), asynchronous best effort, and delivery (reports the result for each destination).
  • A log/slog handler.
  • Log file rotation, compression (gzip, zstd, lz4, xz), and upload to object storage (S3) with upload checkpoints.
  • Logs that could not be delivered are kept in a spool or a failure archive and replayed. Retry-After is honored, also across restarts.
  • Overload protection with a free disk space threshold, an optional memory pressure monitor, and drop/degrade policies.
  • Configuration in code, or from HETEROLOG_ environment variables with LoadEnvConfig.
  • The level and sampling of outputs can change while the application runs, in code or through a token-protected HTTP API.
  • A CLI that recovers log files of a stopped application.
  • Tested on Linux, Windows, and macOS, including case-insensitive file systems.

Installation

go get github.com/go-jappe/heterolog

Quick start

In a checkout of this repository, you can run the following example:

go run ./examples/slog
package main

import (
    "context"
    "log"
    "log/slog"

    "github.com/go-jappe/heterolog"
)

func main() {
    ctx := context.Background()
    runtime, err := heterolog.New(ctx, heterolog.DefaultConfig())
    if err != nil {
        log.Fatal(err)
    }
    defer func() {
        if err := runtime.Close(); err != nil {
            log.Print(err)
        }
    }()

    logger := slog.New(heterolog.NewSlogHandler(runtime, nil))
    logger.InfoContext(ctx, "service started", "service", "example")
    logger.With("component", "worker").WithGroup("job").InfoContext(ctx,
        "job completed", "id", 42)
}

By default, INFO and higher are written to stdout and WARN and higher to stderr. Timestamps are in UTC. To replace the global slog logger, call slog.SetDefault(logger) in your application.

Writing logs

Errors from logging calls

The regular API returns errors from log processing.

jobID := heterolog.MustFieldKey("job_id")
err := runtime.Info(ctx, "job completed", jobID.Int(42))
Field values
  • Any(key, value) keeps the value as JSON when the field is created.
  • A value that cannot be converted to JSON, or whose arrays and objects are nested deeper than MaxFieldNestingDepth (9000 levels), makes field creation return ErrFieldValueNotJSON. This limit is the depth that can still be stored and replayed after the spool and each destination's format add their own outer levels.
  • The same limit applies to slog attributes. A record that exceeds it is not written, and Handle returns an error.
  • An ErrFieldValueNotJSON error includes the reason the value could not be converted (such as the error returned by MarshalJSON) in its message only. Because that reason can contain the value being logged, it cannot be retrieved with errors.Is or errors.As.
Metadata keys
  • request_id, trace_id, and span_id are treated as log metadata when their values are strings.
  • Numbers, booleans, objects, and other values keep their type and are stored as regular structured fields.
  • When the same key is given more than once, only the last value is used, and it is classified by its type.
  • These rules also apply to top-level slog attributes.
Stack traces
  • ErrorWithStack(ctx, message, err, fields...) records the application's stack at the call.
  • The caller is kept even when the log is processed asynchronously, and the stack is shown according to each destination's ErrorTraceDepth. Depth 0 shows only the call site; depth N shows N parent frames above it. Debug mode uses ErrorTraceDepthDebugMode.
  • A nil err is not rejected; the log is recorded as an ERROR log without error details, together with the stack.
Using slog
  • slog.Logger does not return the result of Handler.Handle to the caller. Use the regular API to check errors from a call, and NewDelivery to check delivery for each destination.
  • A successful call of the regular API can mean that the log was accepted into a buffer; it does not guarantee final delivery.
  • slog and each backend have their own level filters. To write DEBUG logs, set both:
cfg := heterolog.DefaultConfig()
cfg.Stdout.RuntimeConfig.LogLevel = heterolog.LevelDebug
runtime, err := heterolog.New(ctx, cfg)
// Check err before using runtime.
logger := slog.New(heterolog.NewSlogHandler(runtime, &slog.HandlerOptions{
    Level: slog.LevelDebug,
    AddSource: true,
}))
  • WithAttrs, WithGroup, LogValuer, LevelVar, and ReplaceAttr are supported.
  • slog attributes are normalized to JSON-equivalent values and stored as structured fields. When a key appears more than once, the later value is used.
  • Replacing or removing the message with ReplaceAttr also changes the message sent to backends. A removed message becomes an empty string, and a message replaced by a non-string value becomes its JSON representation. The level and time of the original record are kept.

Loggers and shutdown

APIs
API Purpose
DefaultConfig / New Synchronous API. Returns processing results as errors (a drop caused by overload is ErrLogDropped)
DefaultAsyncConfig / NewAsync Asynchronous best-effort logging
DefaultDeliveryConfig / NewDelivery Returns the delivery result for each destination (ClickHouse reports acceptance into its queue as DeliveryEnqueued)
NewSlogHandler Uses a synchronous logger as a slog.Handler
DefaultSpoolConfig / WithSpool Settings for the workers that replay persisted failed logs
Close / Shutdown(ctx) Finishes accepted work, flushes buffers, and releases resources
ForceClose Stops accepting logs, releases waiting Close and Shutdown calls with ErrForcedClose, and requests background and recovery work to stop without waiting
Delivery reports

Each destination in a report has one of these statuses:

Status Meaning
DeliverySucceeded The destination confirmed success
DeliveryFailed The destination explicitly rejected the log
DeliveryRejected The log was rejected before sending, for example by input validation
DeliveryUnconfirmed The result cannot be confirmed, for example because the response was missing or could not be parsed
DeliveryEnqueued Only acceptance into the send queue is reported
  • ClickHouse is designed for batch inserts, so even the delivery API returns DeliveryEnqueued as soon as the log is accepted into the queue, without waiting for the send. The send happens when the count, size, or FlushInterval threshold is reached, or at Close, and its result is not reflected in the returned report.
  • HasTargetFailure() counts only confirmed failures and rejections before sending. To stop on unconfirmed results as well, use HasUnregisteredTarget(). DeliveryEnqueued is treated as unconfirmed, so HasUnregisteredTarget() is true for a report that includes ClickHouse.
  • Saving a log to fallback storage is independent of success at the destination.
  • For a report without any destination result, HasTargetFailure() and HasAnyFailure() are true, just as Error() returns ErrNoDeliveryTargets. A configuration without outputs is rejected at construction, so such a report can only come from an internal inconsistency.
  • The Backend of a destination result is the name of a pkg/logger.LogOutputDestination (stdout, file, slack, opensearch, loki, cloudwatchlogs, clickhouse), whether the destination returned the result or the logger created it on its behalf (a handler panic or deadline, or a rejection before sending because Close had started or a single entry exceeded the limit).
  • When a panic in a delivery handler is recovered, destinations that did not return a result are DeliveryUnconfirmed. Confirmed results of other destinations are kept.
  • CloudWatch Logs send errors keep the original cause in the returned error and in the destination's Err, and can be identified with errors.Is and errors.As.
Errors and dropped logs
  • With the regular API of OpenSearch, Loki, ClickHouse, and CloudWatch Logs, when a log that failed to send could not be persisted (including when no fallback is configured), the returned error contains both the persistence error and the destination's original cause, which can be identified with errors.Is and errors.As. For ClickHouse, the error is returned by the logging call that ran the flush, or by Close.
  • When a log that failed to send is discarded because its storage (spool or failure archive) is overloaded and the overload policy is drop (the default), the regular API returns an error that wraps heterolog.ErrLogDropped; check it with errors.Is(err, heterolog.ErrLogDropped). The same error also contains the destination's original cause.
  • When a buffered log is discarded by a later flush, the logging call that ran the flush, or Close, returns the error.
  • When the log is saved by degrade, no error is returned.
  • Logging calls of the asynchronous API do not return errors. If logs are discarded in the final flush of Close, Close returns the error.
  • With the delivery API, check DeliveryReport.HasDrop().
  • The number of discarded logs can also be observed with the logger_failure_overload_drop_total metric.
Shutdown
  • Always call Close or Shutdown when the application exits.
  • When the context of Shutdown ends, only that call stops waiting; the cleanup continues. Call Close or Shutdown again to wait for it to finish.
  • Unsent data in the spool may remain for the next replay. There is no separate Flush API.
  • While compression or upload of log files keeps failing, Close does not return until that work completes. If you need an upper bound on shutdown time, stop waiting with the deadline of Shutdown(ctx), and stop the cleanup with ForceClose if needed.
  • Close and Shutdown wait for accepted sends and for the internal log notifications they cause (writes to the targets selected with OnErrorConfig and the like), including flushes that started inside logging calls because a count or size threshold was reached.
  • When a panic is recovered while closing a destination, the other destinations are still closed, and incomplete closing is retried. A destination that is already closed is not closed again.

Configuration

Configuration types
  • Config, AsyncConfig, and DeliveryConfig are the public configuration types of pkg/logger. The destinations are stdout, file, Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse. See go doc github.com/go-jappe/heterolog/pkg/logger for the details of each setting.
  • For synchronous and asynchronous configurations that use a spool, also pass WithSpool.
  • A configuration without any regular output is rejected by New, NewAsync, and NewDelivery before construction, with an error that contains ErrNoActiveLogOutput of pkg/logger (check it with errors.Is).
  • When LogOutputDestinations is empty, every non-nil backend configuration becomes a regular output. Storage or client settings used only for internal logs do not make a destination an output.
Construction errors

Configuration errors at construction can be identified with errors.Is and errors.As:

  • A nil context: ErrNilContext.
  • A Timeout of 0 or less, and a MaxParallel of 0 or less for NewAsync: pkg/logger.ConfigFieldError with Field set to heterolog.ConfigFieldTimeout or heterolog.ConfigFieldMaxParallel and the kind ErrNonPositiveSetting.
  • WithSpool passed to NewDelivery: ErrDeliverySpoolUnsupported.
  • An unsupported value of WithCloudWatchLogsStreamRouting: ErrInvalidStreamRouting (*InvalidStreamRoutingError).
  • A context that has already ended: its error, such as context.Canceled.
  • A destination selected as an internal log notification target (OnErrorConfig and the like) whose settings cannot create a notification writer (an invalid TimeZone, an empty LogLineDateFormat, and so on): ErrInvalidNotificationTarget (*NotificationTargetError, where Source is the kind of logger, Backend is the target, and Err is the cause).
  • Invalid presentation settings or backend values (buffers, send limits, retry settings, and so on): pkg/logger.ConfigFieldError with Source, Backend, and Field (and Value and Limit for checks against a value). The kind is a sentinel such as ErrNonPositiveSetting that can be checked with errors.Is.
  • Invalid client settings: Field is ConfigFieldClient and the kind is ErrInvalidClientConfig. The reason is a sentinel of each backend package (for example, pkg/loki.ErrEndpointRequired) that can be checked with errors.Is.
  • An endpoint that cannot be parsed as a URL: the error message and the *url.Error in the error tree contain only the URL with its user info (user name and password) replaced by xxxxx.
  • A handler selector that cannot be resolved: pkg/logger.HandlerSelectorError.
  • An invalid element of Slack's Intervals: its position is in Index of pkg/logger.SlackIntervalError, which can be retrieved with errors.As.
  • The policy for running out of disk space while writing a file: a policy other than drop or degrade is pkg/fsstore.ErrUnsupportedOverloadPolicy, and a degrade destination other than stdout is pkg/fsstore.ErrUnsupportedSpillDestination (check them with errors.Is).
Side effects and contexts
  • Importing the package or calling New does not load .env files, install signal handlers, start servers, or change the global logger or OpenTelemetry providers. Configuration is passed explicitly in code (to build loggers from environment variables and an env file, call LoadEnvConfig explicitly, as described below).
  • Do not change the configuration a logger uses after creating the logger.
  • The cancellation and deadline of the context passed to New, NewAsync, and NewDelivery apply only to construction. Periodic sending of buffers continues after the context ends, until Close or Shutdown.
Configuring from environment variables

LoadEnvConfig reads settings from environment variables that start with HETEROLOG_ and from the env file given as its argument. Except for the AWS standard variables used as defaults (such as AWS_ACCESS_KEY_ID), every key starts with HETEROLOG_, so the settings can share the environment variables and file with the application's own settings. The keys and their defaults are listed in .env.example. With no settings, all three loggers write to stdout only. The recovery CLI reads the same keys.

env, err := heterolog.LoadEnvConfig(".env") // "" reads only environment variables
if err != nil {
    log.Fatal(err)
}
runtime, err := env.New(ctx) // NewAsync and NewDelivery work the same way
if err != nil {
    log.Fatal(err)
}
defer runtime.Close()
  • The process environment is not modified. When a key is in both the environment and the file, the environment value is used.
  • No other file is read (neither HETEROLOG_ENV_PATH nor .env in the current directory).
  • The settings of the enabled loggers and their consistency with each other (such as shared storage directories) are checked when loading, and all problems found are returned together. Use errors.As with EnvFileError, InvalidEnvironmentValueError, RenamedEnvironmentKeyError, or VariableError of pkg/env to identify the key.
  • To adjust the settings before constructing a logger, get them with cfg, opts, err := env.Config() (or AsyncConfig and DeliveryConfig) and pass them to heterolog.New(ctx, cfg, opts...). opts carries the spool replay settings and CloudWatch Logs stream routing read from the environment.
  • A logger disabled with HETEROLOG_ENABLE_LOGGING=false or the like cannot be constructed, and ErrEnvLoggerDisabled is returned.
  • Tracing (WithObservers) is not created from the environment. Pass it as an additional option, as in env.New(ctx, opts...). A spool enabled with HETEROLOG_USE_MEMORY_PRESSURE_* judges memory pressure with HETEROLOG_MEMORY_CRITICAL_RATIO, HETEROLOG_MIN_AVAILABLE_MEMORY_BYTES_MB and HETEROLOG_MEMORY_CRITICAL_CONSECUTIVE_HITS unless WithMemoryPressureMonitor is passed.
Changing settings while running

The level and sampling of each output of a synchronous or asynchronous logger can change while the application runs, in code or through an HTTP API.

  • In code, runtime.OutputSettings() returns the current settings, and runtime.UpdateOutputSettings(changes) changes them. All changes are checked first, and none is applied if any is invalid: an output the logger does not use is ErrUnknownOutput, and an invalid value is a ConfigFieldError of pkg/logger.
  • Changes take effect from the next entry. An asynchronous logger uses the settings in effect when it processes an entry.
  • Changes are kept in memory only, so a restart returns to the configured settings.
  • Delivery loggers have no such settings: they do not sample, and only their Slack output filters by level, at its configured level. Outputs used only for internal log notifications keep their configured settings.

The HTTP API (admin API) can be called with tools such as curl:

  • NewAdminHandler returns an http.Handler to mount on your own server. StartAdminServer starts a dedicated server instead.
  • GET /settings returns the current settings of every logger, and PATCH /settings changes the fields given in the JSON body. Levels are DEBUG, INFO, WARN, and ERROR (case-insensitive), and sampling fields omitted in a PATCH keep their values.
  • Every request must send Authorization: Bearer <token>. The token must be at least 32 bytes (MinAdminTokenLength); generate it randomly, for example with openssl rand -hex 32. It is compared in constant time, and errors never contain it.
  • A PATCH checks every change of every logger before applying any of them. The body is limited to 64 KiB, and unknown fields are rejected.
  • Each change is passed to OnChange for audit logs. Without OnChange, it is written as one line to the standard logger of the log package.
  • The dedicated server listens on 127.0.0.1 when the host of its address is empty (for example, :9100). To listen on another address, give the host explicitly and set a TLS certificate and key, so the token is not sent over a network in clear text.
  • From the environment configuration, HETEROLOG_ADMIN_ADDR enables the server, together with HETEROLOG_ADMIN_TOKEN, HETEROLOG_ADMIN_TLS_CERT_FILE, and HETEROLOG_ADMIN_TLS_KEY_FILE. LoadEnvConfig checks them, and env.AdminServerConfig() returns them.
env, err := heterolog.LoadEnvConfig(".env")
if err != nil {
    log.Fatal(err)
}
runtime, err := env.New(ctx)
if err != nil {
    log.Fatal(err)
}
defer runtime.Close()
if adminCfg, ok := env.AdminServerConfig(); ok {
    admin, err := heterolog.StartAdminServer(adminCfg, map[string]heterolog.SettingsController{"app": runtime})
    if err != nil {
        log.Fatal(err)
    }
    defer admin.Close()
}
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/settings

curl -X PATCH -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" \
  -d '{"loggers":{"app":{"outputs":{"stdout":{"level":"DEBUG"}}}}}' \
  http://127.0.0.1:9100/settings

Both requests return the settings of every logger:

{
  "loggers": {
    "app": {
      "outputs": {
        "stdout": {
          "level": "DEBUG",
          "sampling": {
            "enabled": false,
            "by_request_id": false,
            "request_id_rate": 0,
            "debug_rate": 0,
            "info_rate": 0,
            "warn_rate": 0,
            "error_rate": 0
          }
        }
      }
    }
  }
}
Memory pressure monitor
  • The caller starts and stops the monitor passed to WithMemoryPressureMonitor.
  • Without WithMemoryPressureMonitor, each spool that enables UseMemoryPressureForOverload starts its own monitor. It reads the memory of the operating system every second, judges each reading with the spool's MemoryCriticalRatio, MinAvailableMemoryBytes and MemoryCriticalConsecutiveHits (HETEROLOG_MEMORY_CRITICAL_RATIO, HETEROLOG_MIN_AVAILABLE_MEMORY_BYTES_MB and HETEROLOG_MEMORY_CRITICAL_CONSECUTIVE_HITS in the environment), and stops when the logger closes. The logger fails to start when they enable no threshold or the memory cannot be read.
  • NewMemoryPressureMonitor(provider, policy, pollInterval) creates a monitor from a Provider and a CriticalPolicy of pkg/memorypressure.
  • Start(ctx) reads once before returning, then reads every pollInterval, and stops when ctx ends.
  • The evaluation is the same as memorypressure.CriticalState: the state is critical when reliable observations reach CriticalRatio or MinAvailableBytes ConsecutiveCriticalHits times in a row (0 and 1 mean the first time).
  • A nil provider, a poll interval of 0 or less, a policy that enables neither threshold, a CriticalRatio above 1, or a negative count is an error at creation. Input errors at creation can be identified with errors.Is(err, heterolog.ErrInvalidMemoryPressureMonitor).
  • The monitor, passed or started by the spool, is used for the overload decision of destinations whose spool enables UseMemoryPressureForOverload. When it reports overload, the overload policy applies; with drop, the log is discarded without being saved, and the regular API returns ErrLogDropped.
  • The Linux provider of pkg/memorypressure checks the limits of its cgroup v2 and of the parent levels it can read. It keeps the level with the highest usage as the main observation and the level with the least remaining memory as CgroupLimit, and checks both. When only a finite limit can be read, the usage is kept as unknown. Limits of ancestors it cannot read, such as those outside its namespace, cannot be obtained.
Internal log notifications
  • Notification targets (OnErrorConfig, OnWarnConfig, OnInfoConfig, and OnDebugConfig of HandlerConfig) use write paths dedicated to notifications.
    • file writes through a path that does not notify the file logger's internal logs.
    • stdout, slack, opensearch, loki, cloudwatchlogs, and clickhouse use notification loggers created separately from the regular outputs.
    • Failures of these writes are not notified; each failure is written as one line to the standard logger.
  • The settings of a destination selected as a notification target are checked when New, NewAsync, or NewDelivery constructs the logger, before any storage is created, not at the first notification.
    • Settings that cannot create a notification writer are a configuration error at construction (ErrInvalidNotificationTarget); a notification is never discarded at the time it is sent.
    • The settings of destinations that are not selected as notification targets are not part of this check.
    • For a file target, the time display settings (time zone and date format) are checked at construction, and errors are configuration errors at construction.
  • The log file of a file target is created at the first notification. When creation fails, each failed notification is written as one line to the standard logger, and creation is retried at the next notification.
  • Notifications do not loop, even when a logger selects itself as a target (for example, file in the OnErrorConfig of a file logger).
  • Even if a regular write to the same logger happens inside the processing of a notification, the internal logs of that write (delays, failures, overload, and so on) do not call the notification target again. They are written directly to the output of that logger: the same log file for file, stdout or stderr for stdout, and the same destination for Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse. These direct writes still use the logger's log level (file also applies its overload handling), and their failures are not notified.
  • Batching loggers and the Slack logger send internal log notifications after releasing their locks, and the asynchronous API (NewAsync) processes writes from inside a notification without waiting even when all of its slots are busy, so writing to the same logger from a notification does not hang.

Log files

Rotation
  • If the file to rotate to cannot be opened, that write returns an error. Existing logs are kept, and rotation is retried at the next write after the problem is resolved.
  • If closing the file before rotation returns an error, that write also returns an error. That file is not reused, and the next write opens a new file to complete the rotation.
  • Rotation does not write diagnostic strings directly to stdout. This holds even when file is the only output, and it is the same for the regular, asynchronous, and delivery APIs.
Storage paths and ownership
  • Valid whitespace in storage paths is kept as is.
  • Ownership of storage is decided on the actual paths. A configuration in which different loggers own the same directory, or a directory and its parent, at the same time is rejected.
Case sensitivity
  • Matching of log file names follows whether the file system of the storage directory is case-sensitive.
  • On Windows, on case-insensitive macOS volumes, and in Linux directories confirmed to be case-insensitive, names that differ only in the case of the prefix, target, or extension are treated as the same file. This is used to choose generation numbers at rotation, to find files to compress, upload, and delete, and to identify the series of upload records (checkpoints).
  • When a target name is added to a storage path such as a failure archive, whether a level already has the same name is decided by the case rule of each directory. On a case-insensitive volume, names that differ only in case are the same directory, and the target is not added twice.
  • On Linux, these directories are treated as case-insensitive:
    • Directories with the casefold attribute (casefold of ext4, F2FS, and tmpfs).
    • Directories on FAT (vfat, msdos) and exFAT file systems, but only when /proc/self/mountinfo confirms that no case-sensitive mount option is set (check=s [strict] of vfat, nocase of msdos, namecase=1 of the staging exFAT driver of Linux 5.4 to 5.6). When this cannot be confirmed, they are treated as case-sensitive.
  • The detection only reads the file system type, attributes, and mount information; it creates no files to probe.
  • A directory on ext4, F2FS, or tmpfs that cannot be read is treated as case-sensitive, because its casefold attribute cannot be checked.
  • Changes of mounts or casefold attributes may take up to 2 seconds to take effect.
  • SMB/CIFS, NFS, NTFS (ntfs3, ntfs-3g), FUSE (including exfat-fuse), 9p (such as Windows drives in WSL2), ZFS, and similar file systems are treated as case-sensitive, because their handling of case depends on the server or mount options and cannot be checked from outside. If such a mount is case-insensitive, do not use settings that differ only in case.
  • When checking compressed log names of regular and internal logs for collisions, names that differ only in case are rejected as collisions if either the storage of the original logs or the fallback storage for failed uploads is case-insensitive.
macOS AppleDouble files
  • On file systems that cannot store extended attributes (such as FAT32 and ExFAT), macOS stores the extended attributes of a file or directory in a file named ._ + the name in the same directory (AppleDouble).
  • On macOS, a ._ file whose counterpart name exists in the same directory is not treated as a log, spool, or failure archive file, and is excluded from size calculations, sending, and deletion. A ._ file without a counterpart is treated as a regular file.
  • ExFAT on macOS 26 does not support renaming without replacing an existing file, so it cannot be used for the storage of spools and failure archives. Saving there fails with an error without overwriting existing files.
Retention
  • The number of kept generations (such as HETEROLOG_MAX_LOG_FILE_BACKUPS) is counted in generations, which are determined by the date and number in the file name.
  • Uncompressed and compressed files of the same generation, including those created before the compression format was changed, count as one generation, and all files of older generations beyond the limit are deleted together.
  • Files that cannot be deleted, such as a file being written or a file whose sending or fallback is not finished, are not counted.
  • In the runner mode of the delivery logger, MaxFileBackups, MaxFileAge, and MaxDirSize given in LifecycleRunnerSettings are checked with the same lower bounds as the regular file logger (at least 2 generations, at least 1 day, and at least 10 MB and at least the maximum file size). Invalid values make logger construction fail even when error and debug separation is disabled.
Compression
  • Compressed files are checked for integrity before they are used for recovery. For XZ, the index and footer of each stream and the end positions of blocks are checked, so the original log is kept and can be compressed again even if a truncated compressed file remains.
  • When a compressed file of the same generation as an original log remains, for the built-in formats (gzip, zstd, lz4, xz) it is decompressed to the end and compared with the original log, and the original log is deleted only when they match.
  • When a compressed file is complete but its content differs, the original log is not deleted; it is moved to .preserved in the log directory and reported as an error, and the compressed file is treated as the file of that generation.
  • Compressed files of a custom codec (CompressionCodec) are not compared even when the codec has a method for decompression; only the codec's own integrity check runs.
  • When compressing anew with a built-in format, the temporary file is decompressed to the end before it is published and compared with the original log. If they do not match, the compressed file is not published and the original log is not deleted (it is compressed again in the next run). A custom codec still uses only its own integrity check.
  • When a damaged compressed file is found while compressing right after rotation or resuming interrupted work, the original log is kept, the damaged file is deleted, and the original log is compressed again, so shutdown never keeps waiting for the same failure to be retried.
  • On POSIX systems, compressed output is created with permissions no broader than those of the source file. Existing temporary outputs and additional restrictions from the umask are kept.
  • On Windows, before compressed data is written, the existing private-file policy is applied, which allows access only to the current user, SYSTEM, and Administrators.
Uploading to object storage
  • When a destination is added to the object storage upload of log files, log files that existed before the destination was added are not sent to it and are not treated as sent.
  • The exception is the newest file being written in the current rotation period (uncompressed): it keeps growing after the destination is added, so it is included for the new destination. Uncompressed files of past periods are excluded like other files from before the addition, even if they are the newest.
  • Adding a destination is never a reason to delete files; they are deleted by the usual retention period, generation count, and size settings.
  • A compressed file is deleted after upload only when it has been sent to at least one enabled destination (or, on failure, saved to every specified fallback), and every other enabled destination is confirmed to have it sent or to have excluded it as a file from before the addition.
  • For object storage sending of a failure archive (fileArchive), newer generations wait until the sending of older generations completes, and are sent as soon as the completion record of an older generation advances.
Restarts
  • At startup, log file writers (regular, delivery, and the fileArchive for backend send failures) treat as used not only the files left in storage but also the generations recorded in the checkpoints of the same series (completion positions of sending and fallback, and records of sending in progress), and write from the following numbers.
  • So even after a restart that follows manual recovery up to the newest file, or after only the log storage was lost, new logs never get the same name as a generation already sent, which would get them deleted without being sent or make them overwrite the same object in object storage.
  • When the system clock goes back before a recorded period, writing continues in the recorded period.

Failure handling and replay

Spool permissions
  • The spool for failed logs (OpenSearch, Loki, ClickHouse, CloudWatch Logs) creates its root and the directories below it with 0700, accessible only to the owner, and saves spool files with 0600. Additional restrictions from the umask are kept.
  • Existing directories created by older versions with broader permissions also lose their group and other permissions, from the root down to the storage directory. The user's directories above the root are not changed.
  • Missing directories above the root are created with 0755 (with the umask applied) as before, because they are shared with other storage such as the object storage spool.
  • On Windows, newly created directories get an ACL that allows only the current user, SYSTEM, and Administrators, and spool files inherit this ACL when created. The ACLs of existing directories are not changed, so review the ACLs of spool directories created by older versions if needed.
How failures are classified

Saving to the spool (OpenSearch, Loki, ClickHouse, CloudWatch Logs) and replaying from it follow the same rules for regular sending and spool replay:

  • Temporary failures are replayed automatically: 408, 429, 5xx, known network failures such as connection failures and timeouts, sends suppressed by the circuit breaker, and Loki's 260.
  • When the result cannot be confirmed (a missing or unparseable response, an interruption during sending, a send error that cannot be classified), the log is moved to quarantine and is not replayed automatically until its content and delivery status have been checked.
  • Size errors such as HTTP 413, and rejections caused by the content of a log (such as OpenSearch mapping and parsing errors, or ClickHouse value parsing and type conversion errors), are handled by splitting a multi-entry send or resending entries one by one to find the logs that cause them; every log rejected on its own is saved to quarantine.
  • Loki's 400 may mean that valid streams were partly accepted, so the logs sent are saved to quarantine without splitting.
  • Problems with the destination or configuration that do not depend on the log content (rejected authentication or permissions, a missing table, index, or stream, wrong SQL or settings) make the logs undeliverable, and they are saved to dead.
  • Events that CloudWatch Logs rejects individually as outside the accepted period are replayed if they are too far in the future, and saved to dead if they are too old or outside the retention period.
  • Replaying can deliver a log twice if an earlier attempt was accepted.
  • When the circuit breaker tries whether it can resume sending, it lifts the suppression only when a response from the destination is confirmed. If the client returns neither a response nor an error, the result is unknown and sending stays suppressed.
  • When a spool record cannot be restored or validated at replay, it is moved to quarantine. The error can be identified by its kind (sentinel) and field name, but the stored value is not included in errors that can be retrieved with errors.As (causes or fields).
Retry-After
  • When an OpenSearch, Loki, ClickHouse, or CloudWatch Logs destination returns Retry-After with a retryable failure, the spool does not replay to that destination until the given time has passed since the response was received.
  • The value, whether received during spool replay or regular sending, is recorded as a waiting deadline for the whole destination, and none of that destination's logs, including older logs without a deadline, are sent before it.
  • A value received during regular sending is recorded when the failed log is saved to the spool (including when the log is not saved to the spool because of a drop or degrade on overload), so a running runner applies it from its next cycle.
  • A value received during spool replay also stops the logs of the same replay that were not sent yet.
  • A new value does not shorten a later deadline already recorded.
  • Replay to other destinations, deletion of spool files by retention period and size, and retries of post-processing continue.
  • The maximum wait is 1 hour by default and can be changed with Worker.MaxRetryAfter for each backend (environment variables *_SPOOL_RUNNER_MAX_RETRY_AFTER_SECOND, such as HETEROLOG_OPENSEARCH_SPOOL_RUNNER_MAX_RETRY_AFTER_SECOND). A longer value is shortened to the maximum, with a warning to the internal log.
  • If the value is shorter than the replay cycle, replay happens at the usual cycle.
  • Client retries within a single send wait up to MaxDelay, for both regular sending and spool replay.

How the deadline survives restarts:

  • The deadline is saved as .retry-after/<backend name>.json (for example, opensearch.json) in the spool directory (<SpoolPath>/<Target>/spool/<Dir>) and loaded before the first replay after a restart, so the destination is not replayed before the deadline regardless of the order in which logs are loaded.
  • The given time is also saved in the logs waiting for replay. If the deadline could not be saved, it is restored when such a log is loaded.
  • A log or deadline whose saved time is further away than the maximum at loading is shortened to the maximum, with a warning to the internal log. The shortened deadline is saved too, so restarts do not extend the wait.
  • Records past their deadline are deleted (a record shortened to the maximum is kept until its original time passes, to show that it was shortened).
  • Temporary files left by a stop in the middle of saving (.<backend name>.json.<digits>.tmp) are deleted at the next load.
  • When a record cannot be read or its content is broken, a warning is written to the internal log, replay continues as if there were no record, and the next Retry-After replaces it.
  • When saving a record fails, a warning is written to the internal log (only once while failures continue), and the process waits until the deadline while retrying the save until the deadline arrives. The retry interval starts at the replay cycle and doubles at each failure, up to 1 minute. If the process restarts before the record could be saved, the deadline may not be carried over.
Compressed log uploads
  • The spool that resends compressed log files to object storage sends the file again to the same destination and object name as when it was saved. So even for send errors that cannot be classified and for panics in the upload, the file is not moved to quarantine; it is returned to waiting and resent automatically. It is moved to dead only when the destination's response shows a permanent rejection.
  • When the destination of compressed log files returns Retry-After, only the files for that destination wait until the given time; resending to other destinations continues.
  • A value received with a temporary failure by a regular upload before the file is saved to the spool is also recorded as that destination's waiting deadline when the file is saved, so a running resend process applies it from its next cycle and does not send files to that destination before the deadline.
  • A new value does not shorten a later deadline already recorded.
  • The maximum wait is 1 hour by default and can be changed with HETEROLOG_OBJECT_STORAGE_COMPRESSED_LOG_FILE_UPLOAD_FAILURE_SPOOL_MAX_RETRY_AFTER_SECOND (the setting of the same name starting with DELIVERY_ for the delivery logger). A longer value is shortened to the maximum, with a warning.
  • The deadline is saved as .retry-after/<destination ID>.json in the spool directory of the destination (<SpoolPath>/<Target>/spool/objectstorage/<service>/<logger contract>/<destination ID>/.retry-after/<destination ID>.json) and loaded before the first send to that destination after a restart, so files for that destination are not sent before the deadline.
  • The destination ID is used for the names of the per-destination spool and file archive directories and of .retry-after/<destination ID>.json, so it must start with a lowercase letter or digit, consist only of lowercase letters, digits, hyphens, and underscores, be at most 128 characters long, and not be a reserved Windows device name (con, prn, aux, nul, com0 to com9, lpt0 to lpt9). S3 destination IDs (s3- followed by 64 hexadecimal digits of SHA-256) always follow this rule.
  • In a configuration that uses storage for failed uploads (a spool or a file archive), a destination ID that breaks the rule makes logger construction return a configuration error without creating any storage.
  • A time further away than the maximum at loading is shortened to the maximum and saved again, with a warning, so restarts do not extend the wait.
  • Records past their deadline and temporary files left by a stop in the middle of saving (.<destination ID>.json.<digits>.tmp) are deleted.
  • When a record cannot be read or its content is broken, a warning is reported, resending continues as if there were no record, and the next Retry-After replaces it.
  • When saving a record fails, a warning is reported (only once while failures continue), and the process waits until the deadline while retrying the save until the deadline arrives. The retry interval starts at the resend cycle and doubles at each failure, up to 1 minute. If the process restarts before the record could be saved, the deadline may not be carried over.
Durability and cancellation
  • Restoring the OpenSearch and ClickHouse spools keeps the precision of JSON numbers. Large integers and high-precision decimals are not converted to float64 for replay, and saved document IDs and deduplication tokens are kept.
  • When appending to a fileArchive fails in the middle, the file is rolled back to the position before the append. While it cannot be recovered, later saves and rotation stop with an error, and recovery is retried at the next save. If the end of an existing file is incomplete at a restart, opening it is refused with its content kept, so the file needs to be checked and repaired.
  • When regular sending to OpenSearch, Loki, ClickHouse, or CloudWatch Logs times out or is canceled, saving the failed logs is still attempted with its own deadline.
  • For both regular sending and spool replay, logs whose result became unknown because the caller's deadline or cancellation interrupted the send go to quarantine, logs not sent yet are kept for replay, and logs whose success is confirmed are not added again. When an explicit response was received, its result is kept.
  • With CloudWatch Logs, even if saving a failed batch fails in the middle, later sends and saves continue while the send context is valid, and the errors of each step are returned together.
  • The status and Retry-After of an HTTP response are not overridden by words in the response body that look like a network failure.
  • A Retry-After too large to be represented as a wait does not cause an immediate resend; it is treated as the maximum value, and then wait limits such as MaxDelay apply.
  • Connection resets, aborts, and refusals are detected by error number, not by error messages that differ between operating systems, so they are retried as temporary disconnections on Windows too.
  • Backend-specific error types are classified by the retry rules of each service.
  • When a send is canceled while waiting for the next attempt after an HTTP rejection, both the confirmed response and the cause of the cancellation are kept. Temporary rejections such as 503 are saved for replay, and logs with an unknown result, such as those interrupted during sending, go to quarantine.
  • When an OpenSearch ingest pipeline intentionally drops a log and responds with noop, the log is treated as processed. The other logs of the same batch are judged by their own responses.
  • When deleting the original processing file fails after saving to done, dead, or quarantine, the saved content is compared at the next start, and only the original file is deleted if every entry is confirmed saved in a single state. A partial save, a split across several states, or mismatching content keeps the file, returns an error, and stops automatic replay. The saved files needed for this check are protected from deletion by retention period and size while their original file remains.
  • Saving replay results is complete only after the file and its storage directory are synced. If syncing fails after publishing, the saved file and the original processing file are kept, and at the retry the content is compared and the sync is redone. Existing results are not overwritten, and the time of the first confirmation is kept.
  • When post-processing of the spool fails, the RetryDelay of the state transition is counted from when the failure was found, so the configured wait before the next retry is kept even when a file operation took a long time.
  • The spool for regular logs reports a successful save only after the file and its storage directory are confirmed to be synced. If syncing fails after publishing, the saved file is kept. Saving the same log again after this error stores it in another file to avoid losing it, so it may be duplicated.
  • When the storage directory of a spool, fileArchive, or checkpoint is newly created, success is reported only after the parent directory is confirmed to be synced. If syncing the parent fails, ErrDurabilityUnconfirmed is returned, and the sync is retried each time the same process prepares storage that depends on that parent. Until it succeeds, the same error is returned even for directories already created.
  • The spool's size statistics are updated even when StatsScanInterval is 0 or less. The first scan runs synchronously, and later results of asynchronous rescans are used for the size decision. MaxCallsSinceScan=0 disables only the update based on the number of calls.
Timeout budget
  • The timeout budget check of must_fit includes waits for Retry-After up to MaxDelay, also for regular retries of Loki and ClickHouse.
  • When timeout and retry settings of loggers and clients are omitted in the environment configuration, the defaults are the same as the values in .env.example and satisfy the default must_fit (18 seconds for the regular and asynchronous loggers, 12 seconds for the delivery logger, 1 second for the OpenSearch client, and 2 seconds for the Loki, ClickHouse, and CloudWatch Logs clients).
  • The recovery CLI, which reads the environment configuration, checks the whole configuration including this budget before starting recovery, and exits with a configuration error if it is not satisfied.

Destination notes

Slack
  • MaxRestThreshold is the idle time between arriving logs. When a log arrives after this time has passed, an immediate send is scheduled together with the waiting logs. If a notification is being sent, it waits for that send to complete.
  • The HTTPClient of SlackLoggerConfig and DeliverySlackLoggerConfig in pkg/logger accepts the *http.Client used to call the Slack API (for example, to use a proxy or a custom transport). When it is nil, the default transport of net/http is used.
    • The given client is copied at construction, keeping Transport, Jar, and CheckRedirect. The original client is not modified, and changes after construction are not reflected.
    • The timeout is the Timeout of each configuration (it must be positive), which takes precedence over the Timeout of the original client.
    • The same client is used for internal logs sent with the same Slack settings.
    • It cannot be set from the environment configuration, so Slack output enabled there uses the default transport.
  • The Slack backend reports DeliveryRejected when the delivery context ended before sending, and DeliveryUnconfirmed for network failures after sending or incomplete responses.
  • The public delivery API uses a delivery deadline that is independent of the caller's cancellation.
  • Success is decided by validating the whole response body.
  • Slack has no durable storage or quarantine for failed logs, so if you need to keep logs with an unconfirmed delivery result, handle that in the caller.
  • For regular and asynchronous Slack sending, batches whose response body could not be validated, and whose result is therefore unknown, are resent as well. Duplicates are preferred over losses, so the same notification may be posted twice.
CloudWatch Logs
  • Stream names after routing (splitting into streams) are checked for the regular and internal log settings actually used. Base settings not selected as outputs, and base settings replaced by settings dedicated to internal logs, are excluded from the check.
  • The size limit is decided by the message length after JSON encoding plus the per-event overhead (26 bytes), and a single message is sent up to 1,048,550 bytes. A log that exceeds the limit is excluded from sending without stopping the other logs of the same batch.
  • When the endpoint URL is omitted, the standard endpoint of the region is used. China regions use amazonaws.com.cn. An explicit URL takes precedence.
  • With automatic stream creation, when a send is rejected because the stream does not exist, logs that were not accepted are saved for replay even if creation is canceled. A permanent rejection by the create API is treated as undeliverable, and if the result of resending after creation is unknown, the logs go to quarantine.
  • When obtaining credentials or signing fails and the HTTP request of the logs is confirmed not to have been sent, the logs are kept for replay. The original cause can be retrieved with errors.Is and errors.As.
Loki
  • The line limit is decided by the UTF-8 byte length of the string as sent. Invalid UTF-8 is replaced as Go's JSON encoding does, and splitting and exclusion use the length after replacement.
OpenSearch
  • When sending a single document, the index name is encoded as a single URL path element. Special characters in date math such as <logs-{now/d}> and in time zone specifications are kept.
Endpoint URLs and redirects
  • When the trailing / of a Loki or CloudWatch Logs endpoint URL is removed, escaped forms such as %2F are kept; an encoded / is not turned into a path separator.
  • Sending to Loki, ClickHouse, and VictoriaMetrics stops with an error at redirects that would lose the POST body. 307 and 308 redirects that keep the POST and its body follow the redirect settings of the HTTP client.
  • Uploading to S3 sends the signed PUT only once and does not follow redirects, including 301, 302, 303, 307, and 308; they are returned as HTTP status errors. The redirect settings of the given HTTP client are not changed.
  • A redirect is treated as a permanent failure caused by a wrong destination or setting, so compressed logs are kept in the fileArchive permanent or the spool dead and are not resent automatically. Only the 307 TemporaryRedirect that S3 returns while the DNS of a bucket is being updated is treated as a temporary failure and resent.
ClickHouse
  • InsertDeduplicationToken of pkg/clickhouse is sent as is, including leading and trailing whitespace. Only an empty string means it is not set. Use the same token so that a resend is treated as the same INSERT, and use different values for different INSERTs.
S3 and object storage
  • The object name of pkg/objectstorage/uploader.NewUploadInput keeps leading and trailing whitespace; only an empty name is rejected.
  • Upload to S3 supports empty files.
  • The S3 region is signed with only its leading and trailing whitespace removed; its case is not changed. Destination IDs treat regions that differ only in case as the same destination.
  • An S3 endpoint cannot contain a query (including an empty query that is just ?) or a fragment.
VictoriaMetrics
  • SendAsync of pkg/victoriametrics copies the metrics and labels it accepts, so the inputs can be reused after it returns.
  • The settings of the client passed to WithHTTPClient are not changed. WithTimeout applies to each HTTP request, for both synchronous and asynchronous sending, and each resend uses the same deadline again. 0 means no deadline.

Log recovery CLI

In addition to the library, a CLI that recovers the log files of a stopped application is included.

go build -o log-recovery ./cmd/log-recovery
./log-recovery --help
./log-recovery --target my-service --application-stopped --env-file /path/to/logging.env
  • --target must be the same identifier used when the logs were written. It can contain letters, digits, hyphens, underscores, and dots, must start with a letter or digit, and cannot contain path separators or be a reserved Windows name.
  • See .env.example for the settings the CLI reads, and manual log recovery for what is recovered and how to operate it.
  • The CLI loads the environment configuration it is given. After applying --target, it checks the whole application configuration: duplicated storage directories and their ownership, upload targets, the composition of failure stores, the timeout hierarchy (must_fit and so on), and the memory health thresholds. If anything is inconsistent, it exits with a configuration error (invalid config: ..., exit code 1) before starting recovery, without creating or changing any storage directory or file.
  • When a value that may contain credentials (HTTP headers of *_HEADERS and HETEROLOG_OTEL_SPAN_HEADERS, the list of *_S3_DESTINATIONS) is invalid, the configuration error shows only the key and the kind of problem. The value is included neither in the message nor in errors that can be retrieved with errors.As.
  • When HETEROLOG_LOG_TYPE, HETEROLOG_ASYNC_LOG_TYPE, and HETEROLOG_DELIVERY_LOG_TYPE are omitted or empty in the environment configuration, the regular, asynchronous, and delivery loggers write only to stdout. File, Slack, and the other destinations are enabled only when given explicitly, and missing credentials such as a Slack token are a configuration error.
  • To recover file logs, give the same outputs as when the logs were written (for example, HETEROLOG_LOG_TYPE=file).
  • When loading from the environment configuration, logs are also recorded in UTC unless HETEROLOG_ENABLE_LOCAL_TIME_LOG is set.
  • The spool's dead and quarantine, and the storage for failed compressed log uploads (retryable, permanent, dead, quarantine), are not deleted automatically unless deletion is enabled in the environment configuration.
  • The fileArchive for backend send failures (retryable, permanent) is not deleted automatically by default either: the limits on kept generations, age, and directory size (HETEROLOG_MAX_*_ENABLE_DURABLE_FILE_ARCHIVE_BACKUPS, HETEROLOG_MAX_*_ENABLE_DURABLE_FILE_ARCHIVE_AGE, HETEROLOG_MAX_*_ENABLE_DURABLE_FILE_ARCHIVE_DIR_SIZE_MB) are all 0 (unlimited). Old files are deleted only by the conditions set to a non-zero value, and the allowed values are at least 2 generations, at least 1 day, and at least 10 MB and at least the maximum file size.
  • MaxFileBackups, MaxFileAge, and MaxDirSize of durable.FileArchiveConfig set in code also mean unlimited when 0. To keep deleting automatically with the previous defaults (60 generations, 60 days, 2048 MB), set these values explicitly.
  • So that the disk is not filled even without limits, new failures are not saved to the fileArchive while the free space is below HETEROLOG_MIN_AVAILABLE_DISK_SPACE_GB; they are handled by *_DURABLE_FILE_ARCHIVE_OVERLOAD_POLICY (drop discards them, degrade saves them to stdout). When a fileArchive is used, this threshold cannot be 0.

Testing

go test ./...
go vet ./...
go test -race . ./internal/application/logging ./internal/application/loggerruntime ./internal/presentation/sloghandler ./internal/infrastructure/logger/multi
  • The regular tests use a dummy configuration generated from the public configuration example and local HTTP servers, and do not need a developer's .env.
  • Tests that check the output of the file logger with the values of the configuration example need at least HETEROLOG_MIN_AVAILABLE_DISK_SPACE_GB (1 GB in the example) of free space on the file system of the temporary directory, and fail with a message about the missing space otherwise.
  • Integration tests that connect to real services are enabled explicitly with individual environment variables.
  • testenv/windows describes additional Windows-specific test procedures, including the CI on Windows, macOS, and Linux and the procedure to run all packages, the same as go test ./... in CI, on a Windows VM.
  • testenv/macos describes how to run, on a real macOS machine, the tests with case-sensitive APFS, ExFAT, and FAT32 disk images as the temporary directory, and the integration tests on Docker.
  • CI on Linux also runs the whole suite with a temporary directory reached through a symbolic link (TMPDIR under a symlink), as on macOS.

Case-insensitive file systems on Linux:

  • The detection of case-insensitive file systems on Linux (casefold of ext4, F2FS, and tmpfs, and FAT) is checked in every run by tests that replace the file system type, the casefold attribute, and the mount options.
  • The test that checks detection on real casefold directories and FAT mounts (TestLinuxDirectoryCaseDetectsAvailableCaseInsensitiveFilesystems of pkg/path/pathidentity), and the file logger tests that run only when the temporary directory is case-insensitive, are skipped in environments that cannot provide them.
  • The CI job test (ubuntu-latest, case-insensitive TMPDIR) runs all tests with a loop-mounted ext4 casefold directory as the temporary directory, and also runs the detection on vfat mounts (and exFAT when the runner supports it) and the file logger tests in a temporary directory on vfat. This job fails if these tests are skipped.

Integration tests with real services:

  • Prepare a dedicated environment file with the test destinations and credentials, and give it with HETEROLOG_INTEGRATION_ENV_PATH together with each test's opt-in variable. go test runs tests in each package's directory, so give an absolute path.
  • The tests of pkg/opensearch also read only from this file, not from the process environment: the endpoint HETEROLOG_OPENSEARCH_ENDPOINT, the authentication method HETEROLOG_OPENSEARCH_AUTH_TYPE (none for no authentication; basic with HETEROLOG_OPENSEARCH_USERNAME and HETEROLOG_OPENSEARCH_PASSWORD for basic authentication), and the index to write to, OPENSEARCH_TEST_INDEX (a name starting with app-log; app-log-test-index when omitted).
  • The configuration and procedure for running all integration tests against disposable containers in CI are in testenv/integration.
OPENSEARCH_INTEGRATION_TEST=true HETEROLOG_INTEGRATION_ENV_PATH=/path/to/integration.env \
  go test ./pkg/opensearch -count=1
  • Integration tests verify TLS certificates by default. Only for test environments with self-signed certificates, set HETEROLOG_OPENSEARCH_SKIP_VERIFY_SSL=true in the dedicated file. This value is true in .env.example, so set it to false when you create the dedicated file from .env.example and want certificates verified.
  • The logger integration tests use the same dedicated file. Prepare a test file based on .env.example and set the target HETEROLOG_OPENSEARCH_ENDPOINT, HETEROLOG_LOKI_ENDPOINT, or HETEROLOG_CLICKHOUSE_ENDPOINT explicitly.
  • The tests override the sampling rate of ERROR logs to 1, so the sampling settings of the dedicated file do not affect the results.
  • For OpenSearch basic authentication, set HETEROLOG_OPENSEARCH_USERNAME and HETEROLOG_OPENSEARCH_PASSWORD in the dedicated file. Credentials are not filled in, so using OpenSearch without them is a configuration error. For an endpoint without authentication, set HETEROLOG_OPENSEARCH_AUTH_TYPE=none.
OPENSEARCH_INTEGRATION_TEST=true HETEROLOG_INTEGRATION_ENV_PATH=/path/to/integration.env \
  go test ./internal/infrastructure/logger -count=1
  • Loki and ClickHouse are enabled with LOKI_INTEGRATION_TEST=true and CLICKHOUSE_INTEGRATION_TEST=true. The Tempo and OpenTelemetry Collector tests of the file logger use TEMPO_INTEGRATION_TEST=true and OTEL_COLLECTOR_INTEGRATION_TEST=true with the same dedicated file. HETEROLOG_ENV_PATH alone does not start tests against real services.
  • While integration tests run, the settings of this library that are not in the dedicated file (the keys of .env.example, HETEROLOG_ENV_PATH, and AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN, and AWS_REGION, which are used as defaults) are removed from the process environment. The runtime environment, such as PATH, HOME, TMP/TEMP/TMPDIR, SystemRoot, and proxy and certificate settings, is used as is.

Design decisions

Delivering logs from the application itself

heterolog sends logs from the application directly to each destination, instead of relying on a separate log shipper (an agent or sidecar that reads log files and forwards them).

  • Fewer moving parts: there is no extra process to deploy, size, monitor, and upgrade next to each application, and no intermediate file or socket between the application and the destination that can fill up or stall.
  • The application learns the outcome: the synchronous API returns an error when a log could not be recorded or kept, and the delivery API reports the result for each destination. With a shipper, the application only knows that it wrote to a local file.
  • Durability does not depend on an agent: logs that cannot be delivered are written to a local spool or failure archive and replayed by the library, which covers what an agent's disk buffer usually provides.
  • It fits Go programs that are themselves agents, daemons, or command-line tools, where running another agent next to them is awkward.

The trade-off is that delivery uses the application's own CPU, memory, and network, and changing destinations means restarting the application with new settings. When many programs written in different languages share a host, or when routing must be changed centrally, a dedicated shipper can still be the better choice.

Three loggers, and keeping logs that failed

Logs differ in how much the caller needs to know about them, so heterolog has three loggers instead of one logger with options:

  • New is synchronous and returns an error when a log could not be written or kept. It is for logs that must not be lost silently.
  • NewAsync is best effort: it does not make the caller wait for delivery and reports no per-call errors. It is for high-volume logs.
  • NewDelivery returns a report for each destination that separates confirmed success, failure, rejection before sending, an unknown outcome, and queuing. It is for callers that decide what to do next based on where a log arrived.
  • Each type states its guarantee in its method signatures (a logging call of the synchronous logger returns an error, one of the asynchronous logger returns nothing, and one of the delivery logger returns a report), so the code shows which guarantee it relies on.

A log that cannot be delivered is kept, not discarded:

  • Temporary failures go to the spool and are replayed. Retry-After is honored and survives restarts, so a recovering destination is not flooded.
  • When the outcome is unknown, for example because the connection broke after sending, the log goes to quarantine instead of being resent automatically: resending could deliver it twice, and deleting it could lose it, so a person decides.
  • Logs rejected because of their content are isolated one by one, by splitting batches, so that one bad entry does not block the others. Failures caused by the destination or the configuration, such as rejected authentication or a missing table, go to dead.
  • When the choice is between a duplicate and a loss, heterolog prefers the duplicate.

Kept failures are not deleted by default. They may be the only copy of a log, so deleting them should be an explicit decision, and retention limits are opt-in. Filling the disk is prevented instead by the free space threshold (HETEROLOG_MIN_AVAILABLE_DISK_SPACE_GB): below it, new failures are dropped (reported as ErrLogDropped) or degraded to stdout, as configured.

Configuration
  • Configuration is explicit. Importing the package or constructing a logger has no side effects: it does not load env files, install signal handlers, or replace the global slog logger or OpenTelemetry providers. A library should not change the state of the application that uses it.
  • Reading the environment is opt-in. LoadEnvConfig reads only when it is called and only the file it is given, and never modifies the process environment. A variable set in the environment overrides the file, as most dotenv tools do.
  • Every key starts with HETEROLOG_, so the settings can live in the same environment and .env file as the application's own settings without colliding.
  • With no settings, every logger writes only to stdout, so heterolog works without any configuration or external service. Other destinations are enabled only when they are selected, and missing credentials are reported as errors instead of being filled in.
  • Settings are checked when they are loaded or when a logger is constructed, and all problems are reported together, so a wrong setting fails at startup instead of at the first log or the first failure.
  • Only the level and sampling can change while running. The outputs read them for every entry, so a change needs neither rebuilding loggers nor interrupting logging; changing destinations or storage would. The HTTP API needs a token, listens only on 127.0.0.1 unless TLS is configured, and its changes do not survive a restart, so a temporary change, such as switching to DEBUG during an investigation, cannot stay by accident.
  • Configuration errors do not include values that may contain credentials, such as HTTP headers, lists of S3 destinations, and the user info of URLs.
  • Defaults follow the platform: timestamps are in UTC, and on Linux, the BSDs, illumos, Solaris and AIX, storage defaults to the user's state directory ($XDG_STATE_HOME if it is an absolute path, or else ~/.local/state) when the process does not run as root, so a regular user can enable file output without extra settings.
Testing on real systems
  • The parts most likely to lose or duplicate logs depend on the operating system and the file system: case sensitivity of names, renaming without replacement, syncing directories, file permissions and Windows ACLs, symbolic links in temporary directories, and macOS AppleDouble files. Replaced inputs alone do not reproduce these behaviors, so besides unit tests, the suite runs on real file systems.
  • CI runs the whole suite on Linux, Windows, and macOS, plus Linux jobs with a temporary directory reached through a symbolic link and with a case-insensitive temporary directory (ext4 casefold and vfat), and integration tests against OpenSearch, Loki, ClickHouse, Tempo, and the OpenTelemetry Collector in containers.
  • In the jobs that exist to cover such a condition, a test that is skipped counts as a failure, so the coverage cannot disappear silently.
  • Beyond CI, the whole suite has been run on a Windows virtual machine, as a regular user and as an administrator, and on a real macOS machine with case-sensitive APFS, ExFAT, and FAT32 disk images. The results are recorded in testenv.
  • Timing-dependent behavior is tested with virtual time (testing/synctest) where possible.

License

MIT License

Documentation

Overview

Package heterolog provides structured logging to files, standard output, Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse.

Start with DefaultConfig and New, and call Close or Shutdown when the application exits to flush buffered logs and release owned resources. Configuration is explicit: importing this package or constructing a logger does not load environment files, install signal handlers, or change the process-wide slog logger or OpenTelemetry providers. To configure loggers from HETEROLOG_ environment variables and an env file, call LoadEnvConfig.

Advanced backend and durability settings are available in pkg/logger and its related public packages. A configuration must not be modified while a logger constructed from it is in use.

Index

Examples

Constants

View Source
const (
	LevelDebug = pkglogger.LogLevelDebug
	LevelInfo  = pkglogger.LogLevelInfo
	LevelWarn  = pkglogger.LogLevelWarn
	LevelError = pkglogger.LogLevelError
	// DefaultMaxLogEntryBytes is the default size limit before backend fan-out.
	DefaultMaxLogEntryBytes = pkglogger.DefaultMaxLogEntryBytes
)
View Source
const (
	StreamRoutingNone    = pkgcloudwatchlogs.StreamRoutingNone
	StreamRoutingMonthly = pkgcloudwatchlogs.StreamRoutingMonthly
	StreamRoutingDaily   = pkgcloudwatchlogs.StreamRoutingDaily
	StreamRoutingHourly  = pkgcloudwatchlogs.StreamRoutingHourly
)
View Source
const (
	// ConfigFieldTimeout identifies the Timeout of Config, AsyncConfig and
	// DeliveryConfig in a pkg/logger ConfigFieldError. A Timeout that is not
	// positive is reported with the kind pkg/logger ErrNonPositiveSetting.
	ConfigFieldTimeout = loggerruntime.ConfigFieldTimeout
	// ConfigFieldMaxParallel identifies AsyncConfig.MaxParallel in a pkg/logger
	// ConfigFieldError. A MaxParallel that is not positive is reported with the
	// kind pkg/logger ErrNonPositiveSetting.
	ConfigFieldMaxParallel = loggerruntime.ConfigFieldMaxParallel
)
View Source
const MaxFieldNestingDepth = pkglogger.MaxFieldNestingDepth

MaxFieldNestingDepth is the deepest nesting of arrays and objects that Any and slog attributes accept: a scalar is depth 0 and one enclosing array is depth 1. Spool records and backend payloads add a few levels around each value; the limit leaves 1,000 of the 10,000 levels that JSON decoders accept for them, so every accepted value can be stored and replayed.

View Source
const MinAdminTokenLength = pkgadmin.MinTokenLength

MinAdminTokenLength is the minimum length in bytes of an admin API token.

Variables

View Source
var (
	// ErrAdminTokenTooShort reports an admin API token shorter than
	// MinAdminTokenLength. The error never contains the token.
	ErrAdminTokenTooShort = admin.ErrTokenTooShort
	// ErrAdminNoLoggers reports an admin API configuration without loggers.
	ErrAdminNoLoggers = outputsettings.ErrNoLoggers
	// ErrAdminServerAddrRequired reports an AdminServerConfig without Addr.
	ErrAdminServerAddrRequired = admin.ErrServerAddrRequired
	// ErrAdminServerInsecure reports an admin server that would listen on a
	// non-loopback address without TLS, which would send the token over the
	// network in clear text.
	ErrAdminServerInsecure = admin.ErrServerInsecure
	// ErrAdminServerTLSIncomplete reports an AdminServerConfig that sets only
	// one of TLSCertFile and TLSKeyFile.
	ErrAdminServerTLSIncomplete = admin.ErrServerTLSIncomplete
)
View Source
var (
	ErrFieldKeyInvalid       = pkglogger.ErrFieldKeyInvalid
	ErrFieldValueNotJSON     = pkglogger.ErrFieldValueNotJSON
	ErrFieldFloatNotFinite   = pkglogger.ErrFieldFloatNotFinite
	ErrLoggerClosed          = pkglogger.ErrLoggerClosed
	ErrLogEntryTooLarge      = pkglogger.ErrLogEntryTooLarge
	ErrForcedClose           = pkgshutdown.ErrForcedClose
	ErrForceCloseUnsupported = applogging.ErrForceCloseUnsupported
	ErrLogDropped            = pkglogger.ErrLogDropped
	ErrNoActiveLogOutput     = pkglogger.ErrNoActiveLogOutput
)
View Source
var (
	// ErrNilContext reports that New, NewAsync or NewDelivery received a nil context.
	ErrNilContext = loggerruntime.ErrNilContext
	// ErrDeliverySpoolUnsupported reports that NewDelivery received WithSpool. A
	// Delivery logger reports each delivery to the caller and has no replay workers.
	ErrDeliverySpoolUnsupported = loggerruntime.ErrDeliverySpoolUnsupported
	// ErrInvalidNotificationTarget reports that a backend selected as an internal
	// log notification target (OnErrorConfig, OnWarnConfig, OnInfoConfig or
	// OnDebugConfig) has settings from which its notification writer cannot be
	// created, for example an unknown TimeZone or an empty LogLineDateFormat. The
	// constructors return it as a *NotificationTargetError before creating any
	// resource, instead of dropping notifications later.
	ErrInvalidNotificationTarget = pkglogger.ErrInvalidNotificationTarget
)
View Source
var ErrEnvLoggerDisabled = envconfig.ErrLoggerDisabled

ErrEnvLoggerDisabled reports that EnvConfig was asked for a logger that the environment disabled with HETEROLOG_ENABLE_LOGGING, HETEROLOG_ENABLE_ASYNC_BEST_EFFORT_LOGGING or HETEROLOG_ENABLE_DELIVERY_LOGGING set to false.

View Source
var ErrInvalidMemoryPressureMonitor = memorymonitor.ErrInvalidMonitorConfig

ErrInvalidMemoryPressureMonitor reports that NewMemoryPressureMonitor rejected its provider, policy, or poll interval.

View Source
var ErrInvalidStreamRouting = pkgcloudwatchlogs.ErrInvalidStreamRouting

ErrInvalidStreamRouting reports that WithCloudWatchLogsStreamRouting received a StreamRouting value that is not supported. The constructors return it as an *InvalidStreamRoutingError.

View Source
var ErrUnknownOutput = pkglogger.ErrUnknownOutput

ErrUnknownOutput reports that UpdateOutputSettings named an output that the logger does not use.

Functions

func NewAdminHandler added in v0.3.0

func NewAdminHandler(cfg AdminHandlerConfig) (http.Handler, error)

NewAdminHandler returns an http.Handler for the admin API, which reads and changes the level and sampling of the outputs of running loggers. Mount it on your own server, behind your own TLS when it is reachable over a network; StartAdminServer starts a dedicated server instead. The handler serves:

GET   /settings  returns the current settings of every logger
PATCH /settings  changes the fields given in the JSON body

Every request must send "Authorization: Bearer <Token>". A PATCH checks all of its changes before applying any of them. Changes take effect from the next entry and are kept in memory only, so a restart returns to the configured settings.

Types

type AdminChange added in v0.3.0

type AdminChange = pkgadmin.Change

AdminChange describes a change of one output made through the admin API: the client's RemoteAddr, the Logger name, the Output, and the settings Before and After the change.

type AdminHandlerConfig added in v0.3.0

type AdminHandlerConfig = pkgadmin.HandlerConfig

AdminHandlerConfig configures NewAdminHandler: the bearer Token (at least MinAdminTokenLength bytes), the Loggers by the names used in the API, and an optional OnChange called after each change, for example for audit logs. Without OnChange, each change is written as one line to the standard logger.

type AdminServer added in v0.3.0

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

AdminServer serves the admin API until Shutdown or Close stops it.

func StartAdminServer added in v0.3.0

func StartAdminServer(cfg AdminServerConfig, loggers map[string]SettingsController) (*AdminServer, error)

StartAdminServer starts a dedicated HTTP server for the admin API of NewAdminHandler and returns once it listens. loggers maps the names used in the API to the loggers whose settings it reads and changes. The server listens on a loopback address unless cfg names another host and enables TLS. Call Shutdown or Close to stop it.

func (*AdminServer) Addr added in v0.3.0

func (s *AdminServer) Addr() string

Addr returns the address the server listens on, including the port chosen when AdminServerConfig.Addr asked for port 0.

func (*AdminServer) Close added in v0.3.0

func (s *AdminServer) Close() error

Close stops the server immediately and closes active connections.

func (*AdminServer) Shutdown added in v0.3.0

func (s *AdminServer) Shutdown(ctx context.Context) error

Shutdown stops accepting connections and waits until active requests finish or ctx ends. It returns ctx's error if ctx ends first, and otherwise the error that stopped the server, if any.

type AdminServerConfig added in v0.3.0

type AdminServerConfig = pkgadmin.ServerConfig

AdminServerConfig configures StartAdminServer. Addr is the TCP address to listen on; with an empty host, such as ":9100", the server listens on 127.0.0.1 only. Listening on a non-loopback address requires TLSCertFile and TLSKeyFile. Token and OnChange are as in AdminHandlerConfig.

type AsyncConfig

AsyncConfig configures a logger with asynchronous best-effort delivery.

func DefaultAsyncConfig

func DefaultAsyncConfig() AsyncConfig

DefaultAsyncConfig returns stdout configuration with at most 16 parallel backend operations. Logging methods do not return delivery errors.

type AsyncLogger

type AsyncLogger = pkglogger.AsyncLogger

AsyncLogger accepts entries without returning delivery errors.

type AsyncRuntime

type AsyncRuntime struct {
	AsyncLogger
	// contains filtered or unexported fields
}

AsyncRuntime owns an asynchronous best-effort logger. Shutdown waits for accepted operations and final buffer flushing. Obtain one with NewAsync.

func NewAsync

func NewAsync(ctx context.Context, cfg AsyncConfig, opts ...Option) (*AsyncRuntime, error)

NewAsync constructs an asynchronous best-effort logger. MaxParallel and the normal timeout and entry-size limits must all be positive.

func (*AsyncRuntime) Close

func (r *AsyncRuntime) Close() error

Close stops accepting new entries, waits for accepted operations and final buffer flushing, and releases resources. It waits without a deadline. A spool's entire backlog need not be delivered; durable records remain available for later replay.

func (*AsyncRuntime) ForceClose

func (r *AsyncRuntime) ForceClose() error

ForceClose stops accepting new entries, releases callers waiting in Close or Shutdown, and requests the background and recovery work, such as spool replay and the compression and upload of log files, to stop. It returns without waiting, while the regular cleanup continues in the background. Unless shutdown has already finished, it returns ErrForcedClose, which the released Close and Shutdown calls also return; after shutdown has finished, it returns the result of that shutdown. Unfinished checkpoints or archives may remain, and OS I/O may still need time to complete.

func (*AsyncRuntime) OutputSettings added in v0.3.0

func (r *AsyncRuntime) OutputSettings() map[LogOutputDestination]OutputSettings

OutputSettings returns the current settings of each output of the logger, like Runtime.OutputSettings.

func (*AsyncRuntime) Shutdown

func (r *AsyncRuntime) Shutdown(ctx context.Context) error

Shutdown starts graceful shutdown and waits until it completes or ctx ends. If ctx has already ended, it returns ctx.Err() without starting shutdown. Cancellation only stops this caller's wait; cleanup continues. A later Close or Shutdown joins cleanup. Use ForceClose to request aborting recovery work.

func (*AsyncRuntime) UpdateOutputSettings added in v0.3.0

func (r *AsyncRuntime) UpdateOutputSettings(changes map[LogOutputDestination]OutputSettingsChange) error

UpdateOutputSettings changes the level and sampling of outputs while the logger runs, like Runtime.UpdateOutputSettings. An asynchronous logger applies the settings in effect when it processes an entry.

type BackendSpoolRunnerConfig

type BackendSpoolRunnerConfig = spoolrunner.BackendSpoolRunnerConfig

BackendSpoolRunnerConfig controls one backend's replay worker and lifecycle.

type Config

type Config = pkglogger.LoggerConfig

Config configures a synchronous logger. See pkg/logger for backend settings.

func DefaultConfig

func DefaultConfig() Config

DefaultConfig returns independent configuration for INFO and higher logs on stdout (WARN and ERROR on stderr). Timestamps use UTC and RFC3339Nano.

type Counter

type Counter = pkgobserver.Counter

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type DeliveryConfig

type DeliveryConfig = pkglogger.DeliveryLoggerConfig

DeliveryConfig configures a logger that returns a report for each destination.

func DefaultDeliveryConfig

func DefaultDeliveryConfig() DeliveryConfig

DefaultDeliveryConfig returns stdout configuration for reporting delivery. Delivery loggers do not sample entries, and only their Slack output filters severity.

type DeliveryLogger

type DeliveryLogger = pkglogger.DeliveryLogger

DeliveryLogger reports the result for each configured destination.

type DeliveryReport

type DeliveryReport = pkglogger.DeliveryReport

DeliveryReport describes backend delivery, durable storage, and evacuation.

type DeliveryRuntime

type DeliveryRuntime struct {
	DeliveryLogger
	// contains filtered or unexported fields
}

DeliveryRuntime owns a delivery-reporting logger. Obtain one with NewDelivery.

func NewDelivery

func NewDelivery(ctx context.Context, cfg DeliveryConfig, opts ...Option) (*DeliveryRuntime, error)

NewDelivery constructs a logger that reports delivery per destination. Delivery mode has no replay workers, so NewDelivery returns ErrDeliverySpoolUnsupported when opts include WithSpool.

func (*DeliveryRuntime) Close

func (r *DeliveryRuntime) Close() error

Close stops accepting new entries, flushes accepted buffered entries and releases resources. It waits without a deadline.

func (*DeliveryRuntime) ForceClose

func (r *DeliveryRuntime) ForceClose() error

ForceClose stops accepting new entries, releases callers waiting in Close or Shutdown, and requests the background and recovery work, such as spool replay and the compression and upload of log files, to stop. It returns without waiting, while the regular cleanup continues in the background. Unless shutdown has already finished, it returns ErrForcedClose, which the released Close and Shutdown calls also return; after shutdown has finished, it returns the result of that shutdown. Unfinished checkpoints or archives may remain, and OS I/O may still need time to complete.

func (*DeliveryRuntime) Shutdown

func (r *DeliveryRuntime) Shutdown(ctx context.Context) error

Shutdown starts graceful shutdown and waits until it completes or ctx ends. If ctx has already ended, it returns ctx.Err() without starting shutdown. Cancellation only stops this caller's wait; cleanup continues. A later Close or Shutdown joins cleanup. Use ForceClose to request aborting recovery work.

type EnvConfig

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

EnvConfig holds the settings that LoadEnvConfig read from HETEROLOG_ environment variables. New, NewAsync and NewDelivery construct loggers from them; Config, AsyncConfig and DeliveryConfig return the settings to adjust before calling the package-level constructors.

The environment does not configure tracing; pass WithObservers as an option. A spool that a HETEROLOG_USE_MEMORY_PRESSURE_* setting enables judges memory pressure with HETEROLOG_MEMORY_CRITICAL_RATIO, HETEROLOG_MIN_AVAILABLE_MEMORY_BYTES_MB and HETEROLOG_MEMORY_CRITICAL_CONSECUTIVE_HITS, unless WithMemoryPressureMonitor supplies a monitor.

func LoadEnvConfig

func LoadEnvConfig(path string) (*EnvConfig, error)

LoadEnvConfig reads the HETEROLOG_ settings from the process environment and, when path is not empty, from the env file at path. A variable that is set in the process environment takes precedence over the file. LoadEnvConfig does not modify the process environment and reads no other env file: it ignores HETEROLOG_ENV_PATH and a .env file that path does not name. The AWS SDK's AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_SESSION_TOKEN and AWS_REGION supply defaults for the S3 and CloudWatch Logs settings.

Settings that are not set use the defaults documented in .env.example, so an empty environment yields loggers that write to stdout. LoadEnvConfig checks the settings of every enabled logger and of the loggers together, such as directories that two stores would share, and returns the problems it finds joined with errors.Join. Some problems, such as a value of the wrong type, stop the later checks, so fixing them can reveal others. Use errors.As with EnvFileError, InvalidEnvironmentValueError, RenamedEnvironmentKeyError or pkg/env VariableError to identify a setting.

Example

LoadEnvConfig reads HETEROLOG_ variables and the named env file without changing the process environment. Unset settings use the defaults, which write to stdout.

package main

import (
	"context"
	"log"

	"github.com/go-jappe/heterolog"
)

func main() {
	env, err := heterolog.LoadEnvConfig(".env")
	if err != nil {
		log.Fatal(err)
	}
	ctx := context.Background()
	runtime, err := env.New(ctx)
	if err != nil {
		log.Fatal(err)
	}
	defer func() {
		if err := runtime.Close(); err != nil {
			log.Print(err)
		}
	}()

	if err := runtime.Info(ctx, "service started"); err != nil {
		log.Print(err)
	}
}

func (*EnvConfig) AdminServerConfig added in v0.3.0

func (c *EnvConfig) AdminServerConfig() (AdminServerConfig, bool)

AdminServerConfig returns the admin server settings read from HETEROLOG_ADMIN_ADDR, HETEROLOG_ADMIN_TOKEN, HETEROLOG_ADMIN_TLS_CERT_FILE and HETEROLOG_ADMIN_TLS_KEY_FILE, and whether HETEROLOG_ADMIN_ADDR enables the server. LoadEnvConfig has already checked them. Pass the settings to StartAdminServer; set OnChange first to keep your own audit log.

func (*EnvConfig) AsyncConfig

func (c *EnvConfig) AsyncConfig() (AsyncConfig, []Option, error)

AsyncConfig returns the asynchronous logger settings and the options for NewAsync, like Config. It returns an error wrapping ErrEnvLoggerDisabled when HETEROLOG_ENABLE_ASYNC_BEST_EFFORT_LOGGING is false.

func (*EnvConfig) Config

func (c *EnvConfig) Config() (Config, []Option, error)

Config returns the synchronous logger settings and the options for the spool replay settings and CloudWatch Logs stream routing read from the environment. Pass both to New. Each call returns a new Config, but slices in it, such as LogOutputDestinations, can share their backing arrays with the EnvConfig, so replace a slice instead of changing its elements. It returns an error wrapping ErrEnvLoggerDisabled when HETEROLOG_ENABLE_LOGGING is false.

func (*EnvConfig) DeliveryConfig

func (c *EnvConfig) DeliveryConfig() (DeliveryConfig, []Option, error)

DeliveryConfig returns the delivery logger settings and the options for NewDelivery. Delivery loggers do not replay spools, so the options carry only the CloudWatch Logs stream routing. It returns an error wrapping ErrEnvLoggerDisabled when HETEROLOG_ENABLE_DELIVERY_LOGGING is false.

func (*EnvConfig) New

func (c *EnvConfig) New(ctx context.Context, opts ...Option) (*Runtime, error)

New constructs a synchronous logger from the settings and options that Config returns. opts are applied after those options, so they can replace them or add WithObservers and WithMemoryPressureMonitor.

func (*EnvConfig) NewAsync

func (c *EnvConfig) NewAsync(ctx context.Context, opts ...Option) (*AsyncRuntime, error)

NewAsync constructs an asynchronous best-effort logger from the settings and options that AsyncConfig returns, followed by opts.

func (*EnvConfig) NewDelivery

func (c *EnvConfig) NewDelivery(ctx context.Context, opts ...Option) (*DeliveryRuntime, error)

NewDelivery constructs a delivery-reporting logger from the settings and options that DeliveryConfig returns, followed by opts.

type EnvFileError

type EnvFileError = pkgenv.EnvFileError

EnvFileError reports that LoadEnvConfig could not read the env file. Path is the file and Err the cause; errors.Is(err, fs.ErrNotExist) reports a missing file.

type Field

type Field = pkglogger.Field

Field is one immutable structured attribute. Its zero value is ignored.

func Any

func Any(key string, value any) (Field, error)

Any snapshots a JSON-encodable value with a validated key. Values that cannot be encoded, or that nest arrays and objects deeper than MaxFieldNestingDepth, return ErrFieldValueNotJSON instead of a field.

func Bool

func Bool(key string, value bool) (Field, error)

Bool constructs a boolean attribute with a validated key.

func Float64

func Float64(key string, value float64) (Field, error)

Float64 constructs a finite floating-point attribute with a validated key.

func Int

func Int(key string, value int) (Field, error)

Int constructs an integer attribute with a validated key.

func Int64

func Int64(key string, value int64) (Field, error)

Int64 constructs a signed integer attribute with a validated key.

func String

func String(key, value string) (Field, error)

String constructs a string attribute with a validated key.

func Uint64

func Uint64(key string, value uint64) (Field, error)

Uint64 constructs an unsigned integer attribute with a validated key.

func WithRequestID

func WithRequestID(id string) Field

WithRequestID sets the request ID of a single log entry. An empty id sets no request ID.

type FieldKey

type FieldKey = pkglogger.FieldKey

FieldKey is a validated key that can efficiently construct typed fields.

func MustFieldKey

func MustFieldKey(key string) FieldKey

MustFieldKey validates a constant attribute key and panics if it is invalid.

func NewFieldKey

func NewFieldKey(key string) (FieldKey, error)

NewFieldKey validates a dynamic attribute key.

type Gauge

type Gauge = pkgobserver.Gauge

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type InvalidEnvironmentValueError

type InvalidEnvironmentValueError = pkgenv.InvalidEnvironmentValueError

InvalidEnvironmentValueError reports a value that LoadEnvConfig rejected after reading it. Key names the variable and Err the reason. Value is empty for values that may contain credentials. Values that are not of the expected type, such as a number, are reported as a pkg/env VariableError, except values that may contain credentials, which are reported as this error.

type InvalidStreamRoutingError

type InvalidStreamRoutingError = pkgcloudwatchlogs.InvalidStreamRoutingError

InvalidStreamRoutingError reports the unsupported StreamRouting value in its Granularity field. errors.Is matches ErrInvalidStreamRouting.

type Level

type Level = pkglogger.LogLevel

Level is a heterolog severity level, independent of slog's numeric levels.

type LogEntryTooLargeError

type LogEntryTooLargeError = pkglogger.LogEntryTooLargeError

LogEntryTooLargeError describes an entry rejected before fan-out.

type LogOutputDestination added in v0.3.0

type LogOutputDestination = pkglogger.LogOutputDestination

LogOutputDestination names an output, such as stdout or opensearch.

type Logger

type Logger = pkglogger.Logger

Logger synchronously records structured entries and reports failures.

type LoggerFailure

type LoggerFailure = pkglogger.LoggerFailure

LoggerFailure describes a failure from a single physical handler.

type MemoryPressureMonitor

type MemoryPressureMonitor = memorypressure.Monitor

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

func NewMemoryPressureMonitor

func NewMemoryPressureMonitor(
	provider memorypressure.Provider,
	policy memorypressure.CriticalPolicy,
	pollInterval time.Duration,
) (MemoryPressureMonitor, error)

NewMemoryPressureMonitor returns a monitor to pass to WithMemoryPressureMonitor. After Start, it reads provider every pollInterval and evaluates each reading with the same rules as memorypressure.CriticalState: a reading is a critical candidate when a reliable observation reaches CriticalRatio or MinAvailableBytes, and the monitor reports critical once ConsecutiveCriticalHits candidates occur in a row (0 or 1 means the first).

The caller owns the monitor. Start reads once before returning and then polls until its context ends; cancel that context when no logger uses the monitor. If the first read fails, Start returns the error and polling does not begin.

It returns an error wrapping ErrInvalidMemoryPressureMonitor for a nil provider, a non-positive poll interval, or a policy that enables neither threshold, has a CriticalRatio above 1, or has a negative ConsecutiveCriticalHits.

type Meter

type Meter = pkgobserver.Meter

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type MultiLoggerError

type MultiLoggerError = pkglogger.MultiLoggerError

MultiLoggerError contains the failures from a fan-out operation.

type NotificationTargetError

type NotificationTargetError = pkglogger.NotificationTargetError

NotificationTargetError reports the logger (Source) and the notification target (Backend) whose settings are invalid, and the cause in Err. errors.Is matches ErrInvalidNotificationTarget and the cause.

type ObserverAttr

type ObserverAttr = pkgobserver.Attr

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type Option

type Option = loggerruntime.Option

Option supplies optional dependencies and runtime policies to constructors.

func WithCloudWatchLogsStreamRouting

func WithCloudWatchLogsStreamRouting(routing StreamRouting) Option

WithCloudWatchLogsStreamRouting selects stream partitioning for CloudWatch.

func WithMemoryPressureMonitor

func WithMemoryPressureMonitor(monitor MemoryPressureMonitor) Option

WithMemoryPressureMonitor supplies an already-started monitor, such as one from NewMemoryPressureMonitor, for overload policies. The caller owns its lifetime: loggers neither start, reset, nor stop it. Its policy replaces the MemoryCriticalRatio, MinAvailableMemoryBytes and MemoryCriticalConsecutiveHits of the spool settings. Without it, each spool that enables UseMemoryPressureForOverload starts and stops its own monitor with those settings.

func WithObservers

func WithObservers(tracer Tracer, meter Meter) Option

WithObservers supplies instrumentation. Nil dependencies use no-op observers. The caller retains ownership of observer providers and their shutdown.

func WithSpool

func WithSpool(cfg SpoolConfig) Option

WithSpool supplies replay settings when a synchronous or asynchronous backend uses durable spooling. Delivery loggers do not own replay workers.

type OutputSettings added in v0.3.0

type OutputSettings = pkglogger.OutputSettings

OutputSettings are the settings of an output that can change while a logger runs: its Level, the lowest severity it records, and its Sampling.

type OutputSettingsChange added in v0.3.0

type OutputSettingsChange = pkglogger.OutputSettingsChange

OutputSettingsChange changes the Level or Sampling of one output. A nil field keeps the current value.

type RenamedEnvironmentKeyError

type RenamedEnvironmentKeyError = pkgenv.RenamedEnvironmentKeyError

RenamedEnvironmentKeyError reports a variable whose name was corrected. Old is the name that is set and New the current name. LoadEnvConfig does not read the old name as an alias, because ignoring it would silently drop a setting.

type Runtime

type Runtime struct {
	Logger
	// contains filtered or unexported fields
}

Runtime owns a synchronous logger and its background resources. Obtain one with New; the zero value is not a usable logger. Do not copy a Runtime.

func New

func New(ctx context.Context, cfg Config, opts ...Option) (*Runtime, error)

New constructs a logger from explicit configuration. It does not load the environment or modify global providers. Use DefaultConfig as a starting point. Close or Shutdown must be called to flush buffers and release resources.

func (*Runtime) Close

func (r *Runtime) Close() error

Close stops accepting new entries, flushes accepted buffered entries and releases resources. It waits without a deadline. A spool's entire backlog need not be delivered; durable records remain available for later replay.

func (*Runtime) ForceClose

func (r *Runtime) ForceClose() error

ForceClose stops accepting new entries, releases callers waiting in Close or Shutdown, and requests the background and recovery work, such as spool replay and the compression and upload of log files, to stop. It returns without waiting, while the regular cleanup continues in the background. Unless shutdown has already finished, it returns ErrForcedClose, which the released Close and Shutdown calls also return; after shutdown has finished, it returns the result of that shutdown. Unfinished checkpoints or archives may remain, and OS I/O may still need time to complete.

func (*Runtime) Log

func (r *Runtime) Log(ctx context.Context, level Level, message string, fields ...Field) error

Log records a supported severity. It never terminates the process.

func (*Runtime) OutputSettings added in v0.3.0

func (r *Runtime) OutputSettings() map[LogOutputDestination]OutputSettings

OutputSettings returns the current settings of each output of the logger. Outputs used only for internal log notifications are not included.

func (*Runtime) Shutdown

func (r *Runtime) Shutdown(ctx context.Context) error

Shutdown starts graceful shutdown and waits until it completes or ctx ends. If ctx has already ended, it returns ctx.Err() without starting shutdown. Cancellation only stops this caller's wait; cleanup continues. A later Close or Shutdown joins cleanup. Use ForceClose to request aborting recovery work.

func (*Runtime) UpdateOutputSettings added in v0.3.0

func (r *Runtime) UpdateOutputSettings(changes map[LogOutputDestination]OutputSettingsChange) error

UpdateOutputSettings changes the level and sampling of outputs while the logger runs. It checks every change first and applies none of them when any is invalid; an output the logger does not use is reported as ErrUnknownOutput, and an invalid value as a pkg/logger ConfigFieldError. Changes take effect from the next entry and are not kept after the process exits.

type SamplingConfig added in v0.3.0

type SamplingConfig = pkglogger.SamplingConfig

SamplingConfig configures how an output samples entries. See pkg/logger.

type SettingsController added in v0.3.0

type SettingsController = pkglogger.SettingsController

SettingsController is a logger whose output settings can change while it runs. *Runtime and *AsyncRuntime implement it.

type SlogHandler

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

SlogHandler adapts the standard library's structured logger to Logger. Derived handlers share the destination; closing its runtime remains the caller's responsibility. The destination must support concurrent calls.

func NewSlogHandler

func NewSlogHandler(logger Logger, opts *slog.HandlerOptions) *SlogHandler

NewSlogHandler returns a handler suitable for slog.New. A nil options pointer uses slog's defaults (Info level, no source). A nil logger panics.

Attributes follow slog.JSONHandler's encoding and ReplaceAttr behavior. The complete slog record, including time, level, msg and optional source, is available in the destination's structured fields. Duplicate keys retain their last value. The original record level determines backend routing, and its original time is also used as the backend event time. ReplaceAttr changes the structured fields and the backend's message, but not routing or event time. A removed message becomes empty; a non-string message uses its JSON encoding. String-valued top-level request_id, trace_id and span_id become event metadata. Non-string values remain ordinary structured fields alongside any context IDs.

slog.Logger discards errors returned by Handler.Handle. Use the native logging API for returned errors, or NewDelivery for per-destination delivery reports.

func (*SlogHandler) Enabled

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

Enabled reports whether level meets the configured minimum. A LevelVar in the options is consulted on every call, allowing changes without rebuilding the handler. Each backend may impose its own additional level filter.

func (*SlogHandler) Handle

func (h *SlogHandler) Handle(ctx context.Context, record slog.Record) error

Handle sends a record to the destination and returns any delivery error. Like the standard handlers, Handle does not apply Enabled itself. Context values (including trace and request IDs) are retained; cancellation does not suppress the log record.

func (*SlogHandler) WithAttrs

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

WithAttrs returns an independent handler with a snapshot of attrs in the current group. LogValuer and ReplaceAttr are evaluated here, once.

func (*SlogHandler) WithGroup

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

WithGroup returns an independent handler whose subsequent attributes belong to name. Empty names have no effect.

type Span

type Span = pkgobserver.Span

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type SpoolConfig

type SpoolConfig = pkgspool.SpoolConfig

SpoolConfig configures background replay of durable failure spools.

func DefaultSpoolConfig

func DefaultSpoolConfig() SpoolConfig

DefaultSpoolConfig returns replay settings for every supported backend. Purging is disabled so retained records are not deleted implicitly.

type SpoolFinalizeConfig

type SpoolFinalizeConfig = spoolrunner.FinalizeConfig

SpoolFinalizeConfig bounds finalization retry state.

type SpoolLifecycleConfig

type SpoolLifecycleConfig = spoollifecycle.LifecycleConfig

SpoolLifecycleConfig controls retention of finalized spool records.

type SpoolLoopConfig

type SpoolLoopConfig = spoolrunner.RunnerConfig

SpoolLoopConfig controls replay polling.

type SpoolRunnerConfig

type SpoolRunnerConfig = spoolrunner.SpoolRunnerConfig

SpoolRunnerConfig supplies separate replay settings for each backend.

type SpoolSupervisorConfig

type SpoolSupervisorConfig = spoolsupervisor.RunnerSupervisorConfig

SpoolSupervisorConfig controls replay worker restarts.

type SpoolWorkerConfig

type SpoolWorkerConfig = spoolrunner.WorkerConfig

SpoolWorkerConfig controls replay finalization and the maximum wait for a backend-specified Retry-After.

type StreamRouting

type StreamRouting = pkgcloudwatchlogs.StreamRouting

StreamRouting selects time partitioning for CloudWatch Logs stream names.

type TraceID

type TraceID = pkgobserver.TraceID

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

type Tracer

type Tracer = pkgobserver.Tracer

These aliases name the types for custom instrumentation and memory pressure monitoring, so callers need not import pkg/observer or pkg/memorypressure.

Directories

Path Synopsis
cmd
log-recovery command
examples
slog command
Run with: go run ./examples/slog
Run with: go run ./examples/slog
internal
application/loggerruntime
Package loggerruntimeは、公開APIのNew・NewAsync・NewDeliveryの処理を受け持ちます。
Package loggerruntimeは、公開APIのNew・NewAsync・NewDeliveryの処理を受け持ちます。
application/logrecovery
Package logrecoveryは、停止中のアプリケーションのログファイルを手動復旧します。
Package logrecoveryは、停止中のアプリケーションのログファイルを手動復旧します。
application/outputsettings
Package outputsettingsは、稼働中のloggerの出力先ごとのlog levelとsampling設定を、 読み取り・変更する処理を提供します。
Package outputsettingsは、稼働中のloggerの出力先ごとのlog levelとsampling設定を、 読み取り・変更する処理を提供します。
application/trace/span
sdk使う予定のため自作は廃止予定
sdk使う予定のため自作は廃止予定
application/trace/tracer
otel sdk使う予定のためこの自作は廃止予定
otel sdk使う予定のためこの自作は廃止予定
config/configerror
Package configerrorは、設定の検証errorに種類(sentinel)を付けるための補助です。
Package configerrorは、設定の検証errorに種類(sentinel)を付けるための補助です。
config/failure
Package failure はbackend共通のdurable failure設定を提供します。
Package failure はbackend共通のdurable failure設定を提供します。
config/filelifecycle
Package filelifecycle は、通常FileLoggerとfailure archiveの解決済みlifecycle modeごとに 実行時に有効となる責務を定義します。
Package filelifecycle は、通常FileLoggerとfailure archiveの解決済みlifecycle modeごとに 実行時に有効となる責務を定義します。
config/objectstoragecompressedlog
Package objectstoragecompressedlogは、圧縮ログファイルを S3などのobject storageへアップロードできなかった場合の保存設定を定義します。
Package objectstoragecompressedlogは、圧縮ログファイルを S3などのobject storageへアップロードできなかった場合の保存設定を定義します。
config/renamedkey
Package renamedkeyは、公開前に綴りを修正した環境変数keyと、値の意味を変えて名前を 変えたkeyについて、旧名と現在のkey名の対応を定義します。
Package renamedkeyは、公開前に綴りを修正した環境変数keyと、値の意味を変えて名前を 変えたkeyについて、旧名と現在のkey名の対応を定義します。
infrastructure/fsstore/checkpoint
Package checkpointは、ログファイルの宛先登録・送信完了記録と、そのファイル保存・再試行を管理します。
Package checkpointは、ログファイルの宛先登録・送信完了記録と、そのファイル保存・再試行を管理します。
infrastructure/fsstore/directorylease
Package directorylease は、同一process内で独立した構成instanceが同じfilesystem directoryを同時に管理しないための排他的なleaseを提供します。
Package directorylease は、同一process内で独立した構成instanceが同じfilesystem directoryを同時に管理しないための排他的なleaseを提供します。
infrastructure/fsstore/directorysize
Package directorysize は、directory内のfile size合計を、filesystem観測を開始するための 概算値として追跡します。
Package directorysize は、directory内のfile size合計を、filesystem観測を開始するための 概算値として追跡します。
infrastructure/fsstore/failurearchive/compressedlog
Package compressedlogarchive は、object storageへ送信できなかった圧縮log fileを 内容を変更せずfilesystemへ永続保存します。
Package compressedlogarchive は、object storageへ送信できなかった圧縮log fileを 内容を変更せずfilesystemへ永続保存します。
infrastructure/fsstore/spool/objectstorage
Package objectstoragespool は、object storageへ送信する圧縮log fileを filesystem上で永続管理します。
Package objectstoragespool は、object storageへ送信する圧縮log fileを filesystem上で永続管理します。
infrastructure/fsstore/spool/retryafter
Package retryafterは、spoolの送信先がRetry-Afterで指定した再送の下限時刻を、 その送信先を担当するrunnerのspoolディレクトリ内へ永続化します。
Package retryafterは、spoolの送信先がRetry-Afterで指定した再送の下限時刻を、 その送信先を担当するrunnerのspoolディレクトリ内へ永続化します。
infrastructure/logbackend/clickhouse/retryclassifier
Package retryclassifierはClickHouse送信失敗のretry可否を分類します。
Package retryclassifierはClickHouse送信失敗のretry可否を分類します。
infrastructure/logbackend/cloudwatchlogs/retryclassifier
Package retryclassifierは、CloudWatch Logs送信失敗のretry可否を分類します。
Package retryclassifierは、CloudWatch Logs送信失敗のretry可否を分類します。
infrastructure/logbackend/cloudwatchlogs/streamrouting
Package streamroutingは、eventを時間単位で分割したCloudWatch Logs streamへ 振り分けるapplication側のrouting policyを定義します。
Package streamroutingは、eventを時間単位で分割したCloudWatch Logs streamへ 振り分けるapplication側のrouting policyを定義します。
infrastructure/logbackend/opensearch/retryclassifier
Package retryclassifierはOpenSearchのrequest単位の失敗を分類します。
Package retryclassifierはOpenSearchのrequest単位の失敗を分類します。
infrastructure/logfile
Package logfileは、ログファイルの処理を進めるための共通部品を提供します。
Package logfileは、ログファイルの処理を進めるための共通部品を提供します。
infrastructure/logfile/lifecycle
Package lifecycleは、ログの保存ディレクトリを一巡し、各系列の圧縮・upload・ 保持設定による削除を進めます。
Package lifecycleは、ログの保存ディレクトリを一巡し、各系列の圧縮・upload・ 保持設定による削除を進めます。
infrastructure/logfile/processing
Package processingは、通常ログとbackend送信失敗archiveのファイルについて、 圧縮・送信と退避・checkpointへの完了反映・削除を一件ずつ進める共通処理を提供します。
Package processingは、通常ログとbackend送信失敗archiveのファイルについて、 圧縮・送信と退避・checkpointへの完了反映・削除を一件ずつ進める共通処理を提供します。
infrastructure/logfile/runner
Package runnerは、ログ保存先のlifecycle処理を定期間隔で実行し、結果を報告します。
Package runnerは、ログ保存先のlifecycle処理を定期間隔で実行し、結果を報告します。
infrastructure/logger/cloudwatchlogs
Package cloudwatchlogs は、アプリケーション内で生成された LogEntry を CloudWatch Logs の PutLogEvents へ送信するロガー実装を提供します。
Package cloudwatchlogs は、アプリケーション内で生成された LogEntry を CloudWatch Logs の PutLogEvents へ送信するロガー実装を提供します。
infrastructure/logger/failure
Package failureは、loggerの送信からdurable failure handlerへ渡す、 backendに依存しない結果を定義します。
Package failureは、loggerの送信からdurable failure handlerへ渡す、 backendに依存しない結果を定義します。
infrastructure/logger/flushfailure
Package flushfailureは、logger backendへの送信失敗後に実行する共通処理を提供します。
Package flushfailureは、logger backendへの送信失敗後に実行する共通処理を提供します。
infrastructure/logger/flushfailure/degradehandler
Package degradehandlerは、主たるdurable failure storeが明示的に無効化されたときに使う、 直接退避の経路を提供します。
Package degradehandlerは、主たるdurable failure storeが明示的に無効化されたときに使う、 直接退避の経路を提供します。
infrastructure/logger/flushfailure/evacuation
Package evacuationは、直接のdegradationと、durable storeのoverload処理とで共有する 退避先のwriterを提供します。
Package evacuationは、直接のdegradationと、durable storeのoverload処理とで共有する 退避先のwriterを提供します。
infrastructure/logger/flushfailure/fsarchivehandler
Package fsarchivehandler はbackend-neutralなfailure archive保存と保守Pipelineを提供します。
Package fsarchivehandler はbackend-neutralなfailure archive保存と保守Pipelineを提供します。
infrastructure/logger/flushfailure/overload
Package overload は、backend送信失敗のdurable保存先が過負荷になった場合の 共通退避境界を提供します。
Package overload は、backend送信失敗のdurable保存先が過負荷になった場合の 共通退避境界を提供します。
infrastructure/logger/handler/reentrytest
Package reentrytestは、内部ログの通知先(OnError・OnWarn・OnInfo・OnDebug)が同じloggerへ 書き込む再入の試験に共通する、書き込み方法と通知の数え方を提供します。
Package reentrytestは、内部ログの通知先(OnError・OnWarn・OnInfo・OnDebug)が同じloggerへ 書き込む再入の試験に共通する、書き込み方法と通知の数え方を提供します。
infrastructure/logger/timestamp
Package timestampは、loggerが確定済みの発生時刻を各出力先の表示規則へ変換する機能を 提供します。
Package timestampは、loggerが確定済みの発生時刻を各出力先の表示規則へ変換する機能を 提供します。
infrastructure/metrics
Package metricsは、system metricsを収集して整形する機能を提供します。
Package metricsは、system metricsを収集して整形する機能を提供します。
infrastructure/notification
Package notificationは、通知関数を受理順に別のgoroutineで実行する共通部品を提供します。
Package notificationは、通知関数を受理順に別のgoroutineで実行する共通部品を提供します。
infrastructure/objectstorage/compressedlogfailure
Package compressedlogfailureは、通常ログの.logとbackend送信失敗レコードの.jsonlの 圧縮ファイルについて、object storageへの送信と失敗時の退避先への保存を合成します。
Package compressedlogfailureは、通常ログの.logとbackend送信失敗レコードの.jsonlの 圧縮ファイルについて、object storageへの送信と失敗時の退避先への保存を合成します。
infrastructure/objectstorage/failurearchive
Package failurearchive はfailure archive用object storage uploadを構成します。
Package failurearchive はfailure archive用object storage uploadを構成します。
infrastructure/shutdown
Package shutdownは、受理済み処理の完了を待つ正常終了の進捗を通知します。
Package shutdownは、受理済み処理の完了を待つ正常終了の進捗を通知します。
infrastructure/spool/compressedlog/internal/testutil
Package replaytestは、compressed logのrunnerとworkerのtestで共有するfixtureを提供します。
Package replaytestは、compressed logのrunnerとworkerのtestで共有するfixtureを提供します。
infrastructure/spool/compressedlog/uploader
Package uploaderは、保存先サービスに対応する圧縮ログspoolの再送部品を構築します。
Package uploaderは、保存先サービスに対応する圧縮ログspoolの再送部品を構築します。
infrastructure/spool/compressedlog/uploader/s3
Package s3は、圧縮ログspoolの再送とS3固有のcircuit breaker分類を提供します。
Package s3は、圧縮ログspoolの再送とS3固有のcircuit breaker分類を提供します。
infrastructure/spool/compressedlog/worker
Package workerは、spoolに保存された圧縮ログをobject storageへ再送します。
Package workerは、spoolに保存された圧縮ログをobject storageへ再送します。
infrastructure/spool/log/sender/storedvalue
Package storedvalueは、spoolに保存されたrecordの値を保持し得る検証errorを、表示文と 種類のsentinelだけを残したerrorへ置き換えます。
Package storedvalueは、spoolに保存されたrecordの値を保持し得る検証errorを、表示文と 種類のsentinelだけを残したerrorへ置き換えます。
infrastructure/victoriametrics
Package victoriametricsは、VictoriaMetricsへmetricsをpushする機能を提供します。
Package victoriametricsは、VictoriaMetricsへmetricsをpushする機能を提供します。
pathcaserule
Package pathcaseruleは、試験だけがpathidentityのdirectoryの大小文字の規則を差し替えるための 内部hookです。
Package pathcaseruleは、試験だけがpathidentityのdirectoryの大小文字の規則を差し替えるための 内部hookです。
presentation/cli/logrecovery
Package logrecovery はアプリケーション停止中の手動ログ復旧CLIを提供します。
Package logrecovery はアプリケーション停止中の手動ログ復旧CLIを提供します。
presentation/envconfig
Package envconfigは、HETEROLOG_の環境変数とenv fileから届く設定の入力窓口です。
Package envconfigは、HETEROLOG_の環境変数とenv fileから届く設定の入力窓口です。
presentation/http/admin
Package adminは、稼働中のloggerの出力先ごとのlog levelとsampling設定を読み取り・ 変更する、HTTPの管理用APIの受け口です。
Package adminは、稼働中のloggerの出力先ごとのlog levelとsampling設定を読み取り・ 変更する、HTTPの管理用APIの受け口です。
presentation/sloghandler
Package sloghandlerは、標準libraryのlog/slogから届くlogの入力窓口です。
Package sloghandlerは、標準libraryのlog/slogから届くlogの入力窓口です。
testutil
Package testutilは、ファイルシステム関連の回帰試験で共用する補助関数を提供します。
Package testutilは、ファイルシステム関連の回帰試験で共用する補助関数を提供します。
testutil/boundedwait
Package boundedwaitは、試験が処理の完了を待つ時間に上限を設ける共通helperです。
Package boundedwaitは、試験が処理の完了を待つ時間に上限を設ける共通helperです。
testutil/checkpoint
Package checkpointtestは、checkpointの統合test用のfilesystem fixtureを提供します。
Package checkpointtestは、checkpointの統合test用のfilesystem fixtureを提供します。
testutil/configfixture
Package configfixtureは、公開されている環境設定の例からofflineのfixtureを作成します。
Package configfixtureは、公開されている環境設定の例からofflineのfixtureを作成します。
testutil/errortree
Package errortreeは、errors.Joinや%wでまとめたerror treeから型付きerrorを探す試験用helperです。
Package errortreeは、errors.Joinや%wでまとめたerror treeから型付きerrorを探す試験用helperです。
testutil/uploadertest
Package uploadertestは試験用の送信入力をコンストラクタ経由で作成します。
Package uploadertestは試験用の送信入力をコンストラクタ経由で作成します。
pkg
admin
Package admin holds the configuration types of the admin API, which reads and changes the level and sampling of the outputs of running loggers.
Package admin holds the configuration types of the admin API, which reads and changes the level and sampling of the outputs of running loggers.
cloudwatchlogs
Package cloudwatchlogs provides a lightweight client that calls the AWS CloudWatch Logs PutLogEvents and CreateLogStream APIs with SigV4-signed HTTP requests.
Package cloudwatchlogs provides a lightweight client that calls the AWS CloudWatch Logs PutLogEvents and CreateLogStream APIs with SigV4-signed HTTP requests.
env
Package env reads the values of environment variables as typed configuration values.
Package env reads the values of environment variables as typed configuration values.
failurestore
Package failurestore defines the durable store selection values shared by failure pipelines with different payload formats.
Package failurestore defines the durable store selection values shared by failure pipelines with different payload formats.
internal/endpointurl
Package endpointurlは、pkg配下のclientが送信先endpointのURLを解析するときに、URLのuser info (ユーザー名・パスワード)を解析エラーの文面へ含めないための補助です。
Package endpointurlは、pkg配下のclientが送信先endpointのURLを解析するときに、URLのuser info (ユーザー名・パスワード)を解析エラーの文面へ含めないための補助です。
objectstorage/validation
Package validation validates the typed settings of object storage upload destinations.
Package validation validates the typed settings of object storage upload destinations.
observer
Package observer defines the instrumentation interfaces that heterolog loggers report to.
Package observer defines the instrumentation interfaces that heterolog loggers report to.
path/internal/statehome
Package statehomeは、Linuxなどのunix系OSでrootで動いていない利用者について、保存先の 既定の基点directoryにするstate directory(XDG Base Directory仕様)を決めます。
Package statehomeは、Linuxなどのunix系OSでrootで動いていない利用者について、保存先の 既定の基点directoryにするstate directory(XDG Base Directory仕様)を決めます。
path/pathidentity
Package pathidentity resolves the real path of a storage location when the location is initialized, and generates comparison keys for paths.
Package pathidentity resolves the real path of a storage location when the location is initialized, and generates comparison keys for paths.
retry
Package retry runs a function again after it fails.
Package retry runs a function again after it fails.
shutdown
Package shutdown defines the result of an explicit forced shutdown.
Package shutdown defines the result of an explicit forced shutdown.
spool
Package spool defines the records that the spool keeps for log entries whose delivery failed, and the per-record results that the replay workers collect when they resend a batch of those records to the backend.
Package spool defines the records that the spool keeps for log entries whose delivery failed, and the per-record results that the replay workers collect when they resend a batch of those records to the backend.
spool/spoollifecycle
Package spoollifecycle holds the settings that control the retention of finalized spool records.
Package spoollifecycle holds the settings that control the retention of finalized spool records.
spool/spoolrunner
Package spoolrunner holds the settings of the workers that replay durable failure spools.
Package spoolrunner holds the settings of the workers that replay durable failure spools.
spool/spoolsupervisor
Package spoolsupervisor holds the settings of the supervisor that restarts spool replay workers.
Package spoolsupervisor holds the settings of the supervisor that restarts spool replay workers.
testenv
windows/configfixture command
configfixtureは、Windowsのtest用にofflineの設定rootを生成します。
configfixtureは、Windowsのtest用にofflineの設定rootを生成します。
windows/directory-sync-probe command
directory-sync-probeは、新しく作成したtest directoryで、Windowsのdirectory flush APIを 比較します。
directory-sync-probeは、新しく作成したtest directoryで、Windowsのdirectory flush APIを 比較します。

Jump to

Keyboard shortcuts

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