#json-log #tracing #log-line #logging #json-format #log-format #elastic

tracing-ecs

Tracing subscriber that output ECS (Elastic Common Schema) JSON log lines

6 releases

0.4.0 Feb 27, 2024
0.3.1 Oct 3, 2023
0.2.3 Sep 29, 2023
0.1.0 Sep 28, 2023

#530 in Database interfaces

44 downloads per month

MIT/Apache

41KB
840 lines

tracing-ecs crates.io docs.rs

Tracing subscriber that outputs json log lines in the ECS (Elastic Common Schema) log format.

Usage

use tracing_ecs::ECSLayerBuilder;
ECSLayerBuilder::default()
    .stdout()
    .install()
    .unwrap()

License

Contribution

Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in the work by you, as defined in the Apache-2.0 license, shall be dual licensed as above, without any additional terms or conditions.


lib.rs:

Tracing subscriber that outputs json log lines compatible with ECS (Elastic Common Schema).

More specifically, this crate provides a Layer implementation that can be composed with an existing Subscriber from the tracing-subscribers crate.

See how is implemented the install method to understand what's done under the hood.

How spans are handled

All spans attributes are directly appended to the final json object.

As a result, there might be duplicate keys in the resulting json if static extra fields have the same keys as some span attributes, or if an attribute is named message (which shall be reserved to the logged event).

This behavior can be customized by implementing the AttributeMapper trait.

JSON Normalization

Output is normalized by default so there is no dot anymore in the resulting json keys. See https://www.elastic.co/guide/en/ecs/current/ecs-guidelines.html

See ECSLayerBuilder.normalize_json

Examples

Install a default subscriber that outputs json to stdout:

use tracing_ecs::ECSLayerBuilder;

ECSLayerBuilder::default()
    .stdout()
    .install()
    .unwrap()

Install a subscriber with custom extra fields that outputs json to stdout (here we use the json! macro but it accepts anything that serializes to a json map):

use serde_json::json;
use tracing_ecs::ECSLayerBuilder;

ECSLayerBuilder::default()
    .with_extra_fields(json!({
        "labels": {
            "env": "prod",
        },
        "tags": ["service", "foobar"]
    }))
    .unwrap()
    .stdout()
    .install()
    .unwrap();

With attributes name mapping:

use tracing_ecs::ECSLayerBuilder;
use std::borrow::Cow;
use std::ops::Deref;

ECSLayerBuilder::default()
 .with_attribute_mapper(
    |_span_name: &str, name: Cow<'static, str>| match name.deref() {
        "txid" => "transaction.id".into(),
        _ => name,
    },
 ).stdout().install().unwrap()

Dependencies

~9MB
~150K SLoC