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
Please note that console logging doesn’t flush the logging on the console until I use Using Statement,
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,
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.
Is there a option to get rid of ApplicationName & Method Name and to log only the LogLevel & the message?
I don’t want to see ConsolAppDI.MyApplication[0].
Hey Senthil, An easy option I could see would be using Console logging with Serilog which could help to control the Verbosity of the logs as per your requirements. In the given link just replaced file logging with Console logging and define your own message structure in the config file or using supported method of the Serilog.
Hope this helps.
Thanks for the response. I would like to achieve the same while writing logs in Application Insights. I don’t want to write the SourceContext. Only the Date & time, Log level and the message.
Thanks for the response. I would like to achieve the same while writing logs in Application Insights. I don’t want to write the SourceContext. Only the Date & time, Log level and the message. Is there any option to do this with ApplicationInsights Logging?
Dear Senthil- Applicationinsight logging can be configured using serilog also. It does have sink called “serilog-sinks-applicationinsights”
Can above procedure be used for console app runing on .net core 3.0?
Hello Mohammad- Yes, you can use the above logic as-is for .NET Core 3.0 as well.
Additionally, another approach using GenericHostBuilder is also preferred. Please see here DI in Console app using generic HostBuilder – Part II
Hope this helps.
Nice
Thanks for sharing
.Net core is a beauty !! Thank you.
Thanks Jeffrey for your comments.Appreciate that!