Skip to content

Commit

Permalink
Merge pull request #87 from nblumhardt/readme-updates
Browse files Browse the repository at this point in the history
Update samples and README to use recent .NET host APIs
  • Loading branch information
nblumhardt authored Apr 5, 2024
2 parents 4f6a463 + 4d2de16 commit d44e684
Show file tree
Hide file tree
Showing 5 changed files with 98 additions and 148 deletions.
70 changes: 30 additions & 40 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.Extensions.Hosting_ that matches
their application's target framework. I.e. if you're targeting .NET 7.x, choose a 7.x version of _Serilog.Extensions.Hosting_. If
you're targeting .NET 8.x, choose an 8.x _Serilog.Extensions.Hosting_ 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 Expand Up @@ -88,7 +82,3 @@ You can alternatively configure Serilog using a delegate as shown below:
This has the advantage of making the `hostingContext`'s `Configuration` object available for configuration of the logger, but at the expense of ignoring `Exception`s raised earlier in program startup.

If this method is used, `Log.Logger` is assigned implicitly, and closed when the app is shut down.

### Versioning

This package tracks the versioning and target framework support of its [_Microsoft.Extensions.Hosting_](https://nuget.org/packages/Microsoft.Extensions.Hosting) dependency.
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 d44e684

Please sign in to comment.