heterolog

package module
v0.7.0 Latest Latest
Warning

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

Go to latest
Published: Oct 31, 2026 License: MIT Imports: 26 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 logging library for Go applications whose logs must arrive. One logging call writes to several destinations at once: stdout, files, Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse. When a log server cannot be reached, the log is kept on local disk and sent again when the server is back, even after the application restarts. You can use it through the standard log/slog package.

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

This README is an overview. The reference describes the behavior in detail, and the API is documented on pkg.go.dev. Most other documents in this repository, including the comments in .env.example, are written in Japanese.

Contents

Why heterolog

A common setup writes logs to stdout or a file and leaves their delivery to a separate log shipper, an agent or sidecar such as Fluent Bit or Vector. heterolog sends the logs from the application itself instead:

  • The application learns what happened to each log. The regular API returns an error when a log could not be written 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.
  • Logs that could not be sent are not lost. They are saved to a local spool and sent again when the destination recovers, following Retry-After, also after a restart. This covers what the disk buffer of an agent usually provides. A log whose outcome is unknown is set aside for a person to check, instead of being sent twice or deleted.
  • There is nothing else to deploy. There is no extra process to size, monitor, and upgrade next to each application, and no intermediate file or socket that can fill up or stall. This also suits Go programs that are themselves agents, daemons, or command-line tools.
  • The level can change without a restart. For example, switch an output to DEBUG with one HTTP request during an investigation, and back again afterwards.

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. Another tool may fit better:

  • If you only need structured logs on stdout, log/slog alone, or a library such as zap or zerolog, is simpler.
  • If many programs written in different languages share a host, or routing must be changed in one central place, a dedicated log shipper is usually the better choice.

Features

  • Destinations: stdout, file, Slack, OpenSearch, Loki, CloudWatch Logs, and ClickHouse, in any combination.
  • Three loggers with different guarantees: synchronous (returns errors), asynchronous (best effort), and delivery (reports the result for each destination).
  • A log/slog handler.
  • Log files with rotation, compression (gzip, zstd, lz4, xz), retention, and upload to S3 or S3-compatible storage such as Backblaze B2.
  • A local spool for logs that could not be sent, replayed automatically and following Retry-After 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 and an env file.
  • Level and sampling changes while running, in code or through a token-protected HTTP API, which also reports the configuration in use and the status of the process, destinations, spools and disks, with warnings, and serves a browser page for all of it.
  • Traces: a Tracer, and an exporter for the OpenTelemetry SDK, that send spans to an OTLP/HTTP receiver, OpenSearch (for its Trace Analytics), ClickHouse (in the table of the OpenTelemetry Collector), a file, or stdout in batches with retries. Spans that could not be sent go to the same spool and failure archive as logs. The loggers can record their own work as spans.
  • Metrics: a Meter that sends counters, gauges, and histograms to an OTLP/HTTP receiver, VictoriaMetrics, a file, or stdout, with the same retries, spool, and failure archive.
  • A CLI that recovers the 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

The following program writes two logs to stdout. A similar program is in examples/slog; in a checkout of this repository, run it with 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 logs are written to standard output and WARN and ERROR logs to standard error, with timestamps in UTC. To use it as the global logger, call slog.SetDefault(logger). slog and each output filter by level separately, so to write DEBUG logs, lower both levels (see Using slog).

Sending logs to several destinations

The quickest way is an env file that LoadEnvConfig reads. This one writes to stdout, a log file, and Loki:

# logging.env
HETEROLOG_TARGET=my-service
HETEROLOG_LOG_TYPE=stdout,file,loki
HETEROLOG_LOKI_ENDPOINT=http://loki.example.internal:3100
env, err := heterolog.LoadEnvConfig("logging.env") // "" reads only environment variables
if err != nil {
    log.Fatal(err)
}
runtime, err := env.New(ctx) // env.NewAsync and env.NewDelivery work the same way
if err != nil {
    log.Fatal(err)
}
defer runtime.Close()

logger := slog.New(heterolog.NewSlogHandler(runtime, nil))
logger.InfoContext(ctx, "service started")
  • HETEROLOG_TARGET is the name of the application in file and directory names. By default, log files go under $XDG_STATE_HOME (or ~/.local/state) on Linux and the BSDs (/var/log when running as root), ~/Library/Logs on macOS, and %LOCALAPPDATA% on Windows. This example writes my-service/logs/my-service_<date>_1.log there, and ERROR and DEBUG logs to files of their own.
  • Settings that you leave out use their defaults, so the file only needs what differs. .env.example lists every key (its comments are in Japanese). Its values are a sample configuration and differ from the defaults in places.
  • Without any settings, every logger writes to stdout only. Other destinations are used only when you select them, and missing credentials are reported as errors instead of being filled in.
  • The settings are checked when they are loaded, and all problems are reported together.
  • A variable set in the environment overrides the same key in the file. The process environment is not modified, and no other file is read.
Default levels and sampling

Unless you set them, every output records INFO and above, except Slack, which is meant for notifications and records ERROR and above. Sampling is off, so every log at or above the level is kept:

