elastic / ecs-dotnet

https://www.elastic.co/guide/en/ecs-logging/dotnet/current/setup.html
Apache License 2.0
115 stars 58 forks source link

[FEATURE]Update ElasticApmEnricher to better support Open Telemetry #169

Closed carlosli888 closed 1 year ago

carlosli888 commented 2 years ago

ECS integration/library project(s) (e.g. Elastic.CommonSchema.Serilog):: Elastic.Apm.SerilogEnricher

Is your feature request related to a problem? Please describe. I have been exploring Open Telemetry and how the Elastic Stack and Serilog would work together. I have been able to send traces and logs to the Elastic Stack, but I was unable to link the logs to the traces with Elastic.Apm.SerilogEnricher.ElasticApmEnricher. After reviewing the code, I saw that it relies on an (elastic) agent being present. Because I am trying to stay true to the goals of Open Telemetry, I am trying to minimize the amount of code and dependencies I need to add that directly reference the Elastic Stack. Currently, I only have references to the Elastic Stack as a sink (for logs) and as an Otlp Exporter target (for traces).

Describe the solution you'd like I am not sure if I understood SpanId and TransactionId correctly, but I found the following changes would work (forgive the bad class name)...

        public class ElasticApmEnricher2 : ILogEventEnricher
    {
        public void Enrich(LogEvent logEvent, ILogEventPropertyFactory propertyFactory)
        {
            var activity = Activity.Current;
            if (null != activity)
            {
                var traceId = activity.TraceId.ToString();
                var spanId = activity.SpanId.ToString();

                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                    "ElasticApmTraceId", traceId));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                    "ElasticApmSpanId", spanId));
                logEvent.AddPropertyIfAbsent(propertyFactory.CreateProperty(
                    "ElasticApmTransactionId", spanId));
            }
        }
    }

Describe alternatives you've considered I have tried to search for newer or alternative libraries/extensions, but I could not find any.

Additional context None.

Mpdreamz commented 1 year ago

55 now ensures tracing information from Activity is available at a minimum.

Thanks for raising this @carlosli888 :+1: