百科.dev
全部条目在线工具AI 编程趋势榜开源项目技术资讯提交条目
登录
< 返回工具列表
D

dotnet6-serilog-example

> 编程语言
开源

一个示例项目,展示了在默认 .NET 6 Web 应用程序模板中配置的 Serilog

196 stars0 点赞0 次浏览
访问官网GitHub

工具介绍

一个示例项目,展示了在默认 .NET 6 Web 应用程序模板中配置的 Serilog

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 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:

bash
dotnet --version

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

bash
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:

bash
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

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

2. Install Serilog packages

bash
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:

csharp
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.

csharp
try
{
    // 
}
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

csharp
    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:

…

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.

csharp
    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, 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:

Getting help and advice

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

Issues· 0 开放

查看全部 Issues在 GitHub 打开

暂无开放 Issues,或尚未同步最近议题。

> 标签

C#

暂无评论,来聊聊你的看法吧

> 工具信息

发布日期2026年8月1日
最后更新2026年9月18日
分类编程语言
定价开源

> 相关工具

T
TypeScript
JavaScript 的超集,为前端与全栈提供静态类型
P
Python
通用编程语言,广泛用于 Web、数据与 AI
G
Go
Google 推出的简洁高效系统语言