open-telemetry / opentelemetry-dotnet

The OpenTelemetry .NET Client
https://opentelemetry.io
Apache License 2.0
3.23k stars 765 forks source link

Processor does not seem to add attribute when exported to Console #5732

Closed smoms closed 4 months ago

smoms commented 4 months ago

Processor does not seem to add attribute when exported to Console

Hi,

I have a simple processor which adds a new attributes currentDateTimeInUtc This attribute is not showing/being added when the exporter is to Console but it is added when it is exported to an OTLP collector. Why?

Here the code:

internal class LogAttributesProcessor : BaseProcessor<LogRecord>
{
    private readonly string _name;

    public LogAttributesProcessor(string name = "LogAttributesProcessor")
    {
        _name = name;
    }

    public override void OnEnd(LogRecord record)
    {

        var tempDic = record.Attributes.ToDictionary(x => x.Key, y => y.Value);
        IDictionary<string, object?> finalDic = new Dictionary<string, object?>();

        foreach (var attr in tempDic)
        {
            ---some logic--
        }
        //Inject UTC DateTime attribute in ISO-8601 format
        **finalDic["currentDateTimeInUtc"] = DateTime.UtcNow.ToString("o", CultureInfo.InvariantCulture);**

        record.Attributes = finalDic.ToList();
    }

}

And here how it is registered:

internal static void ConfigureLoggingOpenTelemetry(this ILoggingBuilder loggingBuilder, TelemetryOptions telemetryOptions)
{
    loggingBuilder.AddOpenTelemetry(options =>
    {
        options
            .SetResourceBuilder(
                ResourceBuilder
                    .CreateDefault()
                    .AddService(telemetryOptions.ServiceName!, telemetryOptions.ServiceNamespace!, telemetryOptions.ServiceVersion!)
                );
        if (!string.IsNullOrWhiteSpace(telemetryOptions.EndpointLog?.ToString()))
        {
            options.AddOtlpExporter(o =>
            {
                o.Protocol = OtlpExportProtocol.HttpProtobuf;
                o.Endpoint = telemetryOptions.EndpointLog;
             });
        }
        else
        {
            options.AddConsoleExporter();
        }

        options.AddProcessor(new LogAttributesProcessor());
    });
}

Additional context

image

cijothomas commented 4 months ago

Strange.. I guess the order + buffering + shared state is working against you! Could you do options.AddProcessor(new LogAttributesProcessor()) before adding the exporters?

smoms commented 4 months ago

@cijothomas you are definitely right. thanks!