Output Level Sampling
Slack ERROR off
stdout, file, OpenSearch, Loki, CloudWatch Logs, ClickHouse INFO off
  • The keys are HETEROLOG_<OUTPUT>_LOG_LEVEL for the level and HETEROLOG_ENABLE_LOG_<OUTPUT>_SAMPLING for sampling, where <OUTPUT> is STDOUT, FILE, SLACK, OPENSEARCH, LOKI, CLOUDWATCH, or CLICKHOUSE. The asynchronous logger has its own keys with ASYNC_ in the name.
  • With sampling on, a rate of N keeps 1 in N logs of that level, and logs that carry a request ID (heterolog.WithRequestID, or a string request_id attribute in slog) can be kept or skipped by request instead, so the logs of a kept request are complete. Set the rates when you turn sampling on: rates you leave out keep their defaults, such as 1 in 1,000 INFO logs for OpenSearch, Loki, CloudWatch Logs, and ClickHouse.
  • The level and sampling can also be changed while running.
  • The delivery logger does not sample, and only its Slack output filters by level (ERROR).
Configuring in code

heterolog.DefaultConfig() returns a configuration that writes to stdout. Set other fields of Config, such as File and Loki, to add destinations; the pkg/logger documentation describes every setting. To start from the environment and adjust the configuration in code, get it with cfg, opts, err := env.Config() and pass it to heterolog.New(ctx, cfg, opts...).

Choosing a logger

There are three loggers. They differ in what a logging call tells the caller:

Constructor A logging call returns Use it for
New an error logs that must not be lost silently
NewAsync nothing, without waiting for the send high-volume logs
NewDelivery a DeliveryReport and an error logs whose next step depends on where they arrived

NewSlogHandler turns a logger from New into a slog.Handler. slog.Logger drops the errors of its handler, so call the logger directly when you need them:

jobID := heterolog.MustFieldKey("job_id")
if err := runtime.Info(ctx, "job completed", jobID.Int(42)); err != nil {
    // The log could not be written or kept.
}

A delivery report has the result of each destination, and tells confirmed success apart from failure, rejection before sending, an unknown outcome, and acceptance into a send queue:

delivery, err := heterolog.NewDelivery(ctx, heterolog.DefaultDeliveryConfig())
if err != nil {
    log.Fatal(err)
}
defer delivery.Close()

report, err := delivery.Info(ctx, "payment captured")
if err != nil || report.HasUnregisteredTarget() {
    // Some destination has not confirmed the log; report.Targets has the result of each.
}

A successful call of the regular API can mean that the log was accepted into a buffer; it does not guarantee that the log arrived. Only the delivery logger reports arrival.

When a destination fails

For OpenSearch, Loki, CloudWatch Logs, and ClickHouse, a log that could not be sent is handled according to the failure:

What happened What heterolog does
A temporary failure, such as a timeout, 429, or 5xx Saves the log to the spool and sends it again later, following Retry-After, also after a restart
The outcome is unknown, for example because the connection broke after sending Moves the log to quarantine. It is not sent again automatically, because it may already have arrived
The destination rejected the content of the log Splits the batch to find the rejected logs, and moves only those to quarantine
The destination or the settings are wrong, such as rejected authentication or a missing table Moves the logs to dead
  • Saved logs are not deleted by default, because they may be the only copy. To keep the disk from filling up, new failures are instead discarded (drop, reported as ErrLogDropped) or written to stdout (degrade) while free space is below HETEROLOG_MIN_AVAILABLE_DISK_SPACE_GB.
  • When the choice is between sending a log twice and losing it, heterolog sends it twice.
  • With the environment configuration, the regular and asynchronous loggers use the spool by default. The delivery logger does not replay: it saves failed logs to local files and reports every result to the caller.
  • Slack keeps no failed logs. Log files that could not be uploaded to S3 are kept and uploaded again.

The reference describes the rules in detail.

Changing the level and sampling while running

Each output of the regular and asynchronous loggers has a level and sampling settings that you can change while the application runs, without restarting it or rebuilding the logger. A change applies from the next log and is kept in memory only, so a restart returns to the configured values, and a temporary change cannot stay by accident.

To change them from outside the process, start the admin API:

# logging.env
# An empty host listens on 127.0.0.1 only.
HETEROLOG_ADMIN_ADDR=:9100
# At least 32 bytes, for example the output of: openssl rand -hex 32
HETEROLOG_ADMIN_TOKEN=<token>
if adminCfg, ok := env.AdminServerConfig(); ok {
    // Records every change request; by default to stdout and a file in audit_logs.
    audit, err := env.NewAdminAudit(ctx)
    if err != nil {
        log.Fatal(err)
    }
    defer audit.Close()
    members := heterolog.AdminMembers{
        // Loggers: the settings can be read and changed, and the configuration is reported.
        Loggers: map[string]heterolog.SettingsController{"app": runtime},
        // DeliveryLoggers and Telemetries: the configuration is reported.
        DeliveryLoggers: map[string]heterolog.DeliveryLogger{"audit": audit},
    }
    admin, err := heterolog.StartAdminServer(adminCfg, members, audit)
    if err != nil {
        log.Fatal(err)
    }
    defer admin.Close()
}

The name given to each member (here app and audit) is its key in the JSON:

# Show the settings of every logger
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/settings

# Show the configuration every member was created with (tokens and keys are masked)
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/config

# Show one value of it, or several in one request
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/config/loggers/app/config/timeout
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" \
  "http://127.0.0.1:9100/config?path=loggers/app/config/timeout&path=loggers/app/config/max_log_entry_bytes"

# Show the status: CPU and memory, every destination, spools, directories, and warnings
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/status
curl -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" http://127.0.0.1:9100/status/warnings

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

