How to log to a file without using third party logger in .Net Core 3 ASP.NET MVC?
There are several libraries available in the market to archive this, But I am using the Serilog.AspNetCore and Serilog.Sinks.RollingFile packages in My Web API project which used .Net Core 3.0.
First You have to configure the Program class as below.
public static void Main(string[] args)
{
Log.Logger = new LoggerConfiguration()
.WriteTo.RollingFile("Log_{Date}.txt")
.MinimumLevel.Debug()
.MinimumLevel.Override("Microsoft.AspNetCore", LogEventLevel.Warning)
.Enrich.FromLogContext()
.CreateLogger();
CreateHostBuilder(args).Build().Run();
Log.CloseAndFlush();
}
public static IHostBuilder CreateHostBuilder(string[] args) =>
Host.CreateDefaultBuilder(args)
.ConfigureWebHostDefaults(webBuilder =>
{
webBuilder.UseStartup<Startup>();
}).UseSerilog();
}
If you need to log the HTTP requests too. You have to configure the app service by adding the following line of code in Startup.cs.
app.UseSerilogRequestLogging();
And Then You can log the Error, Information or Fatal where you want as below.
using Microsoft.Extensions.Logging;
[Route("api/[controller]")]
[ApiController]
public class TestController : ControllerBase
{
private readonly ILogger _logger;
public TestController(ILogger<TestController> logger)
{
_logger = logger;
}
// GET api/values
[HttpGet("{id}")]
public ActionResult<IEnumerable<string>> Get(int id)
{
_logger.LogInformation("Start : Getting item details for {ID}", id);
List<string> list = new List<string>();
list.Add("A");
list.Add("B");
_logger.LogInformation("Completed : Item details for {ID}", list);
return list;
}
}
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