Skip to content

Commit

Permalink
Run dotnet format as part of the build. (#51)
Browse files Browse the repository at this point in the history
* Add dotnet-format as local tool

* remove dotnet-format, rely on dotnet format instead since the local tool can

* check dotnet formatting as part of the build unless -c is specified

* commit formatting error to test

* add --verify-no-changes

* run dotnet format again
  • Loading branch information
Mpdreamz authored Mar 6, 2024
1 parent 1d8bd3f commit 6ebb95c
Show file tree
Hide file tree
Showing 31 changed files with 420 additions and 415 deletions.
7 changes: 6 additions & 1 deletion build/scripts/Targets.fs
Original file line number Diff line number Diff line change
Expand Up @@ -36,9 +36,14 @@ let private generatePackages _ = exec { run "dotnet" "pack" }
let private pristineCheck (arguments:ParseResults<Build>) =
let skipCheck = arguments.TryGetResult Skip_Dirty_Check |> Option.isSome
match skipCheck, Information.isCleanWorkingCopy "." with
| true, _ -> printfn "Checkout is dirty but -c was specified to ignore this"
| true, _ -> printfn "Skip checking for clean working copy since -c is specified"
| _, true -> printfn "The checkout folder does not have pending changes, proceeding"
| _ -> failwithf "The checkout folder has pending changes, aborting. Specify -c to ./build.sh to skip this check"

match skipCheck, (exec { exit_code_of "dotnet" "format" "--verify-no-changes" }) with
| true, _ -> printfn "Skip formatting checks since -c is specified"
| _, 0 -> printfn "There are no dotnet formatting violations, continuing the build."
| _ -> failwithf "There are dotnet formatting violations. Call `dotnet format` to fix or specify -c to ./build.sh to skip this check"

let private runTests suite _ =
let logger =
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
builder.Services
.AddHttpClient()
.AddOpenTelemetry()
.WithTracing(t=>t.AddAspNetCoreInstrumentation());
.WithTracing(t => t.AddAspNetCoreInstrumentation());

builder.Services
.AddControllersWithViews();
Expand Down
4 changes: 2 additions & 2 deletions examples/Example.Elastic.OpenTelemetry.Worker/Worker.cs
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)
using (var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal))
{
activity?.SetTag("CustomTag", "TagValue");

if (Counter.Enabled)
Counter.Add(1);

Expand All @@ -42,4 +42,4 @@ protected override async Task ExecuteAsync(CancellationToken stoppingToken)

await Task.Delay(5000, stoppingToken);
}
}
}
128 changes: 64 additions & 64 deletions examples/Example.Elastic.OpenTelemetry/Usage.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,12 +12,12 @@ namespace Example.Elastic.OpenTelemetry;

internal static class Usage
{
private const string ActivitySourceName = "CustomActivitySource";
private static readonly ActivitySource ActivitySource = new(ActivitySourceName, "1.0.0");
private static readonly HttpClient HttpClient = new();
private const string ActivitySourceName = "CustomActivitySource";
private static readonly ActivitySource ActivitySource = new(ActivitySourceName, "1.0.0");
private static readonly HttpClient HttpClient = new();

public static async Task BasicBuilderUsageAsync()
{
public static async Task BasicBuilderUsageAsync()
{
// NOTE: This sample assumes ENV VARs have been set to configure the Endpoint and Authorization header.

// Build an agent by creating and using an agent builder, adding a single source (for traces and metrics) defined in this sample application.
Expand Down Expand Up @@ -56,63 +56,63 @@ public static async Task BasicBuilderUsageAsync()

await DoStuffAsync();

static async Task DoStuffAsync()
{
using var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal);
activity?.SetTag("CustomTag", "TagValue");

await Task.Delay(100);
var response = await HttpClient.GetAsync("http://elastic.co");
await Task.Delay(50);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
activity?.SetStatus(ActivityStatusCode.Ok);
else
activity?.SetStatus(ActivityStatusCode.Error);
}
}

//public static async Task ComplexUsageAsync()
//{
// using var agent = Agent.Build(
// traceConfiguration: trace => trace.AddConsoleExporter(),
// metricConfiguration: metric => metric.AddConsoleExporter()
// );
// //agent && Agent.Current now pointing to the same instance;
// var activitySource = Agent.Current.ActivitySource;

// for (var i = 0; i < 2; i++)
// {
// using var parent = activitySource.StartActivity("Parent");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// await StartChildSpansForCompressionAsync();
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// await StartChildSpansAsync();
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// using var _ = activitySource.StartActivity("ChildTwo");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// }

// Console.WriteLine("DONE");

// async Task StartChildSpansForCompressionAsync()
// {
// for (var i = 0; i < 10; i++)
// {
// using var child = activitySource.StartActivity("ChildSpanCompression");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// }
// }

// async Task StartChildSpansAsync()
// {
// using var child = activitySource.StartActivity("Child");
// await Task.Delay(TimeSpan.FromMilliseconds(10));

// // These have effectively ActivitySource = "", there is no way to include this without enabling ALL
// // activities on TracerBuilderProvider.AddSource("*")
// using var a = new Activity("Child2").Start();
// await Task.Delay(TimeSpan.FromMilliseconds(10));
// }
//}
static async Task DoStuffAsync()
{
using var activity = ActivitySource.StartActivity("DoingStuff", ActivityKind.Internal);
activity?.SetTag("CustomTag", "TagValue");

await Task.Delay(100);
var response = await HttpClient.GetAsync("http://elastic.co");
await Task.Delay(50);

if (response.StatusCode == System.Net.HttpStatusCode.OK)
activity?.SetStatus(ActivityStatusCode.Ok);
else
activity?.SetStatus(ActivityStatusCode.Error);
}
}

