Skip to content

Commit bb8f4ec

Browse files
authored
Add additional TFM's to package (#48)
* Move our AgentBuilder to IOpenTelemetryBuilder This is not yet released see open-telemetry/opentelemetry-dotnet#5265 for more background. For now we include a temporary copy with hacks to call internal bits. This allows AgentBuilder to be a native opentelemetry builder and we'd inherit all extension methods from the OpenTelemetry community * clean up AddElasticOpenTelemetry() * stage * add netstandard2.0 and 2.1 * add net462 * add net6.0 * update release folder name now that we have multiple TFMs * rename TraceParentRe
1 parent f2f6f6c commit bb8f4ec

File tree

9 files changed

+52
-31
lines changed

9 files changed

+52
-31
lines changed

build/scripts/Targets.fs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -119,7 +119,7 @@ let private generateApiChanges _ =
119119
"assembly-differ"
120120
$"previous-nuget|%s{p}|%s{currentVersion}|%s{tfm}";
121121
//$"directory|.artifacts/bin/%s{p}/release/%s{tfm}";
122-
$"directory|.artifacts/bin/%s{p}/release";
122+
$"directory|.artifacts/bin/%s{p}/release_net8.0";
123123
"-a"; "true"; "--target"; p; "-f"; "github-comment"; "--output"; outputFile
124124
]
125125
exec { run "dotnet" args }

src/Elastic.OpenTelemetry/AgentBuilder.Build.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -67,7 +67,7 @@ internal class EmptyAgent : IAgent
6767
{
6868
public void Dispose() { }
6969

70-
public ValueTask DisposeAsync() => ValueTask.CompletedTask;
70+
public ValueTask DisposeAsync() => default;
7171
}
7272

7373
internal class ElasticAgent(

src/Elastic.OpenTelemetry/AgentBuilder.cs

Lines changed: 1 addition & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -99,8 +99,7 @@ public AgentBuilder SkipOtlpExporter()
9999
/// </summary>
100100
public void ConfigureOtlpExporter(Action<OtlpExporterOptions> configure, string? name = null)
101101
{
102-
ArgumentNullException.ThrowIfNull(configure);
103-
OtlpExporterConfiguration = configure;
102+
OtlpExporterConfiguration = configure ?? throw new ArgumentNullException(nameof(configure));
104103
OtlpExporterName = name;
105104
}
106105
}

src/Elastic.OpenTelemetry/Diagnostics/LoggerMessages.cs

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,11 @@ public static void LogAgentPreamble(this ILogger logger)
3737

3838
logger.LogInformation("Process ID: {ProcessId}", process.Id);
3939
logger.LogInformation("Process name: {ProcessName}", process.ProcessName);
40+
#if NET6_0_OR_GREATER
4041
logger.LogInformation("Process path: {ProcessPath}", Environment.ProcessPath);
42+
#else
43+
logger.LogInformation("Process path: {ProcessPath}", "<Unknown>");
44+
#endif
4145

4246
logger.LogInformation("Process started: {ProcessStartTime:yyyy-MM-dd HH:mm:ss.fff}", process.StartTime.ToUniversalTime());
4347
logger.LogInformation("Machine name: {MachineName}", Environment.MachineName);

src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -49,11 +49,9 @@ public FileLogger()
4949
if (!Directory.Exists(path))
5050
Directory.CreateDirectory(path);
5151

52-
_streamWriter = new StreamWriter(LogFilePath, Encoding.UTF8, new FileStreamOptions
53-
{
54-
Access = FileAccess.Write,
55-
Mode = FileMode.OpenOrCreate,
56-
});
52+
//StreamWriter.Dispose disposes underlying stream too
53+
var stream = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
54+
_streamWriter = new StreamWriter(stream, Encoding.UTF8);
5755

5856
WritingTask = Task.Run(async () =>
5957
{
@@ -117,7 +115,13 @@ public async ValueTask DisposeAsync()
117115
await WritingTask.ConfigureAwait(false);
118116

119117
if (_streamWriter != null)
118+
{
119+
#if NETSTANDARD2_0 || NETFRAMEWORK
120+
_streamWriter.Dispose();
121+
#else
120122
await _streamWriter.DisposeAsync().ConfigureAwait(false);
123+
#endif
124+
}
121125
}
122126

123127
}

src/Elastic.OpenTelemetry/Diagnostics/Logging/ScopedCompositeLogger.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -20,7 +20,7 @@ public void Dispose()
2020
}
2121

2222
/// <summary> TODO </summary>
23-
public ValueTask DisposeAsync() => additionalLogger is IAsyncDisposable d ? d.DisposeAsync() : ValueTask.CompletedTask;
23+
public ValueTask DisposeAsync() => additionalLogger is IAsyncDisposable d ? d.DisposeAsync() : default;
2424

2525
/// <summary> TODO </summary>
2626
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)

src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs

Lines changed: 24 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -16,8 +16,15 @@ internal sealed partial class LoggingEventListener : EventListener, IAsyncDispos
1616
private readonly ILogger _logger;
1717
private readonly EventLevel _eventLevel = EventLevel.Informational;
1818

19-
[GeneratedRegex("^\\d{2}-[a-f0-9]{32}-[a-f0-9]{16}-\\d{2}$")]
19+
private const string TraceParentRegularExpressionString = "^\\d{2}-[a-f0-9]{32}-[a-f0-9]{16}-\\d{2}$";
20+
#if NET8_0_OR_GREATER
21+
[GeneratedRegex(TraceParentRegularExpressionString)]
2022
private static partial Regex TraceParentRegex();
23+
#else
24+
25+
private static Regex _traceParentRegex = new Regex(TraceParentRegularExpressionString);
26+
private static Regex TraceParentRegex() => _traceParentRegex;
27+
#endif
2128

2229
public LoggingEventListener(ILogger logger)
2330
{
@@ -44,7 +51,7 @@ public override void Dispose()
4451
}
4552

4653
public ValueTask DisposeAsync() =>
47-
_logger is IAsyncDisposable d ? d.DisposeAsync() : ValueTask.CompletedTask;
54+
_logger is IAsyncDisposable d ? d.DisposeAsync() : default;
4855

4956

5057
protected override void OnEventSourceCreated(EventSource eventSource)
@@ -69,20 +76,20 @@ protected override void OnEventWritten(EventWrittenEventArgs eventData)
6976
// to a rented array and Span<char> if required.
7077
var builder = StringBuilderCache.Acquire();
7178

72-
var spanId = CreateLogMessage(eventData, builder);
79+
#if NETSTANDARD2_0 || NETFRAMEWORK
80+
var timestamp = DateTime.UtcNow; //best effort in absense of real event timestamp
81+
var osThreadId = 0L;
82+
#else
83+
var timestamp = eventData.TimeStamp;
84+
var osThreadId = eventData.OSThreadId;
85+
#endif
7386

74-
try
75-
{
76-
// TODO - We can only get the OS thread ID from the args - Do we send that instead??
77-
// As per this issue - https://github.com/dotnet/runtime/issues/13125 - OnEventWritten may be on a different thread
78-
// so we can't use the Environment.CurrentManagedThreadId value here.
79-
_logger.WriteLogLine(null, -1, eventData.TimeStamp, GetLogLevel(eventData), StringBuilderCache.GetStringAndRelease(builder), spanId);
80-
}
81-
catch (Exception)
82-
{
83-
// TODO - We might want to block writing further events if we reach here as it's
84-
// likely a file access issue
85-
}
87+
var spanId = CreateLogMessage(eventData, builder, osThreadId);
88+
89+
// TODO - We can only get the OS thread ID from the args - Do we send that instead??
90+
// As per this issue - https://github.com/dotnet/runtime/issues/13125 - OnEventWritten may be on a different thread
91+
// so we can't use the Environment.CurrentManagedThreadId value here.
92+
_logger.WriteLogLine(null, -1, timestamp, GetLogLevel(eventData), StringBuilderCache.GetStringAndRelease(builder), spanId);
8693

8794
static LogLevel GetLogLevel(EventWrittenEventArgs eventData) =>
8895
eventData.Level switch
@@ -96,13 +103,13 @@ static LogLevel GetLogLevel(EventWrittenEventArgs eventData) =>
96103
_ => LogLevel.None
97104
};
98105

99-
static string? CreateLogMessage(EventWrittenEventArgs eventData, StringBuilder builder)
106+
static string? CreateLogMessage(EventWrittenEventArgs eventData, StringBuilder builder, long threadId)
100107
{
101108
string? spanId = null;
102109

103110
if (eventData.EventSource.Name.StartsWith(OpenTelemetrySdkEventSourceNamePrefix) && eventData.Message is not null)
104111
{
105-
builder.Append($"OTEL-SDK: [{eventData.OSThreadId}] ");
112+
builder.Append($"OTEL-SDK: [{threadId}] ");
106113

107114
if (eventData.Payload is null)
108115
{

src/Elastic.OpenTelemetry/Elastic.OpenTelemetry.csproj

Lines changed: 10 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -2,10 +2,11 @@
22

33
<PropertyGroup>
44
<OutputType>Library</OutputType>
5-
<TargetFramework>net8.0</TargetFramework>
5+
<TargetFrameworks>netstandard2.0;netstandard2.1;net8.0;net6.0;net462</TargetFrameworks>
66
<ImplicitUsings>enable</ImplicitUsings>
77
<Nullable>enable</Nullable>
88
<IsPackable>True</IsPackable>
9+
<PolyPublic>false</PolyPublic>
910
</PropertyGroup>
1011

1112
<ItemGroup>
@@ -18,10 +19,16 @@
1819
<PackageReference Include="OpenTelemetry.Instrumentation.EntityFrameworkCore" Version="1.0.0-beta.9" />
1920
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.7.0" />
2021
<PackageReference Include="OpenTelemetry.Instrumentation.Process" Version="0.5.0-beta.4" />
22+
<PackageReference Include="Polyfill" Version="3.0.0" PrivateAssets="All"
23+
IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive"/>
24+
</ItemGroup>
25+
26+
<ItemGroup Condition="$(TargetFramework.StartsWith('netstandard2')) OR $(TargetFramework.StartsWith('net4'))">
27+
<PackageReference Include="System.Threading.Channels" Version="8.0.0" />
2128
</ItemGroup>
2229

2330
<ItemGroup>
24-
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)" />
31+
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)"/>
2532
</ItemGroup>
26-
33+
2734
</Project>

src/Elastic.OpenTelemetry/Processors/SpanCompressionProcessor.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -13,7 +13,7 @@ namespace Elastic.OpenTelemetry.Processors;
1313
/// <summary> A processor that can mark spans as compressed/composite </summary>
1414
public class SpanCompressionProcessor : BaseProcessor<Activity>
1515
{
16-
private readonly ConditionalWeakTable<Activity, Activity> _compressionBuffer = [];
16+
private readonly ConditionalWeakTable<Activity, Activity> _compressionBuffer = new();
1717

1818
/// <inheritdoc cref="OnStart"/>
1919
public override void OnStart(Activity data)

0 commit comments

Comments
 (0)