# Keep 1 in 10 INFO logs in the log file
curl -X PATCH -H "Authorization: Bearer $HETEROLOG_ADMIN_TOKEN" \
  -d '{"loggers":{"app":{"outputs":{"file":{"sampling":{"enabled":true,"by_request_id":false,"debug_rate":1,"info_rate":10,"warn_rate":1,"error_rate":1}}}}}}' \
  http://127.0.0.1:9100/settings

Every request returns the settings of every logger. For example, this is the stdout part after the second request (the file and loki outputs are omitted):

{
  "loggers": {
    "app": {
      "outputs": {
        "stdout": {
          "level": "DEBUG",
          "sampling": {
            "enabled": false,
            "by_request_id": true,
            "request_id_rate": 10,
            "debug_rate": 1,
            "info_rate": 1,
            "warn_rate": 1,
            "error_rate": 1
          }
        }
      }
    }
  }
}
  • A rate of N keeps 1 in N logs of that level. With by_request_id, logs that carry a request ID are kept or skipped by request (1 in request_id_rate requests), so the logs of a kept request are complete.
  • Levels are DEBUG, INFO, WARN, and ERROR. Fields omitted in a PATCH keep their values. A PATCH is checked as a whole: if any change is invalid, nothing is applied, and the response is 400 with the reason.
  • Every request needs the token. It is compared in constant time and never appears in errors. To listen on an address other than 127.0.0.1, give the host and a TLS certificate and key (HETEROLOG_ADMIN_TLS_CERT_FILE and HETEROLOG_ADMIN_TLS_KEY_FILE), so the token is not sent in clear text.
  • Changes are processed one at a time, and each is recorded in an audit log: the request, the settings when the change starts, the settings after it, and every rejected request (only a successful GET is not recorded). Every record has the field log_kind=audit and the request ID, which the response also returns in X-Request-Id.
  • The audit log is written by a delivery logger of its own, by default to stdout and to a file in audit_logs, next to the other log directories. Other outputs, such as CloudWatch Logs, can be chosen with HETEROLOG_ADMIN_AUDIT_LOG_TYPE; see Audit log of the admin API.
  • If the settings after a change do not match the request, the change is not reverted: the response is 500 with the current settings, and the mismatch is recorded at ERROR, which a Slack output of the audit log turns into a notification. If an audit record does not reach every output, the change still goes ahead and the response carries a warning.
  • To serve the API from your own HTTP server, use NewAdminHandler with the same audit logger. In code, runtime.OutputSettings() returns the settings and runtime.UpdateOutputSettings(changes) changes them.
  • Only the level and sampling can change while running; destinations and storage cannot. The delivery logger has no such settings.
  • GET /config returns the configuration each member was created with, as JSON with snake_case keys, and GET /config/<path> returns one value of it (GET /config?path=...&path=... several). Tokens, passwords, and keys are shown as ***. Delivery loggers and telemetries added to AdminMembers are reported too.
  • The same server serves a browser page at /: open http://127.0.0.1:9100/, enter the token (kept in the browser's session storage, so it is gone when the tab closes), and view the status with its warnings, change the level and sampling, and read the configuration. The page is English with a Japanese switch and loads nothing from other sites.
  • GET /status returns the CPU and memory of the process, the records, request durations and retries of every destination, the state of each spool (files per state, resend, last purge) and the directories in use with their free disk space, together with warnings (a disk nearly full, a slow or failing destination, a stopped resend, and so on), critical ones first. File counts come from a background scan every 5 minutes (HETEROLOG_ADMIN_STATUS_DIRECTORY_SCAN_INTERVAL_SECOND, 0 turns it off) and are approximate. See Status of the loggers.

See Changing settings while running for details.

Log files

  • Rotation every day, week (from Sunday 0:00 UTC), or month, and to a new file when a file reaches its maximum size.
  • ERROR and DEBUG logs can go to files of their own (the environment configuration does so by default).
  • Compression with gzip, zstd, lz4, or xz. A compressed file is compared with the original log before the original is deleted.
  • Retention by the number of generations, age, and directory size.
  • Upload of compressed files to S3, with upload records that survive restarts.
  • File names are matched according to the case rule of the file system (Windows, macOS, and case-insensitive directories on Linux).

The reference describes rotation, retention, compression, and uploads in detail.

Traces

NewTelemetry sends spans to an OTLP/HTTP receiver, such as the OpenTelemetry Collector or Grafana Tempo, to OpenSearch, to ClickHouse, to a file, or to stdout. Its Tracer records the spans of your application, and passed to a logger with WithObservers, also the work of the logger as child spans:

cfg := heterolog.DefaultTelemetryConfig()
cfg.Resource.ServiceName = "checkout"
cfg.Traces.Exporters = []heterolog.TraceExporter{heterolog.TraceExporterOTLP}
cfg.Traces.OTLP.Endpoint = "http://localhost:4318/v1/traces"
tel, err := heterolog.NewTelemetry(ctx, cfg)
if err != nil {
    log.Fatal(err)
}
defer tel.Shutdown(context.Background())

runtime, err := heterolog.New(ctx, heterolog.DefaultConfig(),
    heterolog.WithObservers(tel.Tracer(), nil))
if err != nil {
    log.Fatal(err)
}
defer runtime.Close()

