Skip to content

Commit

Permalink
Add additional TFM's to package (#48)
Browse files Browse the repository at this point in the history
* 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
  • Loading branch information
Mpdreamz authored Mar 5, 2024
1 parent f2f6f6c commit bb8f4ec
Show file tree
Hide file tree
Showing 9 changed files with 52 additions and 31 deletions.
2 changes: 1 addition & 1 deletion build/scripts/Targets.fs
Original file line number Diff line number Diff line change
Expand Up @@ -119,7 +119,7 @@ let private generateApiChanges _ =
"assembly-differ"
$"previous-nuget|%s{p}|%s{currentVersion}|%s{tfm}";
//$"directory|.artifacts/bin/%s{p}/release/%s{tfm}";
$"directory|.artifacts/bin/%s{p}/release";
$"directory|.artifacts/bin/%s{p}/release_net8.0";
"-a"; "true"; "--target"; p; "-f"; "github-comment"; "--output"; outputFile
]
exec { run "dotnet" args }
Expand Down
2 changes: 1 addition & 1 deletion src/Elastic.OpenTelemetry/AgentBuilder.Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -67,7 +67,7 @@ internal class EmptyAgent : IAgent
{
public void Dispose() { }

public ValueTask DisposeAsync() => ValueTask.CompletedTask;
public ValueTask DisposeAsync() => default;
}

internal class ElasticAgent(
Expand Down
3 changes: 1 addition & 2 deletions src/Elastic.OpenTelemetry/AgentBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,7 @@ public AgentBuilder SkipOtlpExporter()
/// </summary>
public void ConfigureOtlpExporter(Action<OtlpExporterOptions> configure, string? name = null)
{
ArgumentNullException.ThrowIfNull(configure);
OtlpExporterConfiguration = configure;
OtlpExporterConfiguration = configure ?? throw new ArgumentNullException(nameof(configure));
OtlpExporterName = name;
}
}
Expand Down
4 changes: 4 additions & 0 deletions src/Elastic.OpenTelemetry/Diagnostics/LoggerMessages.cs
Original file line number Diff line number Diff line change
Expand Up @@ -37,7 +37,11 @@ public static void LogAgentPreamble(this ILogger logger)

logger.LogInformation("Process ID: {ProcessId}", process.Id);
logger.LogInformation("Process name: {ProcessName}", process.ProcessName);
#if NET6_0_OR_GREATER
logger.LogInformation("Process path: {ProcessPath}", Environment.ProcessPath);
#else
logger.LogInformation("Process path: {ProcessPath}", "<Unknown>");
#endif

logger.LogInformation("Process started: {ProcessStartTime:yyyy-MM-dd HH:mm:ss.fff}", process.StartTime.ToUniversalTime());
logger.LogInformation("Machine name: {MachineName}", Environment.MachineName);
Expand Down
14 changes: 9 additions & 5 deletions src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -49,11 +49,9 @@ public FileLogger()
if (!Directory.Exists(path))
Directory.CreateDirectory(path);

_streamWriter = new StreamWriter(LogFilePath, Encoding.UTF8, new FileStreamOptions
{
Access = FileAccess.Write,
Mode = FileMode.OpenOrCreate,
});
//StreamWriter.Dispose disposes underlying stream too
var stream = new FileStream(LogFilePath, FileMode.OpenOrCreate, FileAccess.Write);
_streamWriter = new StreamWriter(stream, Encoding.UTF8);

WritingTask = Task.Run(async () =>
{
Expand Down Expand Up @@ -117,7 +115,13 @@ public async ValueTask DisposeAsync()
await WritingTask.ConfigureAwait(false);

if (_streamWriter != null)
{
#if NETSTANDARD2_0 || NETFRAMEWORK
_streamWriter.Dispose();
#else
await _streamWriter.DisposeAsync().ConfigureAwait(false);
#endif
}
}

}
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@ public void Dispose()
}

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

/// <summary> TODO </summary>
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
Expand Down
41 changes: 24 additions & 17 deletions src/Elastic.OpenTelemetry/Diagnostics/LoggingEventListener.cs
Original file line number Diff line number Diff line change
Expand Up @@ -16,8 +16,15 @@ internal sealed partial class LoggingEventListener : EventListener, IAsyncDispos
private readonly ILogger _logger;
private readonly EventLevel _eventLevel = EventLevel.Informational;

[GeneratedRegex("^\\d{2}-[a-f0-9]{32}-[a-f0-9]{16}-\\d{2}$")]
private const string TraceParentRegularExpressionString = "^\\d{2}-[a-f0-9]{32}-[a-f0-9]{16}-\\d{2}$";
#if NET8_0_OR_GREATER
[GeneratedRegex(TraceParentRegularExpressionString)]
private static partial Regex TraceParentRegex();
#else

private static Regex _traceParentRegex = new Regex(TraceParentRegularExpressionString);
private static Regex TraceParentRegex() => _traceParentRegex;
#endif

public LoggingEventListener(ILogger logger)
{
Expand All @@ -44,7 +51,7 @@ public override void Dispose()
}

public ValueTask DisposeAsync() =>
_logger is IAsyncDisposable d ? d.DisposeAsync() : ValueTask.CompletedTask;
_logger is IAsyncDisposable d ? d.DisposeAsync() : default;


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

var spanId = CreateLogMessage(eventData, builder);
#if NETSTANDARD2_0 || NETFRAMEWORK
var timestamp = DateTime.UtcNow; //best effort in absense of real event timestamp
var osThreadId = 0L;
#else
var timestamp = eventData.TimeStamp;
var osThreadId = eventData.OSThreadId;
#endif

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

// TODO - We can only get the OS thread ID from the args - Do we send that instead??
// As per this issue - https://github.com/dotnet/runtime/issues/13125 - OnEventWritten may be on a different thread
// so we can't use the Environment.CurrentManagedThreadId value here.
_logger.WriteLogLine(null, -1, timestamp, GetLogLevel(eventData), StringBuilderCache.GetStringAndRelease(builder), spanId);

static LogLevel GetLogLevel(EventWrittenEventArgs eventData) =>
eventData.Level switch
Expand All @@ -96,13 +103,13 @@ static LogLevel GetLogLevel(EventWrittenEventArgs eventData) =>
_ => LogLevel.None
};

static string? CreateLogMessage(EventWrittenEventArgs eventData, StringBuilder builder)
static string? CreateLogMessage(EventWrittenEventArgs eventData, StringBuilder builder, long threadId)
{
string? spanId = null;

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

if (eventData.Payload is null)
{
Expand Down
13 changes: 10 additions & 3 deletions src/Elastic.OpenTelemetry/Elastic.OpenTelemetry.csproj
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,11 @@

<PropertyGroup>
<OutputType>Library</OutputType>
<TargetFramework>net8.0</TargetFramework>
<TargetFrameworks>netstandard2.0;netstandard2.1;net8.0;net6.0;net462</TargetFrameworks>
<ImplicitUsings>enable</ImplicitUsings>
<Nullable>enable</Nullable>
<IsPackable>True</IsPackable>
<PolyPublic>false</PolyPublic>
</PropertyGroup>

<ItemGroup>
Expand All @@ -18,10 +19,16 @@
<PackageReference Include="OpenTelemetry.Instrumentation.EntityFrameworkCore" Version="1.0.0-beta.9" />
<PackageReference Include="OpenTelemetry.Instrumentation.Runtime" Version="1.7.0" />
<PackageReference Include="OpenTelemetry.Instrumentation.Process" Version="0.5.0-beta.4" />
<PackageReference Include="Polyfill" Version="3.0.0" PrivateAssets="All"
IncludeAssets="runtime; build; native; contentfiles; analyzers; buildtransitive"/>
</ItemGroup>

<ItemGroup Condition="$(TargetFramework.StartsWith('netstandard2')) OR $(TargetFramework.StartsWith('net4'))">
<PackageReference Include="System.Threading.Channels" Version="8.0.0" />
</ItemGroup>

<ItemGroup>
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)" />
<InternalsVisibleTo Include="Elastic.OpenTelemetry.Tests" Key="$(ExposedPublicKey)"/>
</ItemGroup>

</Project>
Original file line number Diff line number Diff line change
Expand Up @@ -13,7 +13,7 @@ namespace Elastic.OpenTelemetry.Processors;
/// <summary> A processor that can mark spans as compressed/composite </summary>
public class SpanCompressionProcessor : BaseProcessor<Activity>
{
private readonly ConditionalWeakTable<Activity, Activity> _compressionBuffer = [];
private readonly ConditionalWeakTable<Activity, Activity> _compressionBuffer = new();

/// <inheritdoc cref="OnStart"/>
public override void OnStart(Activity data)
Expand Down

0 comments on commit bb8f4ec

Please sign in to comment.