Skip to content

Instantly share code, notes, and snippets.

@Longfld
Last active April 24, 2020 19:07
Show Gist options
  • Save Longfld/de7a5d67a8a6af8684c840e569d58f53 to your computer and use it in GitHub Desktop.
Save Longfld/de7a5d67a8a6af8684c840e569d58f53 to your computer and use it in GitHub Desktop.
How to use serilog in ASP.NET Core 2.0
How to use serilog in ASP.NET Core 2.0
One of major changes core 2.0 compare to core 2 preview is how to registe logging.
logging should be configged before website instanced.
public class Program
{
public static void Main(string[] args)
{
var webHost = new WebHostBuilder()
.UseKestrel()
.UseContentRoot(Directory.GetCurrentDirectory())
.ConfigureAppConfiguration((hostingContext, config) =>
{
var env = hostingContext.HostingEnvironment;
config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true)
.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
config.AddEnvironmentVariables();
Log.Logger = new LoggerConfiguration().MinimumLevel.Error().WriteTo.RollingFile(Path.Combine(env.ContentRootPath,"logs/{Date}.txt")).CreateLogger();
})
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddSerilog(dispose: true);
logging.AddConsole();
logging.AddDebug();
})
.UseStartup<Startup>()
.Build();
webHost.Run();
}
}
ConfigureAppConfiguration(hostingContext, config) => {} get website config setting, after that logging configuretion start with:
.ConfigureLogging((hostingContext, logging) =>{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddSerilog(dispose: true);
logging.AddConsole();
logging.AddDebug();
})
You might familiar these code, it is very similar with before, just move from startup.cs to Main(){}.
Before use logging, need to Inject in your class's constructor
public class HomeController : Controller
{
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogError("HomeController: Helloworld ");
return View();
}
private readonly ILogger<HomeController> _logger;
}
See full details and serilog setting in .csproj from here: https://github.com/Longfld/ASPNETcoreAngularJWT
@sarvasana
Copy link

This did not work.
This did work:

    public class Program
    {
        public static void Main(string[] args)
        {
            var webHost = new WebHostBuilder()
                .UseKestrel()
                .UseContentRoot(Directory.GetCurrentDirectory())
                .ConfigureAppConfiguration((hostingContext, config) =>
                {
                    var env = hostingContext.HostingEnvironment;
                    config.AddJsonFile("appsettings.json", optional: true, reloadOnChange: true);
                    config.AddJsonFile($"appsettings.{env.EnvironmentName}.json", optional: true, reloadOnChange: true);
                    config.AddEnvironmentVariables();

                    Log.Logger = new LoggerConfiguration()
                        .ReadFrom.Configuration(config.Build())
                        .CreateLogger();
                })
                .ConfigureLogging((hostingContext, logging) =>
                {
                    logging.AddSerilog(dispose: true);
                })
                .UseStartup<Startup>()
                .Build();

            webHost.Run();
        }
    }

@felixcen
Copy link

felixcen commented Dec 19, 2017

Hi,

Your solution will exclude any secret settings stored locally. You should do the following instead

` public static int Main(string[] args)
        {
            //Build Config
            var currentEnv = Environment.GetEnvironmentVariable("ASPNETCORE_ENVIRONMENT");
            var configuration = new ConfigurationBuilder()
                .AddJsonFile("appsettings.json")
                .AddJsonFile($"appsettings.{currentEnv}.json", optional: true)
                .AddEnvironmentVariables()
                .Build();
            
//Configure logger
            Log.Logger = new LoggerConfiguration()
                .ReadFrom.Configuration(configuration)
                .CreateLogger();
            try
            {
                Log.Information("Starting web host");
                BuildWebHost(args).Run();
                return 0;
            }
            catch (Exception ex)
            {
                Log.Fatal(ex, "Web Host terminated unexpectedly");
                return 1;
            }
            finally
            {
                Log.CloseAndFlush();
            }
        }`

@laksh-parab
Copy link

@youfoundkris solution works howevere i am not sure why you are setting Log.Logger in ConfigureAppConfiguration method instead of ConfigureLogging? Looks like ConfigureLogging is specific to handle any logging configuration

@gimlichael
Copy link

@youfoundkris solution works howevere i am not sure why you are setting Log.Logger in ConfigureAppConfiguration method instead of ConfigureLogging? Looks like ConfigureLogging is specific to handle any logging configuration

Problem is, that ConfigureAppConfiguration can throw an exceptions; a good low level example is AddAzureKeyVault which is part of the Nuget package Microsoft.Extensions.Configuration.AzureKeyVault.

So it is kinda a hen/egg problem; we want the logging - but we need the logger to be able to handle exceptions thrown from ConfigureAppConfiguration :-/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment