Scenario: A developer wants to use OpenTelemetry .NET for monitoring and logging their application. In this example, we will walk through the process of setting up and configuring OpenTelemetry .NET for monitoring and logging in a .NET application.
- Prerequisites:
- Familiarity with the OpenTelemetry project and its components (https://opentelemetry.io/)
- A .NET application project
- Installing OpenTelemetry .NET:
- OpenTelemetry .NET is included in the .NET SDK, so no additional installation is required.
- Configuring OpenTelemetry .NET for Monitoring and Logging:
a. Add OpenTelemetry NuGet packages to your project:
- For tracing: OpenTelemetry.Exporter.Console, OpenTelemetry.Instrumentation.AspNetCore, OpenTelemetry.Api.ProviderBuilderExtensions
- For logging: OpenTelemetry.Extensions.Hosting, OpenTelemetry.Extensions.Propagators
b. Configure OpenTelemetry in your Program.cs
:
using OpenTelemetry;
using OpenTelemetry.Api;
using OpenTelemetry.Api.Tracing;
using OpenTelemetry.Extensions.Hosting;
using Microsoft.Extensions.DependencyInjection;
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices((hostContext, services) =>
{
services.AddOpenTelemetry()
.AddOpenTelemetryTracing()
.AddOpenTelemetryLogging();
})
.UseOpenTelemetry();
c. Add OpenTelemetry logging middleware to your ASP.NET Core application:
using OpenTelemetry.Api.Logging;
using Microsoft.Extensions.DependencyInjection;
public void ConfigureServices(IServiceCollection services)
{
services.AddOpenTelemetry()
.AddOpenTelemetryTracing()
.AddOpenTelemetryLogging()
.AddControllers();
services.Configure<LoggingBuilder>(loggingBuilder =>
{
loggingBuilder.AddOpenTelemetry();
});
}
public void Configure(IApplicationBuilder app, IWebJobsStartup startUp)
{
if (app.Environment.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseRouting();
app.UseEndpoints(endpoints =>
{
endpoints.MapControllers();
});
app.UseOpenTelemetry();
}
- Testing:
a. To verify that tracing is working, add a trace point to your application:
using OpenTelemetry.Api.Tracing;
using OpenTelemetry.Api.Tracing.Metrics;
using OpenTelemetry.Extensions.Http;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ITracer _tracer;
public WeatherForecastController(ITracer tracer)
{
_tracer = tracer;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
using var span = _tracer.StartSpan("GetWeatherForecast");
span.AddEvent("Started processing request");
// Your code here
span.AddEvent("Finished processing request");
span.RecordException(new Exception("An error occurred"));
span.AddMetric("ResponseSize", 123);
span.End();
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
});
}
}
b. To verify that logging is working, add a log point to your application:
using OpenTelemetry.Api.Logging;
[ApiController]
[Route("[controller]")]
public class WeatherForecastController : ControllerBase
{
private readonly ILogger<WeatherForecastController> _logger;
public WeatherForecastController(ILogger<WeatherForecastController> logger)
{
_logger = logger;
}
[HttpGet]
public IEnumerable<WeatherForecast> Get()
{
_logger.LogInformation("Started processing request");
// Your code here
_logger.LogInformation("Finished processing request");
return Enumerable.Range(1, 5).Select(index => new WeatherForecast
{
Date = DateTime.Now.AddDays(index),
TemperatureC = Random.Shared.Next(-20, 55),
Summary = Summaries[Random.Shared.Next(Summaries.Length)]
});
}
}
c. Run your application and check the logs and traces in the console or a logging/tracing backend.
- Conclusion:
In this example, we have shown how to use OpenTelemetry .NET for monitoring and logging in a .NET application. We have configured OpenTelemetry for tracing and logging, added trace and log points to our application, and tested the configuration. OpenTelemetry provides a unified approach to observability, making it an excellent choice for monitoring and logging your applications.
Tests:
- Verify that tracing is working by checking the traces in the console or a logging/tracing backend.
- Verify that logging is working by checking the logs in the console or a logging backend.
- Verify that tracing and logging are integrated by checking that trace context is propagated to logs.