Search code examples
c#.netopen-telemetryobservability

How to capture logs using OpenTelemetry collector and .NET SDK


I'm trying to setup logs with .NET and OpenTelemetry using a simple example.

using Microsoft.Extensions.Logging;
using OpenTelemetry.Exporter;
using OpenTelemetry.Logs;
using OpenTelemetry.Resources;

using var loggerFactory = LoggerFactory.Create(builder =>
{
    builder.ClearProviders();
    builder.AddOpenTelemetry(options =>
    {
        options
            .ConfigureResource(c => c.AddService("GettingStarted"))
            .AddConsoleExporter()
            .AddOtlpExporter(config =>
            {
                config.Endpoint = new Uri("http://localhost:4318");
                config.Protocol = OtlpExportProtocol.HttpProtobuf;
            });
    });
});

var logger = loggerFactory.CreateLogger<Program>();

for (var i = 0; i < 100; i++)
{
    logger.LogError("{count}: Hello World!", i);
    await Task.Delay(1000);
}

Collector config (otel-collector-config.yaml):

receivers:
  otlp:
    protocols:
      http:
exporters:
  logging:
    loglevel: debug
service:
  telemetry:
    logs:
      level: debug
  pipelines:
    logs:
      receivers: [otlp]
      exporters: [logging]

OpenTelemetry Collector (docker-compose.yml):

services:
  opentelemetry-collector:
    image: otel/opentelemetry-collector:0.67.0
    ports:
      - 4318:4318
    volumes:
      - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml

The logs makes their way to the console (ConsoleExporter), but I don’t see it in the logs (stdout) of the collector.

What am I doing wrong?


Solution

  • My best hunch is that your collector entry in the compose file is missing the command property:

    services:
      opentelemetry-collector:
        image: otel/opentelemetry-collector:0.67.0
        ports:
          - 4318:4318
        # Add this line here
        command: ["--config=/etc/otel-collector-config.yaml"]
        volumes:
          - ./otel-collector-config.yaml:/etc/otel-collector-config.yaml
    

    So your config is actually not being applied in the collector.