简体   繁体   中英

Serilog Sink to ASPNET Core Logging

What I would like is to be able to instrument my code with both Serilog and Microsoft.Extensions.Logging (ILogger). And have them both configured the same so they write to the same "sinks". I have an ASPNET Core application with logging working and some dependent libraries, using Serilog, that I would like to capture the log output from (to the same place as the ASPNET Core app).

I'm aware that there is a nuget package to use Serilog logging with ASPNET Core applications. However, this particular extension

(WebAppBuilder).UseSerilog()

Appears to completely replace the existing ILoggerFactory with a serilog version and this stops my ASPNET logging from working. That would be ok if I could simply plugin the serilog config so that it works like the original ASPNET Core mechanism. However, Serilog.Settings.Configuration doesn't seem to faithfully copy the config to Serilog.

It also bothers me that they can't all share the share config, what if I use other libraries that use, say, NLog, how do i integrate that into the same logging infrastructure?

Can Serilog be configured the same as Microsoft.Extensions.Logging? And if so, how is this achieved?

In your Program.cs you will have this (after you've loaded your IConfigurationRoot ):

Log.Logger = new LoggerConfiguration()
    .ReadFrom.Configuration(configuration)
    .WriteTo.Console()
    .CreateLogger();

That sets up a default "Console" sink along with whatever else you may set up in your appsettings.json configuration file.

In your appsettings.json you may have this, for example:

{
    "Serilog": {
        "MinimumLevel": {
            "Default": "Information",
            "Override": {
                "Microsoft": "Warning",
                "System": "Error"
            }
        },
        "WriteTo": [{
            "Name": "Seq",
            "Args": {
                "serverUrl": "http://localhost:5341"
            }
        }],
        "Enrich": ["FromLogContext"],
        "Properties": {
            "Application": "MyApplication"
        }
    }
}

Now you can either write to the static Serilog.Log :

Log.Information("JSON example {@Json}", json);

or to your injected Microsoft.Extensions.Logging.ILogger :

logger.LogInformation("JSON example {@Json}", json);

and both will write to the configured sinks.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM