Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Draft: Add ActivityEventAttachingLogProcessor to build ActivityEvents from logs in OpenTelemetry.Extensions #1907

Closed
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
7 changes: 7 additions & 0 deletions OpenTelemetry.sln
Original file line number Diff line number Diff line change
@@ -21,6 +21,7 @@ Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "Solution Items", "Solution
EndProject
Project("{2150E333-8FDC-42A3-9474-1A3956D46DE8}") = "build", "build", "{7CB2F02E-03FA-4FFF-89A5-C51F107623FD}"
ProjectSection(SolutionItems) = preProject
build\CodeAnalysis.props = build\CodeAnalysis.props
build\Common.nonprod.props = build\Common.nonprod.props
build\Common.prod.props = build\Common.prod.props
build\Common.props = build\Common.props
@@ -201,6 +202,8 @@ Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "exception-reporting", "docs
EndProject
Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "customizing-the-sdk", "docs\trace\customizing-the-sdk\customizing-the-sdk.csproj", "{64E3D8BB-93AB-4571-93F7-ED8D64DFFD06}"
EndProject
Project("{9A19103F-16F7-4668-BE54-9A1E7A4F7556}") = "OpenTelemetry.Extensions", "src\OpenTelemetry.Extensions\OpenTelemetry.Extensions.csproj", "{7BD1BED9-4CC1-46BE-9152-FF58CD70E08B}"
EndProject
Global
GlobalSection(SolutionConfigurationPlatforms) = preSolution
Debug|Any CPU = Debug|Any CPU
@@ -399,6 +402,10 @@ Global
{64E3D8BB-93AB-4571-93F7-ED8D64DFFD06}.Debug|Any CPU.Build.0 = Debug|Any CPU
{64E3D8BB-93AB-4571-93F7-ED8D64DFFD06}.Release|Any CPU.ActiveCfg = Release|Any CPU
{64E3D8BB-93AB-4571-93F7-ED8D64DFFD06}.Release|Any CPU.Build.0 = Release|Any CPU
{7BD1BED9-4CC1-46BE-9152-FF58CD70E08B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU
{7BD1BED9-4CC1-46BE-9152-FF58CD70E08B}.Debug|Any CPU.Build.0 = Debug|Any CPU
{7BD1BED9-4CC1-46BE-9152-FF58CD70E08B}.Release|Any CPU.ActiveCfg = Release|Any CPU
{7BD1BED9-4CC1-46BE-9152-FF58CD70E08B}.Release|Any CPU.Build.0 = Release|Any CPU
EndGlobalSection
GlobalSection(SolutionProperties) = preSolution
HideSolutionNode = FALSE
21 changes: 21 additions & 0 deletions build/CodeAnalysis.props
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
<Project>
<PropertyGroup>
<Nullable>enable</Nullable>
</PropertyGroup>

<PropertyGroup Condition="'$(SkipAnalysis)'!='true'">
<AnalysisMode>AllEnabledByDefault</AnalysisMode>
<AnalysisLevel>latest</AnalysisLevel>
</PropertyGroup>

<PropertyGroup Condition="'$(TargetFramework)' != 'net5.0' and '$(TargetFramework)' != 'netstandard2.1'">
<!-- Nullable analysis really only works on .net standard 2.1 and newer. -->
<NoWarn>$(NoWarn);nullable</NoWarn>
</PropertyGroup>

<ItemGroup>
<PackageReference Include="Microsoft.CodeAnalysis.NetAnalyzers" Version="$(MicrosoftNetAnalyzersPkgVer)" Condition="'$(SkipAnalysis)'!='true'">
<PrivateAssets>all</PrivateAssets>
</PackageReference>
</ItemGroup>
</Project>
2 changes: 1 addition & 1 deletion build/Common.prod.props
Original file line number Diff line number Diff line change
@@ -6,7 +6,7 @@
<IncludeAssets>runtime; build; native; contentfiles; analyzers; buildtransitive</IncludeAssets>
<PrivateAssets>all</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="$(MicrosoftCodeAnalysisAnalyzersPkgVer)" Condition=" $(OS) == 'Windows_NT'">
<PackageReference Include="Microsoft.CodeAnalysis.PublicApiAnalyzers" Version="$(MicrosoftPublicApiAnalyzersPkgVer)" Condition=" $(OS) == 'Windows_NT'">
<PrivateAssets>All</PrivateAssets>
</PackageReference>
</ItemGroup>
8 changes: 3 additions & 5 deletions build/Common.props
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
<Project>
<PropertyGroup>
<LangVersion>8.0</LangVersion>
<LangVersion>9.0</LangVersion>
<SignAssembly>true</SignAssembly>
<RepoRoot>$([System.IO.Directory]::GetParent($(MSBuildThisFileDirectory)).Parent.FullName)</RepoRoot>
<AssemblyOriginatorKeyFile>$(MSBuildThisFileDirectory)debug.snk</AssemblyOriginatorKeyFile>
@@ -29,7 +29,8 @@
<MicrosoftAspNetCoreHttpAbstractionsPkgVer>[2.1.1,6.0)</MicrosoftAspNetCoreHttpAbstractionsPkgVer>
<MicrosoftAspNetCoreHttpFeaturesPkgVer>[2.1.1,6.0)</MicrosoftAspNetCoreHttpFeaturesPkgVer>
<MicrosoftAspNetTelemetryCorrelationPkgVer>[1.0.7,2.0)</MicrosoftAspNetTelemetryCorrelationPkgVer>
<MicrosoftCodeAnalysisAnalyzersPkgVer>[3.3.1]</MicrosoftCodeAnalysisAnalyzersPkgVer>
<MicrosoftPublicApiAnalyzersPkgVer>[3.3.2]</MicrosoftPublicApiAnalyzersPkgVer>
<MicrosoftNetAnalyzersPkgVer>[5.0.3]</MicrosoftNetAnalyzersPkgVer>
<MicrosoftCodeCoveragePkgVer>[16.9.1]</MicrosoftCodeCoveragePkgVer>
<MicrosoftExtensionsHostingAbstractionsPkgVer>[2.1.0,6.0)</MicrosoftExtensionsHostingAbstractionsPkgVer>
<MicrosoftExtensionsLoggingPkgVer>[2.1.0,6.0)</MicrosoftExtensionsLoggingPkgVer>
@@ -57,9 +58,6 @@
<PrivateAssets>All</PrivateAssets>
</PackageReference>
<PackageReference Include="Microsoft.CodeCoverage" Version="$(MicrosoftCodeCoveragePkgVer)" Condition="'$(Configuration)'=='Release'"/>
<!--<PackageReference Include="Microsoft.CodeAnalysis.FxCopAnalyzers" Version="$(MicrosoftCodeAnalysisAnalyzersPkgVer)" Condition="'$(SkipAnalysis)'!='true'">
<PrivateAssets>all</PrivateAssets>
</PackageReference>-->
</ItemGroup>

<ItemGroup Condition="'$(IncludeDiagnosticSourceInstrumentationHelpers)'=='true'">
1 change: 1 addition & 0 deletions examples/AspNetCore/Examples.AspNetCore.csproj
Original file line number Diff line number Diff line change
@@ -19,6 +19,7 @@
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Extensions.Hosting\OpenTelemetry.Extensions.Hosting.csproj" />
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Instrumentation.Http\OpenTelemetry.Instrumentation.Http.csproj" />
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Exporter.OpenTelemetryProtocol\OpenTelemetry.Exporter.OpenTelemetryProtocol.csproj" />
<ProjectReference Include="$(RepoRoot)\src\OpenTelemetry.Extensions\OpenTelemetry.Extensions.csproj" />
</ItemGroup>


2 changes: 1 addition & 1 deletion examples/AspNetCore/Models/WeatherForecast.cs
Original file line number Diff line number Diff line change
@@ -18,7 +18,7 @@

namespace Examples.AspNetCore.Models
{
public class WeatherForecast
public record WeatherForecast
{
public DateTime Date { get; set; }

14 changes: 10 additions & 4 deletions examples/AspNetCore/Program.cs
Original file line number Diff line number Diff line change
@@ -40,15 +40,21 @@ public static IHostBuilder CreateHostBuilder(string[] args) =>
builder.ClearProviders();
builder.AddConsole();

var useLogging = context.Configuration.GetValue<bool>("UseLogging");
var loggingConfiguration = context.Configuration.GetSection("Logs");

var useLogging = loggingConfiguration.GetValue<bool>("Enabled");
if (useLogging)
{
builder.AddOpenTelemetry(options =>
{
options.IncludeScopes = true;
options.ParseStateValues = true;
options.IncludeFormattedMessage = true;
options.IncludeScopes = loggingConfiguration.GetValue<bool>("IncludeScopes");
options.ParseStateValues = loggingConfiguration.GetValue<bool>("ParseStateValues");
options.IncludeFormattedMessage = loggingConfiguration.GetValue<bool>("IncludeFormattedMessage");
options.AddConsoleExporter();
if (loggingConfiguration.GetValue<bool>("AttachLogsToActivity"))
{
options.AddActivityEventAttachingLogProcessor();
}
});
}
});
8 changes: 7 additions & 1 deletion examples/AspNetCore/appsettings.json
Original file line number Diff line number Diff line change
@@ -8,7 +8,13 @@
},
"AllowedHosts": "*",
"UseExporter": "console",
"UseLogging": true,
"Logs": {
"Enabled": true,
"IncludeScopes": true,
"ParseStateValues": true,
"IncludeFormattedMessage": true,
"AttachLogsToActivity": true
},
"Jaeger": {
"ServiceName": "jaeger-test",
"AgentHost": "localhost",
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#nullable enable
Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ActivityEventAttachingLogProcessorOptions() -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, int, OpenTelemetry.Logs.LogRecordScope>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.set -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string!, object!>>!>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.set -> void
static Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions.AddActivityEventAttachingLogProcessor(this OpenTelemetry.Logs.OpenTelemetryLoggerOptions! loggerOptions, System.Action<OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions!>? configure = null) -> OpenTelemetry.Logs.OpenTelemetryLoggerOptions!
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#nullable enable
Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ActivityEventAttachingLogProcessorOptions() -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, int, object!>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.set -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string!, object!>>!>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.set -> void
static Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions.AddActivityEventAttachingLogProcessor(this OpenTelemetry.Logs.OpenTelemetryLoggerOptions! loggerOptions, System.Action<OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions!>? configure = null) -> OpenTelemetry.Logs.OpenTelemetryLoggerOptions!
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
#nullable enable
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
#nullable enable
Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ActivityEventAttachingLogProcessorOptions() -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, int, OpenTelemetry.Logs.LogRecordScope>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.ScopeConverter.set -> void
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.get -> System.Action<System.Diagnostics.ActivityTagsCollection!, System.Collections.Generic.IReadOnlyList<System.Collections.Generic.KeyValuePair<string!, object!>>!>!
OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions.StateConverter.set -> void
static Microsoft.Extensions.Logging.OpenTelemetryLoggingExtensions.AddActivityEventAttachingLogProcessor(this OpenTelemetry.Logs.OpenTelemetryLoggerOptions! loggerOptions, System.Action<OpenTelemetry.Logs.ActivityEventAttachingLogProcessorOptions!>? configure = null) -> OpenTelemetry.Logs.OpenTelemetryLoggerOptions!
19 changes: 19 additions & 0 deletions src/OpenTelemetry.Extensions/AssemblyInfo.cs
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
// <copyright file="AssemblyInfo.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;

[assembly: CLSCompliant(false)]
3 changes: 3 additions & 0 deletions src/OpenTelemetry.Extensions/CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
# Changelog

## Unreleased
Original file line number Diff line number Diff line change
@@ -0,0 +1,45 @@
// <copyright file="OpenTelemetryExtensionsEventSource.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

using System;
using System.Diagnostics.Tracing;

namespace OpenTelemetry.Internal
{
/// <summary>
/// EventSource implementation for OpenTelemetry SDK extensions implementation.
/// </summary>
[EventSource(Name = "OpenTelemetry-Extensions")]
internal class OpenTelemetryExtensionsEventSource : EventSource
{
public static OpenTelemetryExtensionsEventSource Log = new OpenTelemetryExtensionsEventSource();

[NonEvent]
public void LogProcessorException(string @event, Exception ex)
{
if (this.IsEnabled(EventLevel.Error, (EventKeywords)(-1)))
{
this.LogProcessorException(@event, ex.ToInvariantString());
}
}

[Event(1, Message = "Unknown error in LogProcessor event '{0}': '{1}'.", Level = EventLevel.Error)]
public void LogProcessorException(string @event, string exception)
{
this.WriteEvent(1, @event, exception);
}
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,111 @@
// <copyright file="ActivityEventAttachingLogProcessor.cs" company="OpenTelemetry Authors">
// Copyright The OpenTelemetry Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// </copyright>

#if NET461_OR_GREATER || NETSTANDARD2_0 || NET5_0_OR_GREATER
using System;
using System.Diagnostics;
using OpenTelemetry.Internal;
using OpenTelemetry.Trace;

namespace OpenTelemetry.Logs
{
internal class ActivityEventAttachingLogProcessor : BaseProcessor<LogRecord>
{
private static readonly Action<LogRecordScope, State> ProcessScopeRef = ProcessScope;

private readonly ActivityEventAttachingLogProcessorOptions options;

public ActivityEventAttachingLogProcessor(ActivityEventAttachingLogProcessorOptions options)
{
this.options = options ?? throw new ArgumentNullException(nameof(options));
}

public override void OnEnd(LogRecord data)
{
Activity? activity = Activity.Current;

if (activity?.IsAllDataRequested == true)
{
var tags = new ActivityTagsCollection
{
{ nameof(data.CategoryName), data.CategoryName },
{ nameof(data.LogLevel), data.LogLevel },
};

if (data.EventId != 0)
{
tags[nameof(data.EventId)] = data.EventId;
}

var activityEvent = new ActivityEvent("log", data.Timestamp, tags);

data.ForEachScope(ProcessScopeRef, new State(tags, this));

if (data.StateValues != null)
{
try
{
this.options.StateConverter?.Invoke(tags, data.StateValues);
}
catch (Exception ex)
{
OpenTelemetryExtensionsEventSource.Log.LogProcessorException($"Processing state of type [{data.State.GetType().FullName}]", ex);
}
}

if (!string.IsNullOrEmpty(data.FormattedMessage))
{
tags["FormattedMessage"] = data.FormattedMessage;
}

activity.AddEvent(activityEvent);

if (data.Exception != null)
{
activity.RecordException(data.Exception);
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Should we use data.Timestamp even for the exception event?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

You don't think so? It's a log event with an exception added. The timestamp of the log still feels valid to me, but I don't feel strongly about it.

}
}
}

private static void ProcessScope(LogRecordScope scope, State state)
{
try
{
state.Processor.options.ScopeConverter?.Invoke(state.Tags, state.Index++, scope);
}
catch (Exception ex)
{
OpenTelemetryExtensionsEventSource.Log.LogProcessorException($"Processing scope of type [{scope.GetType().FullName}]", ex);
}
}

private class State
{
public State(ActivityTagsCollection tags, ActivityEventAttachingLogProcessor processor)
{
this.Tags = tags;
this.Processor = processor;
}

public ActivityTagsCollection Tags { get; }

public ActivityEventAttachingLogProcessor Processor { get; }

public int Index { get; set; }
}
}
}
#endif
Loading