ctx, span := tel.Tracer().StartSpan(ctx, "checkout")
defer span.End()
  • From the environment, set HETEROLOG_ENABLE_TRACES=true and HETEROLOG_TRACES_OTLP_ENDPOINT, and call env.NewTelemetry(ctx). The service name comes from HETEROLOG_APP_NAME.
  • Spans are sent in batches from a queue for each destination, so ending a span never waits for the network. Failed requests are retried. Spans that the receiver still did not accept can be kept in the same spool and failure archive as logs, and the spool resends them when the receiver recovers, also after a restart. Spans that are not kept, or that do not fit in the queue, are dropped, counted in metrics, and reported to the function passed with WithTelemetryErrorHandler, or to the standard logger without it.
  • TraceExporterOpenSearch writes each span as a document in the format of OpenSearch Data Prepper, so the Trace Analytics of OpenSearch Dashboards can show the spans. Install the index template first.
  • TraceExporterClickHouse inserts each span into a table with the columns of the otel_traces table of the OpenTelemetry Collector, which the ClickHouse data source of Grafana reads. Create it with otel_traces.sql first.
  • pkg/observer reads and writes the W3C traceparent header, so a trace can continue across services.
  • Spans from the OpenTelemetry SDK are sent the same way through otelexport.NewSpanExporter(tel), a separate package so that programs without the SDK do not link it.

See Sending traces for details.

Metrics

The same Telemetry sends metrics to an OTLP/HTTP receiver, such as the OpenTelemetry Collector, Prometheus, or VictoriaMetrics, to the Prometheus import API of VictoriaMetrics, to a file, or to stdout. Its Meter records counters, gauges, and histograms, and passed to a logger with WithObservers, also the heterolog_* metrics of the logger:

cfg.Metrics.Exporters = []heterolog.MetricExporter{heterolog.MetricExporterOTLP}
cfg.Metrics.OTLP.Endpoint = "http://localhost:4318/v1/metrics"
tel, err := heterolog.NewTelemetry(ctx, cfg)

tel.Meter().Counter("orders_total").Add(ctx, 1, heterolog.ObserverAttr{Key: "region", Value: "eu"})
  • From the environment, set HETEROLOG_ENABLE_METRICS=true and HETEROLOG_METRICS_OTLP_ENDPOINT.
  • The values are collected every ExportInterval (one minute by default) and sent as cumulative values, so a collection that is dropped or lost still leaves the totals in the next one.
  • Metrics from the OpenTelemetry SDK are sent the same way through otelexport.NewMetricExporter(tel), passed to an SDK reader.
  • Metrics that could not be sent go to the same spool and failure archive as logs and spans. Because an uncertain send is resent rather than lost, the same value can arrive twice; with cumulative values, the second one is the same value at the same time.

See Sending metrics for details.

Shutting down

  • Call Close or Shutdown(ctx) before the application exits. They finish accepted work, flush buffers, and release resources. A Telemetry sends its queued spans, and collects and sends its metrics one last time, in Shutdown(ctx); close the loggers that use its Tracer and Meter first.
  • When the context of Shutdown ends, only that call stops waiting; the cleanup continues. ForceClose asks the cleanup to stop and returns without waiting.
  • Logs left in the spool are sent after the next start.

See Shutdown for details.

Recovering logs of a stopped application

The repository also has a CLI that recovers the log files of a stopped application, with the same environment configuration as the application:

go build -o log-recovery ./cmd/log-recovery
./log-recovery --target my-service --application-stopped --env-file /path/to/logging.env

See Log recovery CLI for its checks and options, and manual log recovery (in Japanese) for what it recovers and how to operate it.

Testing

go test ./...
go vet ./...

The regular tests need no external service. CI also runs the whole suite on Windows and macOS, and on Linux with a case-insensitive and with a symlinked temporary directory, and runs integration tests against OpenSearch, Loki, ClickHouse, Tempo, and the OpenTelemetry Collector in containers. See Testing for race tests and integration tests with real services.

Design decisions

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.
  • Sampling is opt-in. By default, every output records every log at INFO and above (Slack, which is meant for notifications, at ERROR and above), so no log at or above the level is skipped unless you turn sampling on.
  • 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.

NewTelemetry records spans with its Tracer and metrics with its Meter, and sends them, together with those from the OpenTelemetry SDK passed through package otelexport: spans to OTLP/HTTP receivers, OpenSearch, ClickHouse, files, and stdout, and metrics to OTLP/HTTP receivers, VictoriaMetrics, files, and stdout. Pass its Tracer and Meter to loggers with WithObservers to trace and measure their work.

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 = pkglogger.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 = pkglogger.ConfigFieldMaxParallel
)
View Source
const (
	TraceExporterOTLP   = pkgtelemetry.TraceExporterOTLP
	TraceExporterFile   = pkgtelemetry.TraceExporterFile
	TraceExporterStdout = pkgtelemetry.TraceExporterStdout

	TraceExporterOpenSearch = pkgtelemetry.TraceExporterOpenSearch
	TraceExporterClickHouse = pkgtelemetry.TraceExporterClickHouse
)
View Source
const (
	MetricExporterOTLP   = pkgtelemetry.MetricExporterOTLP
	MetricExporterFile   = pkgtelemetry.MetricExporterFile
	MetricExporterStdout = pkgtelemetry.MetricExporterStdout

	MetricExporterVictoriaMetrics = pkgtelemetry.MetricExporterVictoriaMetrics
)
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
	// ErrAdminAuditLoggerRequired reports an admin API without the delivery
	// logger that records its audit log.
	ErrAdminAuditLoggerRequired = outputsettings.ErrNoAuditLogger
	// ErrAdminSharedLiveSettings reports that two outputs of the loggers given
	// to the admin API share one pkg/logger LiveSettings, set through
	// RuntimeConfig.Live, in one logger or in different loggers. A logger given
	// under two names shares all of its outputs. A change of one output would
	// also change the other, which the audit log could neither record nor
	// verify.
	ErrAdminSharedLiveSettings = outputsettings.ErrSharedLiveSettings
	// ErrAdminDuplicateName reports a name used in more than one map of
	// AdminMembers.
	ErrAdminDuplicateName = admin.ErrDuplicateName
	// ErrAdminInvalidStatusConfig reports an AdminStatusConfig with a negative
	// duration or a percentage outside 0 to 100.
	ErrAdminInvalidStatusConfig = admin.ErrInvalidStatusConfig
	// 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, NewDelivery or NewTelemetry
	// 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 ErrEnvAdminAuditNotEnabled = envconfig.ErrAdminAuditNotEnabled

