Location>code7788 >text

Serilog Documentation Translation Series (VII) - Application Setup, Debugging and Diagnostics, Development Receiver

Popularity:82 ℃/2024-10-09 00:14:42

01Application Settings

Serilog supports the use of the simple Configuration syntax to set the minimum log level, add additional attributes to events, and control log output.

Serilog is primarily configured through code, and setup support is intended to be a supplemental feature. While not comprehensive, most logging configuration tasks can be accomplished through it.

1. Enable configure

Requires installation from NuGet Support Package:

Install-Package 

reliable source (of funds) To read the configuration, use the () extension method on LoggerConfiguration:

 = new LoggerConfiguration()
  .()
  ... // Other configuration here, then
  .CreateLogger()

You can use a combination of XML and code-based configuration, but each receiver (sink) must be configured via XML or code - receivers added via code cannot be modified via application settings.

2. Configure the logger

To configure the logger, you should include in your program's or file a Elements.

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
  <appSettings>
    <add **key**="serilog:minimum-level" **value**="Verbose" />
    <!-- More settings here -->

Setting the minimum log level

To set the logging level for your application, use the serilog:minimum-level setting key.

<add **key**="serilog:minimum-level" **value**="Verbose" />

Valid values are those defined in the LogEventLevel enumeration: Verbose, Debug, Information, Warning, Error, Fatal.

Add Receiver

The receiver is added via the serilog:write-to key. The name of the setting matches the name of the configuration method used in the code, so the following two are equivalent:

  .()

in XML:

  <add **key**="serilog:write-to:LiterateConsole" />

Note: Uniqueness needs to be ensured when using serilog:* keys.

The receiver assembly must be specified using the serilog:using syntax. For example, to configure:

  <add **key**="serilog:using:LiterateConsole" **value**="" />
  <add **key**="serilog:write-to:LiterateConsole"/>

If the receiver accepts parameters, specify them by appending the parameter name to the setting.

  .(@"C:\Logs\myapp-{Date}.txt", retainedFileCountLimit: 10)

in XML:

  <add **key**="serilog:using:RollingFile" **value**="" />
  <add **key**="serilog:write-to:" **value**="C:\Logs\myapp-{Date}.txt" />
  <add **key**="serilog:write-to:" **value**="10" />

Any environment variables specified in the setup values (e.g. %TEMP%) will be expanded appropriately when read.

Using receiver extensions from additional assemblies

To use receivers and enrichers from additional assemblies, specify them with the serilog:using key.

For example, to use a configuration from an assembly:

  <add **key**="serilog:using:EventLog" **value**="" />
  <add **key**="serilog:write-to:" **value**="Serilog Demo" />

Enriching Logs with Attributes

To attach additional properties to log events, specify them using the serilog:enrich:with-property directive.

For example, to add the property Release to all events and assign the value "1.2-develop":

  <add **key**="serilog:enrich:with-property:Release" **value**="1.2-develop" />

Add Minimum Level Override

As of Serilog 2.1, it is possible to add a minimum-level override to change the minimum level of certain specific namespaces. This is done by setting the key serilog:minimum-level:override: followed by the source context prefix.

For example, the following two are equivalent:

 = new LoggerConfiguration()
    .()
    .("Microsoft", )
    .("", )

in XML:

    <add **key**="serilog:minimum-level" **value**="Information" />
    <add **key**="serilog:minimum-level:override:Microsoft" **value**="Warning" />
    <add **key**="serilog:minimum-level:override:" **value**="Error" />

02, debugging and diagnostics

When Serilog does not behave as you expect, this may be due to an internal exception or a configuration problem. Here are a few ways to fix the problem.

1、SelfLog

First, Serilog will write simple diagnostic messages if user-specified output is provided. Call () at program startup:

(msg => (msg));

Instead of using a delegate, a StringWriter on the system console, in a file, or in memory can collect Serilog output by providing a TextWriter:

();

Serilog does not write its own events to user-defined receivers.

