Search This Blog

Wednesday, December 2, 2020

Easiest and shortest sample to get a c# ILogger instance working

 I am embarrassed but I could not get a working ILogger instance to log to the console. I expected this to be achievable with 3, 4 lines. Tried several different approaches, following different posts/articles, nothing !


Using Serilog, however, gives the desired results, easily.

            var serilog = new LoggerConfiguration()

               .MinimumLevel.Debug()

               .WriteTo.Console()

               .WriteTo.File("Logs\\tests.txt", rollingInterval: RollingInterval.Day)

               .CreateLogger();

            

            var logger = new LoggerFactory().AddSerilog(serilog).CreateLogger<LinuxStartUpAndUpdaterManager>();


For instance, I use the following method in a base class all my test classes inherit from:

        protected ILogger<K> GetLogger<K>()

        {

            var serilog = new LoggerConfiguration()

                            .WriteTo.Console()

                            .WriteTo.File("testLog.txt", rollingInterval: RollingInterval.Day)

                            .CreateLogger();


            //if you need a Microsoft.Extensions.Logging ILogger out of your serilog

            return LoggerFactory.Create((c) =>

            {

                c.AddConsole();

                c.AddSerilog(serilog);

            }).CreateLogger<K>();

        }

No comments:

Post a Comment