//public static async Task ComplexUsageAsync()
//{
// using var agent = Agent.Build(
// traceConfiguration: trace => trace.AddConsoleExporter(),
// metricConfiguration: metric => metric.AddConsoleExporter()
// );
// //agent && Agent.Current now pointing to the same instance;
// var activitySource = Agent.Current.ActivitySource;

// for (var i = 0; i < 2; i++)
// {
// using var parent = activitySource.StartActivity("Parent");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// await StartChildSpansForCompressionAsync();
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// await StartChildSpansAsync();
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// using var _ = activitySource.StartActivity("ChildTwo");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// }

// Console.WriteLine("DONE");

// async Task StartChildSpansForCompressionAsync()
// {
// for (var i = 0; i < 10; i++)
// {
// using var child = activitySource.StartActivity("ChildSpanCompression");
// await Task.Delay(TimeSpan.FromSeconds(0.25));
// }
// }

// async Task StartChildSpansAsync()
// {
// using var child = activitySource.StartActivity("Child");
// await Task.Delay(TimeSpan.FromMilliseconds(10));

// // These have effectively ActivitySource = "", there is no way to include this without enabling ALL
// // activities on TracerBuilderProvider.AddSource("*")
// using var a = new Activity("Child2").Start();
// await Task.Delay(TimeSpan.FromMilliseconds(10));
// }
//}
}
3 changes: 2 additions & 1 deletion src/Elastic.OpenTelemetry/AgentBuilder.Build.cs
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,8 @@ public static class OpenTelemetryBuilderExtensions
/// <summary> TODO </summary>
public static IOpenTelemetryBuilder WithLogger(this IOpenTelemetryBuilder builder, ILogger logger)
{
if (builder is not AgentBuilder agentBuilder) return builder;
if (builder is not AgentBuilder agentBuilder)
return builder;

agentBuilder.Logger.SetAdditionalLogger(logger);
return agentBuilder;
Expand Down
5 changes: 3 additions & 2 deletions src/Elastic.OpenTelemetry/AgentBuilder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -48,7 +48,7 @@ public record AgentBuilderOptions
public bool SkipOtlpExporter { get; init; }

/// <summary>
/// Optional name which is used when retrieving OTLP options.
/// Optional name which is used when retrieving OTLP options.
/// </summary>
public string? OtlpExporterName { get; init; }
}
Expand All @@ -68,7 +68,8 @@ public class AgentBuilder : IOpenTelemetryBuilder
public AgentBuilder(params string[] activitySourceNames) : this(new AgentBuilderOptions
{
ActivitySources = activitySourceNames
}) { }
})
{ }

/// <summary> TODO </summary>
public AgentBuilder(AgentBuilderOptions options)
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -40,8 +40,8 @@ public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollect
/// <returns></returns>
public static IOpenTelemetryBuilder AddElasticOpenTelemetry(this IServiceCollection serviceCollection, AgentBuilderOptions options)
{
if (serviceCollection.Any(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ElasticOtelDistroService)))
{
if (serviceCollection.Any(d => d.ServiceType == typeof(IHostedService) && d.ImplementationType == typeof(ElasticOtelDistroService)))
{
var sp = serviceCollection.BuildServiceProvider();
return sp.GetService<AgentBuilder>()!; //already registered as singleton
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -30,12 +30,14 @@ public ValueTask DisposeAsync()
/// <summary> TODO </summary>
public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Exception? exception, Func<TState, Exception?, string> formatter)
{
if (_isDisposed) return;
if (_isDisposed)
return;

if (FileLogger.IsEnabled(logLevel))
FileLogger.Log(logLevel, eventId, state, exception, formatter);

if (additionalLogger == null) return;
if (additionalLogger == null)
return;

if (additionalLogger.IsEnabled(logLevel))
additionalLogger.Log(logLevel, eventId, state, exception, formatter);
Expand All @@ -58,7 +60,7 @@ private class CompositeDisposable(params IDisposable?[] disposables) : IDisposab
{
public void Dispose()
{
foreach(var disposable in disposables)
foreach (var disposable in disposables)
disposable?.Dispose();
}
}
Expand Down
16 changes: 5 additions & 11 deletions src/Elastic.OpenTelemetry/Diagnostics/Logging/FileLogger.cs
Original file line number Diff line number Diff line change
Expand Up @@ -34,7 +34,8 @@ public FileLogger()
_scopeProvider = new LoggerExternalScopeProvider();
var process = Process.GetCurrentProcess();

if (!FileLoggingEnabled) return;
if (!FileLoggingEnabled)
return;

var configuredPath = Environment.GetEnvironmentVariable(EnvironmentVariables.ElasticOtelLogDirectoryEnvironmentVariable);

Expand All @@ -56,8 +57,8 @@ public FileLogger()
WritingTask = Task.Run(async () =>
{
while (await _channel.Reader.WaitToReadAsync().ConfigureAwait(false) && !_disposing)
while (_channel.Reader.TryRead(out var logLine) && !_disposing)
await _streamWriter.WriteLineAsync(logLine).ConfigureAwait(false);
while (_channel.Reader.TryRead(out var logLine) && !_disposing)
await _streamWriter.WriteLineAsync(logLine).ConfigureAwait(false);

_syncDisposeWaitHandle.Set();
});
Expand Down Expand Up @@ -114,14 +115,7 @@ public async ValueTask DisposeAsync()
if (WritingTask != null)
await WritingTask.ConfigureAwait(false);

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

}
Original file line number Diff line number Diff line change
Expand Up @@ -28,7 +28,8 @@ public void Log<TState>(LogLevel logLevel, EventId eventId, TState state, Except
if (fileLogger.IsEnabled(logLevel))
fileLogger.Log(logLevel, eventId, state, exception, formatter);

if (additionalLogger == null) return;
if (additionalLogger == null)
return;

if (additionalLogger.IsEnabled(logLevel))
additionalLogger.Log(logLevel, eventId, state, exception, formatter);
Expand All @@ -45,7 +46,7 @@ private class CompositeDisposable(params IDisposable?[] disposables) : IDisposab
{
public void Dispose()
{
foreach(var disposable in disposables)
foreach (var disposable in disposables)
disposable?.Dispose();
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,7 @@ class LoggingEventListener : EventListener, IAsyncDisposable
private static partial Regex TraceParentRegex();
#else

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

Expand Down
15 changes: 7 additions & 8 deletions src/Elastic.OpenTelemetry/Exporters/BatchExporter.cs
Original file line number Diff line number Diff line change
@@ -1,18 +1,17 @@
// Licensed to Elasticsearch B.V under one or more agreements.
// Elasticsearch B.V licenses this file to you under the Apache 2.0 License.
// See the LICENSE file in the project root for more information
using OpenTelemetry;

using System.Diagnostics;
using OpenTelemetry;

namespace Elastic.OpenTelemetry.Exporters;

internal class BatchExporter : BaseExporter<Activity>
{
public override ExportResult Export(in Batch<Activity> batch)
{
using var scope = SuppressInstrumentationScope.Begin();
Console.WriteLine($"Exporting: {batch.Count:N0} items");
return ExportResult.Success;
}
public override ExportResult Export(in Batch<Activity> batch)
{
using var scope = SuppressInstrumentationScope.Begin();
Console.WriteLine($"Exporting: {batch.Count:N0} items");
return ExportResult.Success;
}
}
Loading

0 comments on commit 6ebb95c

Please sign in to comment.