Error Log in Core 2.0

From Logic Wiki
Jump to: navigation, search


Serilog.AspNetCore

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.


Usage

To keep things sane and streamlined, Serilog is integrated deeper into ASP.NET Core 2.0. It’s much simpler to explain and configure:

  1. Install Serilog.AspNetCore from Nuget
  2. Set up Serilog with LoggerConfiguration in Program.cs, as you would in any other app
  3. Call UseSerilog() on the web host builder to replace the default logging provider


Program.cs

using System;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.Extensions.Configuration;
using Serilog;
using Serilog.Events;

namespace tht.Dashboards.WebApi
{
    public class Program
    {
        public static int Main(string[] args)
        {
            //            BuildWebHost(args).Run();

            var configuration = new ConfigurationBuilder()
                .SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"appsettings.{Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT") ?? "Production"}.json", optional: true)
                .Build();

            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .MinimumLevel.Override("Microsoft", LogEventLevel.Information)
                .Enrich.FromLogContext()
                .WriteTo.Console()
                .WriteTo.RollingFile("./logs/log-{Date}.txt")
                .CreateLogger();

            try
            {
                Log.Information("Host Started");

                var host = new WebHostBuilder()
                    .UseKestrel()
                    .UseContentRoot(Directory.GetCurrentDirectory())
                    .UseIISIntegration()
                    .UseStartup<Startup>()
                    .UseConfiguration(configuration)
                    .UseSerilog()
                    .Build();

                host.Run();

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


        }

    }
}

Where to log?

Depending on how you want to keep the logs, install related nuget packages.

RollingFile

MSSQL

For all available options go to https://github.com/serilog


URL

Serilog Nuget Link

Other Logging Libraries

  • Log4Net
  • NLog