11

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://learn.microsoft.com/ru-ru/aspnet/core/fundamentals/.

4
  • 1
    Why don't you want to use thirdy part loggers? Surely they are more tested than a home made solution. Commented Nov 1, 2019 at 13:56
  • As far as I undestand ASP.NET Core 3 MVC already contains built-in file logging providers. But I didn't find examples. 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. Commented Nov 1, 2019 at 14:03
  • 3
    Well, then perhaps you can find about built-in logging here Commented Nov 1, 2019 at 14:11
  • Microsoft is not adding a file logger provider to .NET Core. Ref: github.com/aspnet/Logging/issues/441 Commented Feb 26, 2020 at 12:42

2 Answers 2

18

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

Sign up to request clarification or add additional context in comments.

1 Comment

for .net core 3.0 and above, you need to install Serilog.AspNetCore too
5

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;
            }
        }

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.