ErrEnvAdminAuditNotEnabled reports that EnvConfig has no settings for the audit logger of the admin API because HETEROLOG_ADMIN_ADDR is empty.

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, audit *DeliveryRuntime) (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 and reports the configuration of loggers and telemetries. 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
GET   /config         returns the configuration of every member
GET   /config/<path>  returns one value of that configuration
GET   /status         returns the status of the process and every member
GET   /status/<path>  returns one value of that status
GET   /               serves a browser page that uses the API (with /ui.css and /ui.js)

Every request except the three files of the browser page must send "Authorization: Bearer <Token>"; the page asks for the token and keeps it in the browser's session storage. PATCH requests are processed one at a time, and 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.

GET /config returns the configuration each member was created with, as the structs of Config, AsyncConfig, DeliveryConfig and TelemetryConfig in JSON with snake_case keys. Tokens, passwords and keys are replaced by "***". Only members created by heterolog are reported; other implementations of SettingsController, DeliveryLogger and Telemetry are left out. Changes made through PATCH /settings are not part of it. GET /config/<path> walks the document by its keys and array indexes, for example /config/loggers/app/config/file/log_dir, and is 404 when the path does not exist, and GET /config?path=<path>&path=<path> returns several values in one request, as {"values": {"<path>": ...}}. It returns ErrAdminDuplicateName if a name is used in more than one map of cfg.Members.

GET /status returns the CPU, memory and goroutines of the process, and for every member the records, request durations, retries, circuit breaker, failure store and spool of each destination, the directories in use with their size limits and free disk space, and the warnings judged from them (disk nearly full, a destination slow or failing, a spool whose resend stopped, and so on), critical ones first. The file counts come from a background scan at the interval of cfg.Status and are approximate; they are reported with the time of the scan. GET /status/<path> and ?path= work as for /config. It returns ErrAdminInvalidStatusConfig if cfg.Status is out of range.

audit records the audit log of the API: each change request, the settings when the change starts and after it, and every rejected request; only a successful GET is not recorded. Every record has the field log_kind=audit and the request ID, which the response also sends in X-Request-Id. When the settings after a change do not match the request, the change is not reverted: the mismatch is recorded at ERROR and the response is 500. When a record does not reach every output of audit, the change still goes ahead, the response carries a warning, and this is recorded at ERROR too. Use a delivery logger made for the audit log, such as the one of EnvConfig.NewAdminAudit, and close it after the handler is no longer used. It returns ErrAdminAuditLoggerRequired if audit is nil.

Each output of the loggers must have its own settings, so that every change is recorded and verified for the output it changes. It returns ErrAdminSharedLiveSettings if two outputs share one LiveSettings. Loggers created by New and NewAsync are checked; other implementations of SettingsController are not.

Types

type AdminHandlerConfig added in v0.3.0

type AdminHandlerConfig = pkgadmin.HandlerConfig

AdminHandlerConfig configures NewAdminHandler: the bearer Token (at least MinAdminTokenLength bytes) and the Members served by the API.

type AdminMembers added in v0.7.0

type AdminMembers = pkgadmin.Members

AdminMembers are the loggers and telemetries the admin API serves, each under the name used in the API: Loggers, whose settings it reads and changes and whose configuration it reports, and DeliveryLoggers and Telemetries, whose configuration it reports. A name must not appear in more than one map.

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, members AdminMembers, audit *DeliveryRuntime) (*AdminServer, error)

StartAdminServer starts a dedicated HTTP server for the admin API of NewAdminHandler and returns once it listens. members are the loggers and telemetries served under the names used in the API, and audit records the audit log; both are checked as in NewAdminHandler. The server listens on a loopback address unless cfg names another host and enables TLS. Call Shutdown or Close to stop it, and close audit after that.

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 is as in AdminHandlerConfig.

type AdminStatusConfig added in v0.7.0

type AdminStatusConfig = pkgadmin.StatusConfig

AdminStatusConfig configures GET /status of the admin API: the interval of the directory scans, whether they run at all, and the thresholds of the warnings. A zero field uses the default of DefaultAdminStatusConfig.

func DefaultAdminStatusConfig added in v0.7.0

func DefaultAdminStatusConfig() AdminStatusConfig

DefaultAdminStatusConfig returns the default settings of GET /status: a directory scan every 5 minutes, disk warnings below 10% and 5% free, directory warnings from 90% of the limit, and backend warnings above 10% failed records or 5 seconds per request on average.

type AppliedOutputSettings added in v0.5.0

type AppliedOutputSettings = pkglogger.AppliedOutputSettings

