Logging in .NET Core Console Application

Logging in NET Core Console application

Today in this article, we will see how to do basic logging using framework-supported providers in the Console .NET Core application.

Today in this article, we will cover below aspects,

As we know .NET Core has introduced ILogger as a generic interface for logging purposes.

This framework-supported interface ILogger can be used across different types of applications like,

  • Console App
  • ASP.NET/WebAPI
  • Desktop or Form applications (.NET Core 3.0 and above)
  • WPF application

Unlike ASP.NET Core, the Console app doesn’t have dependency injection by default. In ASP.NET WebAPI it was easy configuring ILogger through DI. But note that it is not that difficult in a Console application to configure the same.

ILogger interface works very nicely with the .NET Core ecosystem and today in this post we will learn on how to enable logging in a .NET Core Console application.

Getting Started

Here I am using a Console .NET Core 2.2 application.

The below code illustrates how to achieve the logging in to Console applications.

Add ILogger using Dependency Injection to the Console App

public class Program
    {
        static void Main(string[] args)
        {
            var services = new ServiceCollection();
            ConfigureServices(services);
            using (ServiceProvider serviceProvider = services.BuildServiceProvider())
            {
                MyApplication app = serviceProvider.GetService<MyApplication>();
                // Start up logic here
                app.Run();
            }
        }
        private static void ConfigureServices(ServiceCollection services)
        {
            services.AddLogging(configure =>configure.AddConsole())
            .AddTransient<MyApplication>();
        }
    }

In the above code, we added logging and custom Startup MyApplication to the services collection and built the ServiceProvider for the required services.

Now ILogger instance can be DI via Constructor injection as below,

The complete sample code is as below,

public class MyApplication
    {
        private readonly ILogger _logger;
        public MyApplication(ILogger<myapplication> logger)
        {
            _logger = logger;
          
        }
        internal void Run()
        {    
            _logger.LogInformation("Application Started at {dateTime}", DateTime.UtcNow);
             
             //Business Logic START
             //Business logic END
            _logger.LogInformation("Application Ended at {dateTime}", DateTime.UtcNow);
        }
    }

We just enabled Console logging using the below code in the above example by using the Console provider,

services.AddLogging(configure => configure.AddConsole())

Please add below NuGet packages explicitly to your application.

  • Microsoft.Extensions.DependencyInjection
  • Microsoft.Extensions.Logging
  • Microsoft.Extensions.Logging.Console

blank

Please note that console logging doesn’t flush the logging on the console until I use Using Statement,

blank

Here above using statements internally call dispose and flush out console logs.

This is as per my understanding and this solution worked perfectly fine for me. I shall soon put more concrete details on this issue and will be happy to hear from you too.

Let’s run the application and check the logging,

blank

Dependency Injection using Generic Host Builder – Approach 2

Additionally, you can also use Generic Host builder for performing DI for Logging and other business requirements.

Reference: Logging in Console app using Generic Host Builder

Other References :

Summary

Today we learned on how to enable logging in a .NET Core Console application. Unlike .NET Core in WebAPI, the .NET Core Console app doesn’t have dependency injection, but with custom changes as mentioned above, we can very much achieve similar functionality.

Do you have any comments or ideas or any better suggestions to share?

Please sound off your comments below.

Happy Coding !!



Please bookmark this page and share it with your friends. Please Subscribe to the blog to receive notifications on freshly published(2024) best practices and guidelines for software design and development.