Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to log to a file without using third party logger in .Net Core 3 ASP.NET MVC?

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/.

like image 473
Roman Avatar asked Nov 01 '19 13:11

Roman


People also ask

Where does the log file get written to in .NET Core logging?

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 .

How do I inject a logger in .NET Core?

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.


1 Answers

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

like image 155
Ryan Avatar answered Oct 08 '22 17:10

Ryan