AppliedOutputSettings holds the settings of one output right before and right after UpdateOutputSettings changed it.

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

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.

Loggers constructed from the environment do not trace or measure by themselves: pass the Tracer and the Meter of the Telemetry that NewTelemetry constructs from the HETEROLOG_TRACES_* and HETEROLOG_METRICS_* settings with 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) AdminAuditConfig added in v0.5.0

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

AdminAuditConfig returns the settings of the delivery logger that records the audit log of the admin API, and the options for NewAdminAudit. Its outputs are HETEROLOG_ADMIN_AUDIT_LOG_TYPE, by default stdout and file, and the HETEROLOG_ADMIN_AUDIT_* settings give where each output records, such as the file directory, by default audit_logs. The other settings, such as endpoints, credentials and timeouts, are those of the delivery logger (HETEROLOG_DELIVERY_*), even when HETEROLOG_ENABLE_DELIVERY_LOGGING is false. The audit logger keeps its own directories: its files are written to one file per period for every level, are not compressed, uploaded or removed, and its failure archives use their own directories. It returns ErrEnvAdminAuditNotEnabled when HETEROLOG_ADMIN_ADDR is empty.

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 together with the audit logger of NewAdminAudit.

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) NewAdminAudit added in v0.5.0

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

NewAdminAudit constructs the audit logger of the admin API from the settings and options that AdminAuditConfig returns, followed by opts. Pass it to StartAdminServer or NewAdminHandler, and close it after the admin API stops.

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.

func (*EnvConfig) NewTelemetry added in v0.7.0

func (c *EnvConfig) NewTelemetry(ctx context.Context, opts ...Option) (*Telemetry, error)

NewTelemetry constructs a Telemetry from the settings that TelemetryConfig returns. Of opts, only the Meter of WithObservers and WithTelemetryErrorHandler are used, as with the package-level NewTelemetry.

func (*EnvConfig) TelemetryConfig added in v0.7.0

func (c *EnvConfig) TelemetryConfig() TelemetryConfig

TelemetryConfig returns the settings for NewTelemetry. The trace settings are read from HETEROLOG_ENABLE_TRACES and HETEROLOG_TRACES_*, the metric settings from HETEROLOG_ENABLE_METRICS and HETEROLOG_METRICS_*, and Resource from the settings that loggers also use, such as HETEROLOG_APP_NAME and HETEROLOG_APP_ENV. A signal that is not enabled has no destinations, and a Telemetry records nothing for it. LoadEnvConfig has already checked them.

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 Histogram added in v0.7.0

type Histogram = pkgobserver.Histogram

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 MetricExporter added in v0.7.0

type MetricExporter = pkgtelemetry.MetricExporter

MetricExporter names a destination of metrics in TelemetryConfig.

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.

func WithTelemetryErrorHandler added in v0.7.0

func WithTelemetryErrorHandler(handler func(error)) Option

WithTelemetryErrorHandler sets the function that a Telemetry calls with the errors of its delivery: a batch of spans that could not be sent after the retries, spans that a receiver rejected, and spans dropped because a queue was full or because they ended after Shutdown started. Dropped spans are reported in one error per destination at most once per ExportInterval.

The function may be called concurrently from several goroutines, and the delivery to a destination waits until it returns, so it should return quickly. A panic in it is recovered and written to the standard logger. Without this option, each error is written as one line to the standard logger. To pass the errors to the error handler of the OpenTelemetry SDK, pass otel.Handle. Loggers do not use this option.

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 some Sampling fields 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

UpdateOutputSettings changes the level and sampling of outputs while the logger runs and returns the settings of each changed output right before and after the change. It applies each change to the settings current when it runs, so changes to different fields made at the same time, for example through the admin API, do not undo each other. 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 SamplingChange added in v0.5.0

type SamplingChange = pkglogger.SamplingChange

SamplingChange changes the fields of the sampling settings of one output that it sets. A nil field keeps the current value. See pkg/logger.

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 Telemetry added in v0.7.0

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

Telemetry records spans and metrics with its Tracer and Meter and delivers them, together with those from the OpenTelemetry SDK passed through package otelexport, to the destinations of its TelemetryConfig. Obtain one with NewTelemetry; the zero value records nothing. Do not copy a Telemetry.

func NewTelemetry added in v0.7.0

func NewTelemetry(ctx context.Context, cfg TelemetryConfig, opts ...Option) (*Telemetry, error)

NewTelemetry starts delivering spans and metrics to the destinations of cfg. It returns the errors of cfg.Validate, and ErrNilContext for a nil ctx. ctx applies only to construction. Call Shutdown when the application exits to send the spans and metrics that are still queued.

Of opts, only the Meter of WithObservers and WithTelemetryErrorHandler are used: the Meter records the heterolog_trace_* and heterolog_metric_* metrics of the delivery, and the error handler receives its errors. The delivery does not create spans for its own sending, so the Tracer of WithObservers is not used.

To trace and measure the work of loggers, pass the Tracer and the Meter of the Telemetry to the loggers with WithObservers.

func (*Telemetry) Meter added in v0.7.0

func (t *Telemetry) Meter() Meter

Meter returns the Meter that records metrics. Counters are sent as cumulative sums, gauges as their last value, and histograms with the buckets of MetricsConfig.HistogramBounds, every MetricsConfig.ExportInterval. Without metric destinations, the Meter records nothing.

func (*Telemetry) Shutdown added in v0.7.0

func (t *Telemetry) Shutdown(ctx context.Context) error

Shutdown stops accepting spans and waits until the queued spans are sent, then collects the values of the Meter one last time, sends the queued metrics, and closes the destinations, or until ctx ends. If ctx ends first, it returns ctx.Err() and the sending continues in the background. Spans and metrics recorded after Shutdown started are dropped. A later Shutdown waits for the same cleanup.

func (*Telemetry) Tracer added in v0.7.0

func (t *Telemetry) Tracer() Tracer

Tracer returns the Tracer that records spans. It also implements pkg/observer OptionsTracer, which accepts a span kind and links. A span becomes a child of the span context in the context passed to StartSpan, and otherwise starts a new trace that TracesConfig.SamplingRatio decides to record or not. Without destinations, the Tracer records nothing.

type TelemetryConfig added in v0.7.0

type TelemetryConfig = pkgtelemetry.Config

TelemetryConfig configures NewTelemetry. See pkg/telemetry for its settings.

func DefaultTelemetryConfig added in v0.7.0

func DefaultTelemetryConfig() TelemetryConfig

DefaultTelemetryConfig returns settings with no destinations, which record nothing, and the host name and OS in Resource. Choose the destinations in Traces.Exporters and Metrics.Exporters, and set Resource.ServiceName.

type TelemetryMember added in v0.7.0

type TelemetryMember = pkgtelemetry.Telemetry

TelemetryMember is the interface of *Telemetry: a Tracer and a Meter whose data is delivered until Shutdown. AdminMembers.Telemetries takes it.

type TraceExporter added in v0.7.0

type TraceExporter = pkgtelemetry.TraceExporter

