- Notifications
You must be signed in to change notification settings - Fork24
A Serilog OpenTelemetry Protocol (OTLP) sink
License
serilog/serilog-sinks-opentelemetry
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
This Serilog sink transforms Serilog events into OpenTelemetryLogRecords and sends them to an OTLP (gRPC or HTTP) endpoint.
The sink aims for full compliance with the OpenTelemetry Logs protocol. Itdoes not depend on the OpenTelemetry SDK or .NET API.
OpenTelemetry supports attributes with scalar values, arrays, and maps.Serilog does as well. Consequently, the sink does a one-to-onemapping between Serilog properties and OpenTelemetry attributes.There is no flattening, renaming, or other modifications done to theproperties by default.
To use the OpenTelemetry sink, first install theNuGet package:
dotnet add package Serilog.Sinks.OpenTelemetry
Then enable the sink usingWriteTo.OpenTelemetry():
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry().CreateLogger();
Generate logs using theLog.Information(...) and similar methods tosend transformed logs to a local OpenTelemetry OTLP endpoint.
A more complete configuration would specifyEndpoint,Protocol,and other parameters, such asResourceAttributes, as shown in theexamples below.
This sink supports two configuration styles: inline and options.Inline configuration is appropriate for simple, local loggingsetups, and looks like:
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry(endpoint:"http://127.0.0.1:4318",protocol:OtlpProtocol.HttpProtobuf).CreateLogger();
More complicated use cases need to use options-styleconfiguration, which looks like:
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry(options=>{options.Endpoint="http://127.0.0.1:4318";options.Protocol=OtlpProtocol.HttpProtobuf;}).CreateLogger();
This supports the sink's full set of configuration options. See theOpenTelemetrySinkOptions.cs file for the full set of options.Some of the more important parameters are discussed in the followingsections.
The default endpoint and protocol arehttp://localhost:4317 andOtlpProtocol.Grpc.
In most production scenarios, you'll need to set an endpoint and protocol to suit yourdeployment environment. To do so, add theendpoint argument to theWriteTo.OpenTelemetry() call.
You may also want to set the protocol. The supported valuesare:
OtlpProtocol.Grpc: Sends a protobuf representation of theOpenTelemetry Logs over a gRPC connection (the default).OtlpProtocol.HttpProtobuf: Sends a protobuf representation of theOpenTelemetry Logs over an HTTP connection.
OpenTelemetry logs may contain a "resource" that provides metadata concerningthe entity associated with the logs, typically a service or library. Thesemay contain "resource attributes" and are emitted for all logs flowing throughthe configured logger.
These resource attributes may be provided as aDictionary<string, Object>when configuring a logger. OpenTelemetry allows resource attributeswith rich values; however, this implementationonly supports resourceattributes with primitive values.
⚠️ Resource attributes with non-primitive values will besilently ignored.
This example shows how the resource attributes can be specified whenthe logger is configured.
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry(options=>{options.Endpoint="http://127.0.0.1:4317";options.ResourceAttributes=newDictionary<string,object>{["service.name"]="test-logging-service",["index"]=10,["flag"]=true,["value"]=3.14};}).CreateLogger();
The sink also recognizes a selection of theOTEL_OTLP_EXPORTER_* environment variables described intheOpenTelemetry documentation, and willoverride programmatic configuration with any environment variable values present at runtime.
To switch off this behavior, passignoreEnvironment: true to theWriteTo.OpenTelemetry() configurationmethods.
The following table provides the mapping between the Serilog logevents and the OpenTelemetry log records.
SerilogLogEvent | OpenTelemetryLogRecord | Comments |
|---|---|---|
Exception.GetType().ToString() | Attributes["exception.type"] | |
Exception.Message | Attributes["exception.message"] | Ignored if empty |
Exception.StackTrace | Attributes["exception.stacktrace"] | Value ofex.ToString() |
Level | SeverityNumber | Serilog levels are mapped to corresponding OpenTelemetry severities |
Level.ToString() | SeverityText | |
Message | Body | Culture-specific formatting can be provided via sink configuration |
MessageTemplate | Attributes["message_template.text"] | RequiresIncludedData. MessageTemplateText (enabled by default) |
MessageTemplate (MD5) | Attributes["message_template.hash.md5"] | RequiresIncludedData. MessageTemplateMD5 HashAttribute |
Properties | Attributes | Each property is mapped to an attribute keeping the name; the value's structure is maintained |
SpanId (Activity.Current) | SpanId | RequiresIncludedData.SpanIdField (enabled by default) |
Timestamp | TimeUnixNano | .NET provides 100-nanosecond precision |
TraceId (Activity.Current) | TraceId | RequiresIncludedData.TraceIdField (enabled by default) |
This sink supports configuration of how common OpenTelemetry fields are populated fromthe SerilogLogEvent and .NETActivity context via theIncludedData flags enum:
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry(options=>{options.Endpoint="http://127.0.0.1:4317";options.IncludedData=IncludedData.MessageTemplateTextAttribute|IncludedData.SpecRequiredResourceAttributes;}).CreateLogger();
The example shows the default value;IncludedData.MessageTemplateMD5HashAttribute canalso be used to add the MD5 hash of the message template.
SerilogLogEvents that carry aSpanStartTimestamp property of typeDateTime will berecognized as spans by this sink, and sent using the appropriate OpenTelemetry endpointand schema. The properties recognized by the sink match the ones emitted bySerilogTracing.
In addition to the field mapping performed for log records, events that represent tracespans can carry the special properties listed below.
SerilogLogEvent | OpenTelemetrySpan | Comments |
|---|---|---|
MessageTemplate | Name | |
Properties["ParentSpanId"] | ParentSpanId | Value must be of typeActivitySpanId |
Properties["SpanKind"] | Kind | Value must be of typeActivityKind |
Properties["SpanStartTimestamp"] | StartTimeUnixNano | Value must be of typeDateTime; .NET provides 100-nanosecond precision |
Timestamp | EndTimeUnixNano | .NET provides 100-nanosecond precision |
If the sink is used in an application that also instruments HTTP or gRPC requests using the OpenTelemetry libraries,this can be suppressed for outbound requests made by the sink usingOnBeginSuppressInstrumentation:
Log.Logger=newLoggerConfiguration().WriteTo.OpenTelemetry(options=>{options.OnBeginSuppressInstrumentation=OpenTelemetry.SuppressInstrumentationScope.Begin;// ...
Theexample/Example subdirectory contains an example application that logsto a localOpenTelemetry collector.See the README in that directory for instructions on how to run the example.
In .NET 5 and later versions, theActivity.DefaultIdFormat isActivityIdFormat.W3C. In previous versions, the default format isActivityIdFormat.Hierarchical.To make use of theActivity's traces and spans, you should set the globalActivity.DefaultIdFormat toActivityIdFormat.W3C in .NET Framework environments.Read more:Default ActivityIdFormat is W3C
Copyright © Serilog Contributors - Provided under theApache License, Version 2.0.
About
A Serilog OpenTelemetry Protocol (OTLP) sink
Topics
Resources
License
Uh oh!
There was an error while loading.Please reload this page.