Hello I need to have OpenTelemetry logs/metrics/traces sent to console of my application, but in JSON fromat. It's a .NET 8 ASP.NET application set up loosely following: https://learn.microsoft.com/en-us/dotnet/core/diagnostics/observability-with-otel, the application already Microsoft logger with JSON log formatter (see below, uses a custom JsonLogFormatter
class). The problem is that all logs are actually formatted as JSON, but the OpenTelemetry is not.
var builder = WebApplication.CreateBuilder(args);
var services = builder.Services;
// OpenTelemetry stuff...
var otel = services.AddOpenTelemetry();
otel.WithMetrics(metrics => metrics
.AddAspNetCoreInstrumentation()
.AddMeter("Microsoft.AspNetCore.Hosting")
.AddMeter("Microsoft.AspNetCore.Server.Kestrel")
);
otel.WithTracing(tracing =>
{
tracing.AddAspNetCoreInstrumentation();
tracing.AddHttpClientInstrumentation();
tracing.AddConsoleExporter();
});
[...]
// JSON Microsoft logger added like so...
var loggerFactory = LoggerFactory.Create(builder =>
{
builder.ClearProviders();
builder.AddConfiguration(configuration.GetSection("Logging"))
.AddConsole();
builder.AddConsoleFormatter<JsonLogFormatter, JsonLogOptions>();
});
services.AddSingleton(loggerFactory);
services.AddLogging();
Console output:
{"message":"Hosting starting","machineName":"XXX","source":"Microsoft.Extensions.Hosting.Internal.Host","level":"Debug","timestamp":"2024-03-14T19:38:23.2569003+01:00"}
Activity.TraceId: 8794488a000a8aa943fb4bd76b8becbe
Activity.SpanId: bae785686698f263
Activity.TraceFlags: Recorded
Activity.ActivitySourceName: System.Net.Http
Activity.DisplayName: GET
Activity.Kind: Client
[..]
{"message":"Now listening on: https://localhost:6001","...}
I would truly like to have OpenTelemetry as JSON in this log example. :)
Currently, this is not supported by OpenTelemetry .NET. You will either need to create a new exporter or customize the existing ConsoleExporter.
Here is the code to look at: https://github.com/open-telemetry/opentelemetry-dotnet/tree/main/src/OpenTelemetry.Exporter.Console
Also, be sure to leave a comment that this is something you'd like to see included in the library. There is already an open issue: https://github.com/open-telemetry/opentelemetry-dotnet/issues/5036