How to log to a file without using third party logger (serilog, elmah etc.) in .NET CORE 3 ASP.NET MVC? I haven't find this information on https://docs.microsoft.com/ru-ru/aspnet/core/fundamentals/.
For example, the Console ILoggerProvider writes the logs to the console. This interface is used to create a custom instance of an ILogger . ILoggerFactory : This interface registers one or more ILoggerProvider instances and provides the CreateLogger() method used to create an instance of ILogger .
So, go to the Startup. cs file and add the ILoggerFactory parameter in the Configure() method. Then, call the AddFile() extension method to add Serillog file provider, as shown below. ASP.NET Core dependency injection will automatically pass an instance of the LoggerFactory for this parameter.
If ASP.NET Core 3 MVC doesn't have such built-in functionality the code of using third-party logging providers will be acceptable for me.
MS officially recommends to use 3rd party file loggers.
Using Serilog is also very convenient in asp.net core 3.0:
1.program.cs
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.UseSerilog((ctx, config) => { config.ReadFrom.Configuration(ctx.Configuration); })
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
});
2.appsettings.json
"Serilog": {
"Using": [ "Serilog.Sinks.Console", "Serilog.Sinks.File" ],
"WriteTo": [
{ "Name": "Console" },
{ "Name": "Debug" },
{
"Name": "File",
"Args": {
"path": "log-{Date}.txt",
"rollingInterval": "Day",
"shared": true
}
}
],
"Properties": {
"Application": "SampleApp"
}
}
3.Use the following NuGet packages
<ItemGroup>
<PackageReference Include="Serilog.AspNetCore" Version="3.0.0" />
<PackageReference Include="Serilog.Settings.Configuration" Version="3.1.1-dev-00209" />
<PackageReference Include="Serilog.Sinks.File" Version="4.1.0" />
</ItemGroup>
4. In controller:
public class HomeController : Controller
{
private readonly ILogger<HomeController> _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public async Task Index()
{
_logger.LogInformation("Hello, World!");
}
}
Then you could check the txt file existing in your project.
Refer to https://github.com/serilog/serilog-sinks-file
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With