How to log to a file without using third party logger (serilog, elmah etc.) in .NET CORE?
public void ConfigureSer
.NET Core does not (and probably will not) provide a built-in ILoggerProvider implementation for file logging.
There is a facade which makes trace source logging (the built-in logger framework originated in classic .NET) available for .NET Core applications. It can be ok for those who are already familiar with it, but be prepared that configuration is somewhat cumbersome on .NET Core (for details, see this nice article).
As an alternative, you may try my lightweight ILogger implementation which covers the features of the built-in ConsoleLogger and provides additional essential features and good customizability. My library is free, open-source and has only framework dependencies. It completely conforms with the Microsoft provider implementations.
Usage is as simple as follows:
dotnet add package Karambolo.Extensions.Logging.File
ASP.NET Core 3.x web applications:
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder
.ConfigureLogging((ctx, builder) =>
{
builder.AddConfiguration(ctx.Configuration.GetSection("Logging"));
builder.AddFile(o => o.RootPath = ctx.HostingEnvironment.ContentRootPath);
})
.UseStartup();
});
ASP.NET Core 2.1+ web applications:
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.ConfigureLogging((ctx, builder) =>
{
builder.AddConfiguration(ctx.Configuration.GetSection("Logging"));
builder.AddFile(o => o.RootPath = ctx.HostingEnvironment.ContentRootPath);
})
.UseStartup();
.NET Core 2.1+ console applications:
// build configuration
// var configuration = ...;
// configure DI
var services = new ServiceCollection();
services.AddLogging(builder =>
{
builder.AddConfiguration(configuration.GetSection("Logging"));
builder.AddFile(o => o.RootPath = AppContext.BaseDirectory);
});
// create logger factory
using (var sp = services.BuildServiceProvider())
{
var loggerFactory = sp.GetService();
// ...
}
For configuration details, see the project site.