Introduction to Serilog
Serilog is a diagnostic log library for. NET applications. It is easy to set up, has a clean API, and can run on all the latest. NET platforms. Although it is also useful in the simplest applications, Serilog support for structured logging is still useful in complex, distributed and asynchronous applications and systems. —— Introduction to GithubSerilog
Using Serilog through Console
Before using Serilog, you have to download several packages in NuGet, enter them in the NuGet console
>Install-Package Serilog >Install-Package Serilog.Sinks.Console
The first is the core package of Serilog and the other is the receiver, which receives log events and displays them. Only the receiver of the console is downloaded here. For other receivers, you can find them at the following address.
https://github.com/serilog/serilog/wiki/Provided-Sinks
class Program { static void Main(string[] args) { //Log output template string Logformat = @"{Timestamp:yyyy-MM-dd HH:mm-dd }[{Level:u3}] {Message:lj}{NewLine}"; //Similar to creating a pipeline var log = new LoggerConfiguration() //Setting the Minimum Level .MinimumLevel.Debug() //Send events to the console and display them .WriteTo.Console(outputTemplate:Logformat) .CreateLogger(); // Log.Logger = log; //Because the lowest level is Debug, //So Verbose, which is lower than Debug, will not be displayed on the console. Log.Verbose("This is one Verbose"); Log.Information("start"); int a = 0; int b = 2; try { Log.Debug("Calculate the division of the two"); Console.WriteLine(b / a); }catch(Exception ex) { Log.Error(ex, "Calculate unexpected errors"); } Log.Information("End"); } }
Minimum Level of Logger Configuration defaults to Information Level
If you want to log to a file, download the relevant Sinks at NuGet first.
>Install-Package Serilog.Sinks.File
Then add some code to the above program. WriteTo.File()
Log.Logger = new LoggerConfiguration() .MinimumLevel.Debug() .WriteTo.Console(outputTemplate:Logformat) //The first parameter is the file path, the second parameter is the selection of the output template, and the third parameter is to indicate what event the program creates a new log file. .WriteTo.File("logs\\myConsole.log",outputTemplate:Logformat,rollingInterval:RollingInterval.Day) .CreateLogger();
Rolling Interval parameter defaults to Rolling Interval. Infinite never creates new files and does not roll back logs to new files
Using Serilog in Web Programs
The following uses ASP.NET Core to show the effect
First, download the relevant packages in NuGet
>Install-Package Serilog >Install-Package Serilog.AspNetCore >Install-Package Serilog.Sinks.Console >Install-Package Serilog.Sinks.File >Install-Package Serilog.Settings.Configuration
The first and second packages are ASP.NET Core requires core packages, the second and third are receiver packages, and the fourth are used to configure Serilog through external configuration files.
Add Serliog through Program.cs
public class Program { public static void Main(string[] args) { //Select the configuration file appset. JSON var Configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json") .Build(); Log.Logger = new LoggerConfiguration() //Pipeline configuration is modified by configuration file .ReadFrom.Configuration(Configuration) .CreateLogger(); BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() //Method of Serilog.AspNetCore .UseSerilog() .Build(); }
Add configuration information to appsettings.json file
"Serilog": { "MinimumLevel": { "Default": "Debug" }, "WriteTo": [ { "Name": "Console", "Args": { "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm-dd }[{Level:u3}] {Message:lj}{NewLine}{Exception}" } }, { "Name": "File", "Args": { "path": "logs\\myWeb.log", "outputTemplate": "{Timestamp:yyyy-MM-dd HH:mm-dd }[{Level:u3}] {Message:lj}{NewLine}{Exception}" } } ] }
Controller
public class HomeController : Controller { private readonly ILogger<HomeController> _log; public HomeController(ILogger<HomeController> Logger) { _log = Logger; } public IActionResult Index() { _log.LogInformation("start"); int a = 0; int b = 2; try { _log.LogDebug("Calculate the division of the two"); Console.WriteLine(b / a); } catch (Exception ex) { _log.LogError(ex, "Calculate unexpected errors"); } _log.LogInformation("End"); return View(); } }
Reference material
Serilog official documents: https://github.com/serilog/serilog/wiki/Getting-Started