TraceExporter names a destination of spans in TelemetryConfig.

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/configview
Package configviewは、loggerとtelemetryを作った設定を、管理用APIが返すJSONの文書に します。
Package configviewは、loggerとtelemetryを作った設定を、管理用APIが返すJSONの文書に します。
application/loggerruntime
Package loggerruntimeは、公開APIのNew・NewAsync・NewDeliveryの処理を受け持ちます。
Package loggerruntimeは、公開APIのNew・NewAsync・NewDeliveryの処理を受け持ちます。
application/metricnames
Package metricnamesは、heterologが記録するmetricsとspan属性の名前と、属性の値です。
Package metricnamesは、heterologが記録するmetricsとspan属性の名前と、属性の値です。
application/metrics
Package metricsは、heterologのMeterを実装します。
Package metricsは、heterologのMeterを実装します。
application/outputsettings
Package outputsettingsは、稼働中のloggerの出力先ごとのlog levelとsampling設定を、 読み取り・変更する処理を提供します。
Package outputsettingsは、稼働中のloggerの出力先ごとのlog levelとsampling設定を、 読み取り・変更する処理を提供します。
application/status
Package statusは、稼働中のloggerとtelemetryの様子(processのCPUとmemory、出力先ごとの 送信の結果と所要時間、spoolとdirectoryの使用状況)を一つの報告にまとめ、注意すべき状態を 判定します。
Package statusは、稼働中のloggerとtelemetryの様子(processのCPUとmemory、出力先ごとの 送信の結果と所要時間、spoolとdirectoryの使用状況)を一つの報告にまとめ、注意すべき状態を 判定します。
application/telemetrydata
Package telemetrydataは、spanとmetricsに共通する記録の部品です。
Package telemetrydataは、spanとmetricsに共通する記録の部品です。
application/telemetryruntime
Package telemetryruntimeは、NewTelemetryが返すtelemetryの実体です。
Package telemetryruntimeは、NewTelemetryが返すtelemetryの実体です。
application/tracing
Package tracingは、heterologのTracerを実装します。
Package tracingは、heterologのTracerを実装します。
bootstrap
Package bootstrapは、application層のloggerの処理に、infrastructure層の実装を渡して loggerを組み立てます。
Package bootstrapは、application層のloggerの処理に、infrastructure層の実装を渡して loggerを組み立てます。
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名の対応を定義します。
goroutineid
Package goroutineidは、callbackが同じgoroutineから直接呼び直されたことを見分けるために、 今のgoroutineのidを読みます。
Package goroutineidは、callbackが同じgoroutineから直接呼び直されたことを見分けるために、 今のgoroutineのidを読みます。
infrastructure/delivery
Package deliveryは、NewTelemetryがspanとmetricsを送る仕組みのうち、送るものの種類に よらない部分です。
Package deliveryは、NewTelemetryがspanとmetricsを送る仕組みのうち、送るものの種類に よらない部分です。
infrastructure/delivery/failurestore
Package failurestoreは、NewTelemetryの送り先へ送れなかったもの(spanやmetric)を、 ログの出力先と同じ失敗処理(spool、failure archive、degrade、overload)へ渡し、spoolに 保存したものを送り直します。
Package failurestoreは、NewTelemetryの送り先へ送れなかったもの(spanやmetric)を、 ログの出力先と同じ失敗処理(spool、failure archive、degrade、overload)へ渡し、spoolに 保存したものを送り直します。
infrastructure/delivery/jsonlines
Package jsonlinesは、spanやmetricsのbatchをOTLP/JSONの1行にして書く送り先(fileと stdout)です。
Package jsonlinesは、spanやmetricsのbatchをOTLP/JSONの1行にして書く送り先(fileと stdout)です。
infrastructure/delivery/otlphttp
Package otlphttpは、spanやmetricsをOTLP/HTTPのprotobufで受信側(OpenTelemetry Collector、Grafana Tempoなど)へ送る送り先です。
Package otlphttpは、spanやmetricsをOTLP/HTTPのprotobufで受信側(OpenTelemetry Collector、Grafana Tempoなど)へ送る送り先です。
infrastructure/delivery/retrying
Package retryingは、spanやmetricsのbatchを送り先へ送る処理のうち、送り先によらない 部分です。
Package retryingは、spanやmetricsのbatchを送り先へ送る処理のうち、送り先によらない 部分です。
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/logrecovery
Package logrecoveryは、停止中のアプリケーションのログファイルを手動復旧します。
Package logrecoveryは、停止中のアプリケーションのログファイルを手動復旧します。
infrastructure/metrics
Package metricsは、NewTelemetryのmetricsの配送の仕組みです。
Package metricsは、NewTelemetryのmetricsの配送の仕組みです。
infrastructure/metrics/otlp
Package otlpは、metricsをOTLP(OpenTelemetry Protocol)のprotobufとJSONに変換します。
Package otlpは、metricsをOTLP(OpenTelemetry Protocol)のprotobufとJSONに変換します。
infrastructure/metrics/victoriametrics
Package victoriametricsは、metricsをPrometheusのtext形式(exposition format)で VictoriaMetricsの/api/v1/import/prometheusへ送る送り先です。
Package victoriametricsは、metricsをPrometheusのtext形式(exposition format)で VictoriaMetricsの/api/v1/import/prometheusへ送る送り先です。
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/otlpcommon
Package otlpcommonは、OTLP(OpenTelemetry Protocol)の、spanとmetricsに共通する部分の 変換です。
Package otlpcommonは、OTLP(OpenTelemetry Protocol)の、spanとmetricsに共通する部分の 変換です。
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/status
Package statusは、管理用APIのstatusの報告に使う、OSとfile systemの読み取りです。
Package statusは、管理用APIのstatusの報告に使う、OSとfile systemの読み取りです。
infrastructure/storageowner
Package storageownerは、object storageへ送れなかった圧縮ログを保存するdirectory (圧縮ログのspoolとfailure archive)を、所有者ごとに分ける名前を定義します。
Package storageownerは、object storageへ送れなかった圧縮ログを保存するdirectory (圧縮ログのspoolとfailure archive)を、所有者ごとに分ける名前を定義します。
infrastructure/telemetry
Package telemetryは、loggerが記録するmetricsとspan属性の記録の共通処理をまとめます。
Package telemetryは、loggerが記録するmetricsとspan属性の記録の共通処理をまとめます。
infrastructure/traces
Package tracesは、NewTelemetryのtraceの配送の仕組みです。
Package tracesは、NewTelemetryのtraceの配送の仕組みです。
infrastructure/traces/clickhouse
Package clickhouseは、spanをClickHouseの表へ書く送り先です。
Package clickhouseは、spanをClickHouseの表へ書く送り先です。
infrastructure/traces/opensearch
Package opensearchは、spanをOpenSearchへ文書として書く送り先です。
Package opensearchは、spanをOpenSearchへ文書として書く送り先です。
infrastructure/traces/otlp
Package otlpは、終わったspanをOTLP(OpenTelemetry Protocol)のprotobufとJSONに変換します。
Package otlpは、終わったspanをOTLP(OpenTelemetry Protocol)のprotobufとJSONに変換します。
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設定を読み取り・ 変更し、loggerとtelemetryを作った設定を返す、HTTPの管理用APIの受け口です。
Package adminは、稼働中のloggerの出力先ごとのlog levelとsampling設定を読み取り・ 変更し、loggerとtelemetryを作った設定を返す、HTTPの管理用APIの受け口です。
presentation/otelexport
Package otelexportは、OpenTelemetry SDKから届くspanとmetricsの入口です。
Package otelexportは、OpenTelemetry SDKから届くspanとmetricsの入口です。
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/observertest
Package observertestは、loggerが記録したmetricsとspanを試験で確かめるための、 記録するだけのTracerとMeterを提供します。
Package observertestは、loggerが記録したmetricsとspanを試験で確かめるための、 記録するだけのTracerとMeterを提供します。
testutil/uploadertest
Package uploadertestは試験用の送信入力をコンストラクタ経由で作成します。
Package uploadertestは試験用の送信入力をコンストラクタ経由で作成します。
Package otelexport passes spans and metrics from the OpenTelemetry SDK to a heterolog.Telemetry, which delivers them together with the spans and metrics of its own Tracer and Meter.
Package otelexport passes spans and metrics from the OpenTelemetry SDK to a heterolog.Telemetry, which delivers them together with the spans and metrics of its own Tracer and Meter.
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 and reports the configuration of loggers and telemetries.
Package admin holds the configuration types of the admin API, which reads and changes the level and sampling of the outputs of running loggers and reports the configuration of loggers and telemetries.
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.
telemetry
Package telemetry defines the configuration of heterolog.NewTelemetry, which delivers spans and metrics, from the Tracer and the Meter of heterolog and from the OpenTelemetry SDK, to OTLP/HTTP receivers, OpenSearch, ClickHouse, VictoriaMetrics, files and stdout.
Package telemetry defines the configuration of heterolog.NewTelemetry, which delivers spans and metrics, from the Tracer and the Meter of heterolog and from the OpenTelemetry SDK, to OTLP/HTTP receivers, OpenSearch, ClickHouse, VictoriaMetrics, files and stdout.
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