ASP.Net Core introduced a new logging framework. It’s available through Microsoft.Extensions.Logging NuGet package.
Using the extension you are able to write your application traces, information and track easily application errors. And the best part is that you can use Microsoft Event Viewer to read them, without using third-party applications.
In this Post, I’ll demonstrate what you need in order to create an application that creates logs to the event viewer.
Creating Event Log Source
To open an elevated PowerShell prompt, in the taskbar search, type PowerShell.
Now see the result Windows PowerShell which appears on the top. Right-click on it and select Run as Administrator.
You can now create a new Event Log Entry by entering following command
New-EventLog -LogName HappyApplication -Source HappyCoderScoure
The command produces the following result
Creating the application
Open Program.cs file and use the ConfigureLogging extension method to declare the event log SourceName, LogName and the desired log level of filter events
public static IWebHost BuildWebHost(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.ConfigureLogging((hostingContext, logging) =>
{
logging.AddConfiguration(hostingContext.Configuration.GetSection("Logging"));
logging.AddEventLog(new EventLogSettings()
{
SourceName = "HappyCoderScoure",
LogName = "HappyApplication",
Filter = (x, y) => y >= LogLevel.Information
});
logging.AddConsole();
})
.Build();
You can use logger in the startup.cs file
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILogger<Startup> logger)
{
if (env.IsDevelopment())
{
app.UseDeveloperExceptionPage();
}
app.Run(async (context) =>
{
logger.LogInformation("Happy Information Level Log !");
await context.Response.WriteAsync("Hello World!");
});
}
Or simply get an ILogger from DI in your controller
[Route("Home")]
public class HomeController : Controller
{
private readonly ILogger _logger;
public HomeController(ILogger<HomeController> logger)
{
_logger = logger;
}
public IActionResult Index()
{
_logger.LogWarning("Showing a Warning from Controller using Dependency injection");
return Ok();
}
}
Until next time,
Happy Coding!