• Stars
    star
    182
  • Rank 211,154 (Top 5 %)
  • Language
    C#
  • License
    Apache License 2.0
  • Created about 3 years ago
  • Updated about 3 years ago

Reviews

There are no reviews yet. Be the first to send feedback to the community and the maintainers!

Repository Details

A sample project showing Serilog configured in the default .NET 6 web application template

net6.0 Serilog example

This is a sample project showing Serilog configured in the default .NET 6 web application template.

To show how everything fits together, the sample includes:

  • Support for .NET 6's ILogger<T> and WebApplicationBuilder
  • Namespace-specific logging levels to suppress noise from the framework
  • JSON configuration
  • Clean, themed console output
  • Local logging to a rolling file
  • Centralized structured logging with Seq
  • Streamlined HTTP request logging
  • Filtering out of noisy events using Serilog.Expressions
  • Exception logging
  • Fallback/fail-safe bootstrap logger
  • Proper flushing of logs at exit

The code is not commented, so that the structure is easier to compare with the default template. If you're keen to understand the trade-offs and reasoning behind the choices made here, there's some commentary on each section in Setting up from scratch below.

Trying it out

You'll need the .NET 6.0 SDK or later to run the sample. Check the version you have installed with:

dotnet --version

After checking out this repository or downloading a zip file of the source code, you can run the project with:

dotnet run

Some URLs will be printed to the terminal: open them in a browser to see request logging in action.

  • / — should show "Hello, world!" and respond successfully
  • /oops — throws an exception, which will be logged

To see structured log output, start a temporary local Seq instance with:

docker run --rm -it -e ACCEPT_EULA=y -p 5341:80 datalust/seq

and open http://localhost:5341 in your browser (for Windows users, there's also an MSI at https://datalust.co/download).

Setting up from scratch

You can freely copy code from this project to your own applications. If you'd like to set up from scratch, and skip any steps that aren't relevant to you, try following the steps below.

1. Create the project using the web template

mkdir dotnet6-serilog-example
cd dotnet6-serilog-example
dotnet new web

2. Install Serilog packages

dotnet add package serilog.aspnetcore
dotnet add package serilog.sinks.seq
dotnet add package serilog.expressions

3. Initialize Serilog at the start of Program.cs

Its important that logging is initialized as early as possible, so that errors that might prevent your app from starting are logged.

At the very top of Program.cs:

using Serilog;

Log.Logger = new LoggerConfiguration()
    .WriteTo.Console()
    .CreateBootstrapLogger();

Log.Information("Starting up");

CreateBootstrapLogger() sets up Serilog so that the initial logger configuration (which writes only to Console), can be swapped out later in the initialization process, once the web hosting infrastructure is available.

4. Wrap the rest of Program.cs in try/catch/finally

Configuration of the web application in Program.cs can now be enclosed in a try block.

try
{
    // <snip>
}
catch (Exception ex)
{
    Log.Fatal(ex, "Unhandled exception");
}
finally
{
    Log.Information("Shut down complete");
    Log.CloseAndFlush();
}

The catch block will log any exceptions thrown during start-up.

The Log.CloseAndFlush() in the finally block ensures that any queued log events will be properly recorded when the program exits.

5. Wire Serilog into the WebApplicationBuilder

    builder.Host.UseSerilog((ctx, lc) => lc
        .WriteTo.Console()
        .ReadFrom.Configuration(ctx.Configuration));

6. Replace logging configuration in appsettings.json

In appsettings.json, remove "Logging" and add "Serilog".

The complete JSON configuration from the example is:

{
  "Serilog": {
    "MinimumLevel": {
      "Default": "Information",
      "Override": {
        "Microsoft": "Warning",
        "Microsoft.Hosting.Lifetime": "Information"
      }
    },
    "Filter": [
      {
        "Name": "ByExcluding",
        "Args": {
          "expression": "@mt = 'An unhandled exception has occurred while executing the request.'"
        }
      }
    ],
    "WriteTo": [
      {
        "Name": "File",
        "Args": { "path":  "./logs/log-.txt", "rollingInterval": "Day" }
      },
      {
        "Name": "Seq",
        "Args": { "serverUrl":  "http://localhost:5341" }
      }
    ]
  },
  "AllowedHosts": "*"
}

Remove all "Logging" configuration from appsettings.Development.json. (During development, you should normally use the same logging level as you use in production; if you can't find problems using the production logs in development, you'll have an even harder time finding problems in the real production environment.)

7. Add Serilog's request logging middleware

By default, the ASP.NET Core framework logs multiple information-level events per request.

Serilog's request logging streamlines this, into a single message per request, including path, method, timings, status code, and exception.

    app.UseSerilogRequestLogging();

Writing log events

This setup enables both Serilog's static Log class, as you see used in the example above, and Microsoft.Extensions.Logging's ILogger<T>, which can be consumed through dependency injection into controllers and other components.

Viewing structured logs

If you're running a local Seq instance, you can now view the structured properties attached to your application logs in the Seq UI:

Application logs in Seq

Getting help and advice

Ask your question on Stack Overflow and tag it with serilog.

More Repositories

1

superpower

A C# parser construction toolkit with high-quality error reporting
C#
1,064
star
2

serilog-sinks-seq

A Serilog sink that writes events to the Seq structured log server
C#
185
star
3

seqcli

The Seq command-line client. Administer, log, ingest, search, from any OS.
C#
112
star
4

clef-tool

A command-line tool for manipulating Compact Log Event Format files
C#
98
star
5

seq-tickets

Issues, design discussions and feature roadmap for the Seq log server
91
star
6

piggy

A friendly PostgreSQL script runner in the spirit of DbUp.
C#
75
star
7

seq-extensions-logging

Add centralized log collection to ASP.NET Core apps with one line of code.
C#
74
star
8

serilog-middleware-example

An example ASP.NET Core app with smart request logging middleware
C#
74
star
9

seq-api

HTTP API client for Seq
C#
71
star
10

squirrel-json

A vectorized JSON parser for pre-validated, minified documents
Rust
70
star
11

seq-cheat-sheets

Cheat sheets for Seq filtering and querying syntax
64
star
12

seq-forwarder

Local collection and reliable forwarding of log data to Seq
C#
52
star
13

seq-app-htmlemail

Plug-in apps that act on event streams in the Seq log server
C#
49
star
14

seq-input-healthcheck

Periodically GET an HTTP resource and write response metrics to Seq
C#
24
star
15

seq-client-log4net

A log4net appender that writes events to Seq
C#
24
star
16

seq-logging

A Node.js client for the Seq HTTP ingestion API
JavaScript
19
star
17

nlog-targets-seq

An NLog target that writes events to Seq. Built for NLog 4.5+.
C#
16
star
18

seq-input-gelf

Ingest GELF payloads into Seq
Rust
14
star
19

bunyan-seq

A Bunyan stream to send events to Seq
JavaScript
11
star
20

seq-import

A CLI tool for importing JSON-formatted log files directly into Seq
C#
10
star
21

winston-seq

A Winston v3 transport for Seq
TypeScript
10
star
22

pino-seq

A stream to send Pino events to Seq
JavaScript
9
star
23

squiflog

Ingest Syslog payloads into Seq
Rust
7
star
24

seq-input-rabbitmq

A Seq custom input that pulls events from RabbitMQ
C#
7
star
25

seq-docker-windows

Windows Dockerfile for Seq
PowerShell
6
star
26

seq-app-jsonarchive

Record events to a set of newline-delimited JSON streams
Rust
6
star
27

seq-app-httprequest

Send events and notifications to an HTTP/REST/WebHook endpoint.
C#
6
star
28

helm.datalust.co

Helm charts hosted on helm.datalust.co
Mustache
4
star
29

seq-client-portable

A portable (WP/iOS/Android) sink for Serilog that writes events over HTTP/S to Seq
C#
3
star
30

seq-app-opsgenie

Create Opsgenie alerts in response to events or notifications in Seq
C#
3
star
31

seq-app-digestemail

Batched HTML email integration
C#
2
star
32

seq-app-replication

Seq.App.Replication - forward incoming events to another Seq server
C#
2
star
33

express-pino-seq

An example Node.js Express app using `pino` logger together with `pino-seq`
JavaScript
2
star
34

seq-apps-runtime

The Seq app hosting interfaces published as the Seq.Apps NuGet package
C#
2
star
35

seq-app-valuelist

An example Seq app that tracks which values appear in a particular event property
C#
1
star
36

seq-app-thresholds

Seq.App.Thresholds
C#
1
star