Warning: SelfLog does not perform any synchronization with the supplied TextWriter. For most implementations, you should use the () method to ensure that incoming objects can be written from multiple threads:

var file = (...);
((file));

2. Debugging symbols

Most Serilog packages include debug symbols (_.PDB) on the symbolsource - adding them as a symbol server in Visual Studio can help determine the cause of an exception from the receiver.

3. Serilog Analyzer

This is a Roslyn-based analysis tool for code that uses the Serilog logging library. It checks for common errors and usage issues. You can find more information here.

03, Development Receiver

The following example creates a project using the dotnet command.

1、Create project

mkdir SimpleSink
cd SimpleSink
dotnet new console

Adding dependencies

Add Serilog package from NuGet:

dotnet add package serilog

2、Build a simple receiver

The following using statements are included. These statements are used for the receiver class and to configure Serilog.

using Serilog;
using ;
using ;
using ;

Creating a Receiver

Receivers are simply classes that implement the ILogEventSink interface. The following example renders each message (regardless of log level) to the console.

public class MySink : ILogEventSink
{
    private readonly IFormatProvider _formatProvider;
    public MySink(IFormatProvider formatProvider)
    {
        _formatProvider = formatProvider;
    }
    public void Emit(LogEvent logEvent)
    {
        var message = (_formatProvider);
        (() + " "  + message);
    }
}

Configuration extensions

When configuring a receiver, it is common to use a pattern that provides an extension method class for LoggerSinkConfiguration. The following code illustrates this approach by exposing the MySink option when configuring Serilog.

public static class MySinkExtensions
{
    public static LoggerConfiguration MySink(
              this LoggerSinkConfiguration loggerConfiguration,
              IFormatProvider formatProvider = null)
    {
        return (new MySink(formatProvider));
    }
}

Using the receiver

As shown in Configuration Basics, a new receiver can be configured as follows.

var log = new LoggerConfiguration()
    .()
    .()
    .CreateLogger();

Release of resources

If the receiver implements IDisposable, Serilog will call its Dispose() method when calling () (when using the static Log class) or when releasing the Logger written to the receiver directly.

Handling errors and exceptions

If the receiver is unable to accept or successfully process an event, it can (and should) throw an exception from Emit() to notify Serilog.Unless the receiver is explicitly configured for auditing, Serilog suppresses the exception and writes a standard diagnostic message to SelfLog.

The receiver can also write diagnostic messages to SelfLog, but this should be used with caution to avoid adverse effects on performance.

thread safety

The receiver must be completely thread-safe when it is constructed and accept Emit() calls from any thread. the Serilog will call Emit() concurrently.

3. Complete Example

Below is the complete sample code as a console application.

using System;
using Serilog;
using ;
using ;
using ;
namespace SimpleSink
{
    class Program
    {
        static void Main(string[] args)
        {
            var log = new LoggerConfiguration()
                .()
                .()
                .CreateLogger();
            var position = new { Latitude = 25, Longitude = 134 };
            var elapsedMs = 34;
            ("Processed {@Position} in {Elapsed:000} ms.", position, elapsedMs);
        }
    }
    public class MySink : ILogEventSink
    {
        private readonly IFormatProvider _formatProvider;
        public MySink(IFormatProvider formatProvider)
        {
            _formatProvider = formatProvider;
        }
        public void Emit(LogEvent logEvent)
        {
            var message = (_formatProvider);
            (() + " "  + message);
        }
    }
    public static class MySinkExtensions
    {
        public static LoggerConfiguration MySink(
                  this LoggerSinkConfiguration loggerConfiguration,
                  IFormatProvider formatProvider = null)
        {
            return (new MySink(formatProvider));
        }
    }
}

sample output

17/01/2017 3:10:26 PM +10:00 Processed { Latitude: 25, Longitude: 134 } in 034 ms.

classifier for sums of money: All relevant source code has been uploaded to the codebase for those who are interested./hugogoos/Planner