Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

Getting Started

Ruben Bartelink edited this pageOct 21, 2023 ·21 revisions

Installing from NuGet

The core logging package isSerilog. The supported platforms are .NET/.NET Core, .NET Framework 4.5+, Windows (8/WinRT/Universal+) and Windows Phone 8+.

$ dotnet add package Serilog$ dotnet add package Serilog.Sinks.Console

Browse theSerilog tag on NuGet to see the available sinks, extensions and related third-party packages.

Setup

Types are in the Serilog namespace.

usingSerilog;

The rootLogger is created usingLoggerConfiguration.

usingvarlog=newLoggerConfiguration().WriteTo.Console().CreateLogger();

This is typically done once at application start-up, and the logger saved for later use by application classes. Multiple loggers can be created and used independently if required.

log.Information("Hello, Serilog!");

Serilog's global, statically accessible logger, is set viaLog.Logger and can be invoked using the static methods on theLog class.

Log.Logger=log;Log.Information("The global logger has been configured");

Configuring and using theLog class is an optional convenience that makes it easier for libraries to adopt Serilog. Serilog does not require any static/process-wide state within the logging pipeline itself, so usingLogger/ILogger directly is fine.

Example application

The complete example below shows logging in a simple console application, with events sent to the console as well as a date-stamped rolling log file.

1. Create a new Console Application project

2. Install the core Serilog package,Console sink andFile sink

At a shell prompt in the project directory, type:

$ dotnet add package Serilog$ dotnet add package Serilog.Sinks.Console$ dotnet add package Serilog.Sinks.File

3. Add the following code toProgram.cs

usingSystem;usingSerilog;classProgram{staticasyncTaskMain(){Log.Logger=newLoggerConfiguration().MinimumLevel.Debug().WriteTo.Console().WriteTo.File("logs/myapp.txt",rollingInterval:RollingInterval.Day).CreateLogger();Log.Information("Hello, world!");inta=10,b=0;try{Log.Debug("Dividing {A} by {B}",a,b);Console.WriteLine(a/b);}catch(Exceptionex){Log.Error(ex,"Something went wrong");}finally{awaitLog.CloseAndFlushAsync();}}}

4. Run the program

Serilog Getting Started Example

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp