Logging to elmah.io from OpenTelemetry
elmah.io provides an exporter for OpenTelemetry that will store log entries sent through OpenTelemetry in elmah.io.
Start by installing the Elmah.Io.OpenTelemetry package:
Install-Package Elmah.Io.OpenTelemetry -IncludePrerelease
dotnet add package Elmah.Io.OpenTelemetry --prerelease
<PackageReference Include="Elmah.Io.OpenTelemetry" Version="5.*" />
paket add Elmah.Io.OpenTelemetry
In the Program.cs
file, configure the elmah.io exporter:
builder.Logging.AddOpenTelemetry(options =>
{
options.AddElmahIoExporter(options =>
{
options.ApiKey = "API_KEY";
options.LogId = new Guid("LOG_ID");
});
});
Replace API_KEY
with your API key (Where is my API key?) and LOG_ID
(Where is my log ID?) with the log ID of the log you want to log to.
This will store log messages sent through OpenTelemetry in elmah.io. It is recommended only to send warnings and up to avoid spending your message quota with debug and information messages:
builder.Logging.AddFilter<OpenTelemetryLoggerProvider>("*", LogLevel.Warning);
Enriching log messages
The elmah.io exporter pulls as much information as possible, but you might want to enrich log messages with even more data. This can be done in numerous ways.
The export options provide an OnMessage
action that you may already know from other client integrations:
options.AddElmahIoExporter(options =>
{
// ...
options.OnMessage = msg => msg.Version = "42";
});
You can include a service name on log messages using the ResourceBuilder
part of OpenTelemetry:
builder.Logging.AddOpenTelemetry(options =>
{
// ...
options.SetResourceBuilder(ResourceBuilder
.CreateEmpty()
.AddService("Elmah.Io.OpenTelemetry.AspNetCore80"));
});
OpenTelemetry supports custom properties as Attributes. Global attributes can be added using the ResourceBuilder
too:
options.SetResourceBuilder(ResourceBuilder
.CreateEmpty()
// ...
.AddAttributes(new Dictionary<string, object>
{
{ "deployment.environment", builder.Environment.EnvironmentName }
}));
When logging messages through the ILogger
interface, logging scopes can be configured by setting the IncludeScopes
property:
builder.Logging.AddOpenTelemetry(options =>
{
// ...
options.IncludeScopes = true;
});
When enabling scopes, log messages can be enriched by wrapping the log message in a new scope:
using (logger.BeginScope(new { CorrelationId = "42" }))
{
logger.LogInformation("A log message");
}
This article was brought to you by the elmah.io team. elmah.io is the best error management system for .NET web applications. We monitor your website, alert you when errors start happening, and help you fix errors fast.
See how we can help you monitor your website for crashes Monitor your website