How to Add Logging in .Net Core Console Application
.NET Core provides in built Logging feature which we can to show the Log Information such as Information, Warning, Error etc, We can use the same Logging feature in .NET Core Console application, following steps show to add Logging to your .Net Core Console Appplication:
Step 1: Create the Dot Net Core Console Application with either through .NET CLI or through Visual Studio as shown below:
Use the below command to create dot net core console application through .NET CLI command prompt:
dotnet new console -o ConsoleApp3
Step 2: Once application is created, Add the "Microsoft.Extensions.DependencyInjection" and "Microsoft.Extensions.Logging" Nuget Packages into the Project as shown below:
From .NET CLI run following commands to add Packages:
dotnet add package Microsoft.Extensions.DependencyInjection
dotnet add package Microsoft.Extensions.Logging
dotnet add package Microsoft.Extensions.Logging.Console
Step 3: Include the following using statements at the top of the page of Program.cs file in your Console App:
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
Step 4: Add the following MyApplication class:
class MyApplication
{
private readonly ILogger _logger;
public MyApplication(ILogger<MyApplication> logger)
{
_logger = logger;
}
public void Start()
{
_logger.LogInformation($"MyApplication Started at {DateTime.Now}");
LoadDashboard();
}
private void LoadDashboard()
{
try
{
_logger.LogWarning("MyApplication->LoadDashboard() can throw Exception!");
int[] a = new int[] { 1, 2, 3, 4, 5 };
int b = a[5];
Console.WriteLine($"Value of B: {b}");
}
catch (Exception)
{
throw;
}
finally
{
_logger.LogCritical($"MyApplication->LoadDashboard() Code needs to be fixed");
}
}
public void Stop()
{
_logger.LogInformation($"MyApplication Stopped at {DateTime.Now}");
}
public void HandleError(Exception ex)
{
_logger.LogError($"MyApplication Error Encountered at {DateTime.Now} & Error is: {ex.Message}");
}
}
Step 5: Now in the Program class add the following code:
class Program{
static void Main(string[] args)
{
var services = new ServiceCollection();
ConfigureServices(services);
ServiceProvider serviceProvider = services.BuildServiceProvider();
MyApplication app = serviceProvider.GetService<MyApplication>();
try
{
app.Start();
}
catch (Exception ex)
{
app.HandleError(ex);
}
finally
{
app.Stop();
}
Console.ReadLine();
}
private static void ConfigureServices(ServiceCollection services)
{
services.AddLogging(configure => configure.AddConsole())
.AddTransient<MyApplication>();
}
}
Step 6: Now run the program and see the below output: