Skip to content

Commit

Permalink
Update samples and README to use recent .NET host APIs
Browse files Browse the repository at this point in the history
  • Loading branch information
nblumhardt committed Apr 5, 2024
1 parent 4f6a463 commit 74b3884
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 144 deletions.
66 changes: 30 additions & 36 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,10 @@

Serilog logging for _Microsoft.Extensions.Hosting_. This package routes framework log messages through Serilog, so you can get information about the framework's internal operations written to the same Serilog sinks as your application events.

**ASP.NET Core** applications should consider [using _Serilog.AspNetCore_ instead](https://github.com/serilog/serilog-aspnetcore), which bundles this package and includes other ASP.NET Core-specific features.
**Versioning:** This package tracks the versioning and target framework support of its
[_Microsoft.Extensions.Hosting_](https://nuget.org/packages/Microsoft.Extensions.Hosting) dependency. Most users should choose the version of _Serilog.AspNetCore_ that matches
their application's target framework. I.e. if you're targeting .NET 7.x, choose a 7.x version of _Serilog.AspNetCore_. If
you're targeting .NET 8.x, choose an 8.x _Serilog.AspNetCore_ version, and so on.

### Instructions

Expand All @@ -13,46 +16,37 @@ dotnet add package Serilog.Extensions.Hosting
dotnet add package Serilog.Sinks.Console
```

**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged:
**Next**, in your application's _Program.cs_ file, configure Serilog first. A `try`/`catch` block will ensure any configuration issues are appropriately logged. Call `AddSerilog()` on the host application builder:

```csharp
public class Program
using Serilog;

Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

try
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft", LogEventLevel.Information)
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateLogger();

try
{
Log.Information("Starting host");
BuildHost(args).Run();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
Log.CloseAndFlush();
}
}
```
Log.Information("Starting host");

**Then**, add `UseSerilog()` to the host builder in `BuildHost()`.
var builder = Host.CreateApplicationBuilder(args);
builder.Services.AddHostedService<PrintTimeService>();
builder.Services.AddSerilog();

```csharp
public static IHost BuildHost(string[] args) =>
new HostBuilder()
.ConfigureServices(services => services.AddSingleton<IHostedService, PrintTimeService>())
.UseSerilog() // <- Add this line
.Build();
var app = builder.Build();

await app.RunAsync();
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
```

Expand Down
62 changes: 30 additions & 32 deletions samples/SimpleServiceSample/Program.cs
Original file line number Diff line number Diff line change
Expand Up @@ -2,41 +2,39 @@
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;
using Serilog;
using SimpleServiceSample;

namespace SimpleServiceSample;
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();

public static class Program
try
{
public static int Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.Enrich.FromLogContext()
.WriteTo.Console()
.CreateBootstrapLogger();
Log.Information("Getting the motors running...");

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();
}
}
var builder = Host.CreateApplicationBuilder(args);

builder.Services.AddHostedService<PrintTimeService>();

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());
builder.Services.AddSerilog((services, loggerConfiguration) => loggerConfiguration
.ReadFrom.Configuration(builder.Configuration)
.ReadFrom.Services(services)
.Enrich.FromLogContext()
.WriteTo.Console());

var app = builder.Build();

await app.RunAsync();

return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "Host terminated unexpectedly");
return 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
68 changes: 35 additions & 33 deletions samples/WebApplicationSample/Program.cs
Original file line number Diff line number Diff line change
@@ -1,43 +1,45 @@
using System;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.Hosting;
using Serilog;

namespace WebApplicationSample;

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

Log.Information("Starting up!");
Log.Information("Starting up!");

try
{
var builder = WebApplication.CreateBuilder();

try
{
CreateHostBuilder(args).Build().Run();
builder.Services.AddSerilog((services, loggerConfiguration) => loggerConfiguration
.WriteTo.Console()
.ReadFrom.Configuration(builder.Configuration)
.ReadFrom.Services(services));

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

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>(); });
}
app.MapGet("/", () =>
{
Log.Information("Saying hello");
return "Hello World!";
});

await app.RunAsync();

Log.Information("Stopped cleanly");
return 0;
}
catch (Exception ex)
{
Log.Fatal(ex, "An unhandled exception occured during bootstrapping");
return 1;
}
finally
{
await Log.CloseAndFlushAsync();
}
41 changes: 0 additions & 41 deletions samples/WebApplicationSample/Startup.cs

This file was deleted.

5 changes: 3 additions & 2 deletions samples/WebApplicationSample/appsettings.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,9 @@
"MinimumLevel": {
"Default": "Information",
"Override": {
"Microsoft": "Warning",
"Microsoft.Hosting.Lifetime": "Information"
"Microsoft.AspNetCore.Hosting": "Information",
"Microsoft.AspNetCore.Mvc": "Warning",
"Microsoft.AspNetCore.Routing": "Warning"
}
},
"WriteTo": [
Expand Down

0 comments on commit 74b3884

Please sign in to comment.