Asp.Net Mvc Logging Using Nlog Complete Guide
Understanding the Core Concepts of ASP.NET MVC Logging using NLog
ASP.NET MVC Logging using NLog
Logging is a critical part of application development as it helps in monitoring, debugging, and maintaining applications. In ASP.NET MVC, integrating a robust logging framework such as NLog can greatly enhance the diagnostics capabilities of your application.
What is NLog
NLog is an open-source, flexible, and easy-to-configure logging library for .NET. It supports .NET Framework and .NET Core. NLog provides a set of features to handle logging across different platforms with high performance and great reliability.
Features of NLog
- Flexible Configuration: Supports XML, JSON, and code configuration.
- Advanced Routing: Efficient routing rules allow logging to different targets based on log content.
- Layout Rendering: Customizable log formats using layout renderers.
- Extensibility: Easy to extend with custom targets, layouts, filters, and loggers.
- Performance: Optimized for high-performance logging scenarios.
- Asynchronous Logging: Supports asynchronous logging for better responsiveness.
- Large Community and Documentation: Extensive documentation and community support.
Setting Up NLog in ASP.NET MVC
Install NLog via NuGet: Start by adding NLog to your ASP.NET MVC project using the NuGet package manager.
Install-Package NLog Install-Package NLog.Web.AspNetCore (for ASP.NET Core projects)
Configure NLog:
- Create an
NLog.config
file in the root directory of your project. - Set up targets (where logs will be written) and rules (which logs will go to which targets).
Here is an example of a simple
NLog.config
file:<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"> <!-- Define various log targets --> <targets> <!-- Write logs to file --> <target xsi:type="File" name="fileTarget" fileName="logs\log.txt" layout="${longdate} ${level:uppercase=true} ${message} ${exception:format=tostring}" /> <!-- Write logs to console --> <target xsi:type="Console" name="consoleTarget" layout="${date:format=HH\\:mm\\:ss} ${level:uppercase=true} ${message} ${exception:format=tostring}" /> </targets> <!-- Define rules for loggers --> <rules> <logger name="*" minlevel="Info" writeTo="fileTarget" /> <logger name="*" minlevel="Debug" writeTo="consoleTarget" /> </rules> </nlog>
- Create an
Configure Application to Use NLog:
- Modify
Startup.cs
in ASP.NET Core orGlobal.asax.cs
in older ASP.NET MVC projects to configure NLog.
ASP.NET Core:
public class Program { public static void Main(string[] args) { var logger = NLogBuilder.ConfigureNLog("NLog.config").GetCurrentClassLogger(); try { logger.Debug("init main"); CreateHostBuilder(args).Build().Run(); } catch (Exception ex) { // NLog: catch setup errors logger.Error(ex, "Stopped program because of exception"); throw; } finally { // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux) NLog.LogManager.Shutdown(); } } public static IHostBuilder CreateHostBuilder(string[] args) => Host.CreateDefaultBuilder(args) .ConfigureWebHostDefaults(webBuilder => { webBuilder.UseStartup<Startup>(); }) .ConfigureAppConfiguration((hostingContext, config) => { hostingContext.HostingEnvironment.ApplicationName = typeof(Program).Assembly.GetName().Name; }) .ConfigureServices((hostContext, services) => { services.AddNLogWeb(); }); }
- Modify
Logging in Application:
- Use NLog in your controllers and models.
using NLog; public class HomeController : Controller { private static readonly ILogger Logger = LogManager.GetCurrentClassLogger(); public ActionResult Index() { Logger.Info("Visited the index"); return View(); } public ActionResult About() { try { Logger.Info("Visited the about page"); // Simulate an exception throw new Exception("Simulated exception!"); } catch (Exception ex) { Logger.Error(ex, "An error occurred while viewing the about page"); } return View(); } }
Best Practices for Using NLog
- Separation of Concerns: Keep logging separate from business logic.
- Define Log Levels: Use appropriate log levels (
Trace
,Debug
,Info
,Warn
,Error
,Fatal
) for clarity. - Sensitive Information: Avoid logging sensitive data.
- Log Rotation: Implement log rotation to manage file size.
- Error Handling: Handle logging exceptions gracefully to prevent them from affecting application flow.
Conclusion
Implementing logging with NLog in ASP.NET MVC provides a robust mechanism to track and diagnose issues effectively. By following the steps and best practices outlined above, you can leverage NLog's features to create a reliable logging system tailored to your application needs.
Online Code run
Step-by-Step Guide: How to Implement ASP.NET MVC Logging using NLog
Step 1: Create a New ASP.NET MVC Project
- Open Visual Studio.
- File -> New -> Project.
- Select "ASP.NET Web Application (.NET Framework)" under the web category.
- Give your project a name (e.g.,
MvcLoggingExample
) and click "Create". - In the "New ASP.NET Web Application" window, choose "MVC" under the ASP.NET 4.x Templates and click "Create".
Step 2: Install NLog
You can use NuGet Package Manager to install NLog in your project.
- Right-click on your project in the Solution Explorer.
- Go to "Manage NuGet Packages".
- Search for "NLog.Web.Mvc" and install it.
Step 3: Configure NLog
- Open the newly created
nlog.config
file located in the root directory of your project. - Set up targets and rules for logging. Here’s a simple example configuration:
<?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
throwConfigExceptions="true">
<!-- define various log targets -->
<targets>
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="logs/mvcapp-all-${shortdate}.log"
layout="${longdate}|${uppercase:${level}}|${aspnet-traceidentifier}|${message} ${exception:format=tostring}" />
<target xsi:type="File" name="ownFile-web" fileName="logs/mvcapp-own-${shortdate}.log"
layout="${longdate}|${uppercase:${level}}|${aspnet-traceidentifier}|${message} ${exception:format=tostring}" />
<!-- optionally write logs to console while debugging
see https://github.com/nlog/nlog/wiki/Console-target-->
<target xsi:type="Console" name="console" layout="${longdate}|${uppercase:${level}}|${message} ${exception:format=tostring}" />
</targets>
<!-- setup rules -->
<rules>
<!--All logs, including from Microsoft-->
<logger name="*" minlevel="Trace" writeTo="allfile" />
<!--Skip non-critical Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" maxlevel="Info" final="true" /> <!-- blackhole without log -->
<logger name="*" minlevel="Debug" writeTo="ownFile-web" />
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
</nlog>
Step 4: Ensure Proper File Folder Creation
Make sure the folder specified for logs (logs
) exists and that your application has write permissions to this folder. You may need to create this manually or through code.
- Manually create a folder named
logs
in your project root. - Alternatively, add the following lines in your
Application_Start
method to ensure that the logs folder exists:
protected void Application_Start()
{
AreaRegistration.RegisterAllAreas();
FilterConfig.RegisterGlobalFilters(GlobalFilters.Filters);
RouteConfig.RegisterRoutes(RouteTable.Routes);
BundleConfig.RegisterBundles(BundleTable.Bundles);
string logDirectory = Server.MapPath("~/logs");
if (!Directory.Exists(logDirectory))
{
Directory.CreateDirectory(logDirectory);
}
}
Step 5: Modify Controllers to Use NLog
- First, open
HomeController.cs
. - Add the NLog logger to the Controller class.
using System;
using System.IO;
using System.Web.Mvc;
using NLog;
namespace MvcLoggingExample.Controllers
{
public class HomeController : Controller
{
private static readonly Logger Logger = LogManager.GetCurrentClassLogger();
public ActionResult Index()
{
Logger.Info("Visited Home page.");
return View();
}
public ActionResult About()
{
ViewBag.Message = "Your application description page.";
Logger.Info("Visited About page.");
Logger.Debug("Debugging information here.");
return View();
}
public ActionResult Contact()
{
ViewBag.Message = "Your contact page.";
Logger.Info("Visited Contact page.");
try
{
// Simulate something that could throw an exception
int result = 10 / 0;
}
catch (Exception ex)
{
Logger.Error(ex, "Error occurred in Home Contact action.");
}
return View();
}
}
}
Step 6: Test the Logging
- Run your application.
- Navigate to the Index, About, and Contact pages.
- Check the files in the
logs
directory to confirm that log entries are being captured.
Sample Output:
- Index Log Entry:
2023-10-01 10:15:23.7890|INFO|RequestTraceIdentifier|Visited Home page.
- About Log Entry:
2023-10-01 10:15:35.1230|DEBUG|RequestTraceIdentifier|Debugging information here.
2023-10-01 10:15:35.1230|INFO|RequestTraceIdentifier|Visited About page.
- Contact Log Entry:
2023-10-01 10:16:00.5670|ERROR|RequestTraceIdentifier|Error occurred in Home Contact action.
System.DivideByZeroException: Attempted to divide by zero.
Step 7: Clean Up
Ensure that NLog is properly initialized and shut down when the application ends. Add the following lines at the end of Global.asax.cs
.
protected void Application_End()
{
LogManager.Shutdown();
}
Conclusion
You now have a basic logging system in place with NLog in your ASP.NET MVC application. You can further customize NLog according to your application's needs by modifying the nlog.config
file and adding more loggers where required. Happy coding!
Additional Notes:
- NLog Configuration: Customize the
nlog.config
file as per your requirements. You can add multiple targets like database, mail, etc. - Log Levels: Differentiate between the log levels (
Trace
,Debug
,Info
,Warn
,Error
,Fatal
) based on your logging needs. - Custom Layouts: Define custom log layouts for better readability and more information.
Login to post a comment.