Skip to content

hexawyz/serilog-aspnetcore

 
 

Repository files navigation

Serilog.AspNetCore Build status NuGet Version

Serilog logging for ASP.NET Core. This package routes ASP.NET Core log messages through Serilog, so you can get information about ASP.NET's internal operations logged to the same Serilog sinks as your application events.

Instructions

First, install the Serilog.AspNetCore NuGet package into your app. You will need a way to view the log messages - Serilog.Sinks.Console writes these to the console; there are many more sinks available on NuGet.

Install-Package Serilog.AspNetCore -DependencyVersion Highest
Install-Package Serilog.Sinks.Console

Next, in your application's Program.cs file, configure Serilog first:

public class Program
{
    public static int Main(string[] args)
    {
        Log.Logger = new LoggerConfiguration()
            .MinimumLevel.Debug()
            .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
            .Enrich.FromLogContext()
            .WriteTo.Console()
            .CreateLogger();

Then, add UseSerilog() to the web host builder. A try/catch block will ensure any configuration issues are appropriately logged:

        try
        {
            Log.Information("Starting web host");

            var host = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .UseIISIntegration()
                .UseStartup<Startup>()
                .UseSerilog() // <-- Add this line
                .Build();

            host.Run();

            return 0;
        }
        catch (Exception ex)
        {
            Log.Fatal(ex, "Host terminated unexpectedly");
            return 1;
        }
        finally
        {
            Log.CloseAndFlush();
        }
    }
}

Finally, clean up by removing the remaining configuration for the default logger:

  • Remove calls to AddLogging()
  • Remove the "Logging" section from appsettings.json files (this can be replaced with Serilog configuration as shown in this example, if required)
  • Remove ILoggerFactory parameters and any Add*() calls on the logger factory in Startup.cs
  • Remove UseApplicationInsights() (this can be replaced with the Serilog AI sink, if required)

That's it! With the level bumped up a little you will see log output like:

[22:14:44.646 DBG] RouteCollection.RouteAsync
	Routes: 
		Microsoft.AspNet.Mvc.Routing.AttributeRoute
		{controller=Home}/{action=Index}/{id?}
	Handled? True
[22:14:44.647 DBG] RouterMiddleware.Invoke
	Handled? True
[22:14:45.706 DBG] /lib/jquery/jquery.js not modified
[22:14:45.706 DBG] /css/site.css not modified
[22:14:45.741 DBG] Handled. Status code: 304 File: /css/site.css

Tip: to see Serilog output in the Visual Studio output window when running under IIS, select ASP.NET Core Web Server from the Show output from drop-down list.

Using the package

With Serilog.AspNetCore installed and configured, you can write log messages directly through Serilog or any ILogger interface injected by ASP.NET. All loggers will use the same underlying implementation, levels, and destinations.

Tip: change the minimum level for Microsoft to Warning and plug in this custom logging middleware to clean up request logging output and record more context around errors and exceptions.

Alternative configuration

You can chose to build the logger as part of the WebHostBuilder pipeline, and thus benefit from the application configuration. The following code shows an example of such a configuration:

public class Program
{
    public static void Main(string[] args)
    {
        var host = new WebHostBuilder()
            .UseKestrel()
            .UseContentRoot(Directory.GetCurrentDirectory())
            // Load the application configuration over the web host configuration.
            .ConfigureAppConfiguration((hostingContext, configurationBuilder) =>
            {
                configurationBuilder
                    .SetBasePath(hostingContext.HostingEnvironment.ContentRootPath)
                    .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                    .AddJsonFile($"appsettings.{hostingContext.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true)
                    .AddEnvironmentVariables();
            })
            // Configure Serilog to be used as the logger for the whole application.
            .UseSerilog((hostingContext, loggerConfiguration) =>
                loggerConfiguration.ReadFrom.Configuration(hostingContext.Configuration)
                    .Enrich.FromLogContext()
                    .WriteTo.Console()
            )
            .UseIISIntegration()
            .UseStartup<Startup>()
            .Build();

        host.Run();
    }
}

With this code, the default behavior is to set the created ILogger as the default logger. Log.Logger can be used as usual to access the created logger.

About

Serilog integration for ASP.NET Core 2+

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published

Languages

  • C# 91.1%
  • PowerShell 7.7%
  • Shell 1.2%