Skip to content

File-scoped namespaces #86

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

Merged
merged 1 commit into from
Mar 25, 2024
Merged
Show file tree
Hide file tree
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
27 changes: 13 additions & 14 deletions samples/SimpleServiceSample/PrintTimeService.cs
Original file line number Diff line number Diff line change
Expand Up @@ -4,24 +4,23 @@
using Microsoft.Extensions.Hosting;
using Microsoft.Extensions.Logging;

namespace SimpleServiceSample
namespace SimpleServiceSample;

public class PrintTimeService : BackgroundService
{
public class PrintTimeService : BackgroundService
{
private readonly ILogger _logger;
private readonly ILogger _logger;

public PrintTimeService(ILogger<PrintTimeService> logger)
{
_logger = logger;
}
public PrintTimeService(ILogger<PrintTimeService> logger)
{
_logger = logger;
}

protected override async Task ExecuteAsync(CancellationToken stoppingToken)
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("The current time is: {CurrentTime}", DateTimeOffset.UtcNow);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
_logger.LogInformation("The current time is: {CurrentTime}", DateTimeOffset.UtcNow);
await Task.Delay(TimeSpan.FromSeconds(5), stoppingToken);
}
}
}
63 changes: 31 additions & 32 deletions samples/SimpleServiceSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,41 +3,40 @@
using Microsoft.Extensions.Hosting;
using Serilog;

namespace SimpleServiceSample
namespace SimpleServiceSample;

public static class Program
{
public static class Program
public static int Main(string[] args)
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();

try
{
Log.Information("Getting the motors running...");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
try
{
Log.Information("Getting the motors running...");
CreateHostBuilder(args).Build().Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services => services.AddHostedService<PrintTimeService>())
.UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console());
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureServices(services => services.AddHostedService<PrintTimeService>())
.UseSerilog((context, services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console());
}
63 changes: 31 additions & 32 deletions samples/WebApplicationSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -3,42 +3,41 @@
using Microsoft.Extensions.Hosting;
using Serilog;

namespace WebApplicationSample
namespace WebApplicationSample;

public static class Program
{
public static class Program
public static int Main(string[] args)
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();

Log.Information("Starting up!");
Log.Logger = new LoggerConfiguration()
.WriteTo.Console()
.CreateBootstrapLogger();

Log.Information("Starting up!");

try
{
CreateHostBuilder(args).Build().Run();
try
{
CreateHostBuilder(args).Build().Run();

Log.Information("Stopped cleanly");
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
return 1;
}
finally
{
Log.CloseAndFlush();
}
Log.Information("Stopped cleanly");
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
return 1;
}
finally
{
Log.CloseAndFlush();
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.WriteTo.Console()
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services))
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}

public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((context, services, configuration) => configuration
.WriteTo.Console()
.ReadFrom.Configuration(context.Configuration)
.ReadFrom.Services(services))
.ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); });
}
41 changes: 20 additions & 21 deletions samples/WebApplicationSample/Startup.cs
Original file line number Diff line number Diff line change
Expand Up @@ -9,34 +9,33 @@
using Microsoft.Extensions.Hosting;
using Serilog;

namespace WebApplicationSample
namespace WebApplicationSample;

public class Startup
{
public class Startup
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
// This method gets called by the runtime. Use this method to add services to the container.
// For more information on how to configure your application, visit https://go.microsoft.com/fwlink/?LinkID=398940
public void ConfigureServices(IServiceCollection services)
{
}
}

// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline.
public void Configure(IApplicationBuilder app, IWebHostEnvironment env)
{
if (env.IsDevelopment())
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.UseDeveloperExceptionPage();
}

app.UseRouting();
app.UseRouting();

app.UseEndpoints(endpoints =>
app.UseEndpoints(endpoints =>
{
endpoints.MapGet("/", async context =>
{
endpoints.MapGet("/", async context =>
{
Log.Information("Saying hello");
await context.Response.WriteAsync("Hello World!");
});
Log.Information("Saying hello");
await context.Response.WriteAsync("Hello World!");
});
}
});
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -15,32 +15,31 @@
using System;
using System.Threading;

namespace Serilog.Extensions.Hosting
namespace Serilog.Extensions.Hosting;

class AmbientDiagnosticContextCollector : IDisposable
{
class AmbientDiagnosticContextCollector : IDisposable
{
static readonly AsyncLocal<AmbientDiagnosticContextCollector> AmbientCollector =
new AsyncLocal<AmbientDiagnosticContextCollector>();
static readonly AsyncLocal<AmbientDiagnosticContextCollector> AmbientCollector =
new AsyncLocal<AmbientDiagnosticContextCollector>();

// The indirection here ensures that completing collection cleans up the collector in all
// execution contexts. Via @benaadams' addition to `HttpContextAccessor` :-)
DiagnosticContextCollector _collector;
// The indirection here ensures that completing collection cleans up the collector in all
// execution contexts. Via @benaadams' addition to `HttpContextAccessor` :-)
DiagnosticContextCollector _collector;

public static DiagnosticContextCollector Current => AmbientCollector.Value?._collector;
public static DiagnosticContextCollector Current => AmbientCollector.Value?._collector;

public static DiagnosticContextCollector Begin()
{
var value = new AmbientDiagnosticContextCollector();
value._collector = new DiagnosticContextCollector(value);
AmbientCollector.Value = value;
return value._collector;
}
public static DiagnosticContextCollector Begin()
{
var value = new AmbientDiagnosticContextCollector();
value._collector = new DiagnosticContextCollector(value);
AmbientCollector.Value = value;
return value._collector;
}

public void Dispose()
{
_collector = null;
if (AmbientCollector.Value == this)
AmbientCollector.Value = null;
}
public void Dispose()
{
_collector = null;
if (AmbientCollector.Value == this)
AmbientCollector.Value = null;
}
}
Loading