Logging in .NET Core to file and console - with timestamps

You can use NLog. Configuration is simple. After configuration all you need to do is inject ILogger<T> where T is the class type that uses the logger.

nlog.config file (don´t forget to copy it to output directory)

<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true" >


  <!-- the targets to write to -->
  <targets>
    <!-- write logs to file -->
    <target xsi:type="File" name="target1" fileName="${basedir}/LogFile.txt"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
    <target xsi:type="Console" name="target2"
            layout="${date}|${level:uppercase=true}|${message} ${exception}|${logger}|${all-event-properties}" />
  </targets>

  <!-- rules to map from logger name to target -->
  <rules>
    <logger name="*" minlevel="Trace" writeTo="target1,target2" />    
  </rules>
</nlog>

.NET Core 2.2 app

using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using NLog.Extensions.Logging;
using System;

namespace ConsoleApp1
{
    public class Program
    {
        static void Main(string[] args)
        {
            var serviceProvider = new ServiceCollection()
                .AddSingleton<IFooService, FooService>()
                .AddLogging(builder =>
                {
                    builder.SetMinimumLevel(LogLevel.Trace);
                    builder.AddNLog(new NLogProviderOptions
                    {
                        CaptureMessageTemplates = true,
                        CaptureMessageProperties = true
                    });
                })
                .BuildServiceProvider();

            ILogger<Program> logger = serviceProvider.GetService<ILoggerFactory>()
                                        .CreateLogger<Program>();
            logger.LogInformation("Starting application...");

            var fooService = serviceProvider.GetService<IFooService>();
            fooService.DoWork();

            Console.ReadLine();
        }
    }
}

FooService

using Microsoft.Extensions.Logging;

namespace ConsoleApp1
{
    public interface IFooService
    {
        void DoWork();
    }

    public class FooService : IFooService
    {
        private readonly ILogger _logger;

        public FooService(ILogger<FooService> logger)
        {
            _logger = logger;
        }

        public void DoWork()
        {
            _logger.LogInformation("Doing work.");
        }
    }
}

App output

2019/03/19 23:03:44.875|INFO|Starting application... |ConsoleApp1.Program|
2019/03/19 23:03:44.920|INFO|Doing work. |ConsoleApp1.FooService|

Or if you don't want to use NLog or any other logging provider you can create your own custom console logger and custom file logger.


Use Serilog, is very simple. See Getting Started page of library.

Install NuGet package:

dotnet add package Serilog.Sinks.File

Console App sample:

using System;
using Serilog;

namespace SerilogExample
{
    class Program
    {
        static void Main()
        {
            Log.Logger = new LoggerConfiguration()
                .MinimumLevel.Debug()
                .WriteTo.Console()
                .WriteTo.File("logs\\logfile_yyyyDDmm.txt")
            .CreateLogger();

            Log.Information("Hello, world!");

            try
            {
                Log.Warning("Warning message..");
                Log.Debug("debug message..");
            }
            catch (Exception ex)
            {
                Log.Error(ex, "Error message");
            }

            Log.CloseAndFlush();
            Console.ReadKey();
        }
    }
}

Output sample:

2021-01-28 00:09:42.123 -03:00 [INF] Hello, world!
2021-01-28 00:09:43.456 -03:00 [WRN] Debug message
2021-01-28 00:09:44.789 -03:00 [DBG] Debug message
2021-01-28 00:09:45.012 -03:00 [ERR] Error message