How to create a log error file in ASP.NET Programming Language?
How to create a log error file in ASP.NET Programming Language?
2 Answers
Creating a log error file in ASP.NET is one of the best ways to track exceptions, debug issues, and monitor application health. There are multiple ways to implement logging, ranging from writing to a text file to using professional logging libraries like NLog, Serilog, or log4net.
Method 1: Create a Simple Text Log File
Create a class named Logger.cs.
using System;
using System.IO;
using System.Web;
public class Logger
{
// Method to write error details into a log file
public static void LogError(Exception ex)
{
try
{
// Folder path where log files will be stored
string path = HttpContext.Current.Server.MapPath("~/Logs/");
// Create the Logs folder if it doesn't exist
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
// Create a log file based on the current date
string filePath = path + DateTime.Now.ToString("dd-MM-yyyy") + ".txt";
// Open the file for appending log entries
using (StreamWriter writer = new StreamWriter(filePath, true))
{
// Write log information
writer.WriteLine("----------------------------------------");
writer.WriteLine("Date : " + DateTime.Now);
writer.WriteLine("Message : " + ex.Message);
writer.WriteLine("Source : " + ex.Source);
writer.WriteLine("StackTrace : " + ex.StackTrace);
writer.WriteLine("----------------------------------------");
}
}
catch
{
// Prevent logging failures from crashing the application
}
}
}
Use the Logger
try
{
// Code that may generate an exception
int number = 10;
int result = number / 0;
}
catch (Exception ex)
{
// Log the exception
Logger.LogError(ex);
}
A log file similar to the following will be created:
----------------------------------------
Date : 21-07-2026 10:15:30 AM
Message : Attempted to divide by zero.
Source : MyApplication
StackTrace : at MyApplication.Default.Page_Load()
----------------------------------------
Method 2: Log Errors in Global.asax
To capture all unhandled exceptions in an ASP.NET application:
protected void Application_Error(object sender, EventArgs e)
{
// Get the last exception
Exception ex = Server.GetLastError();
// Log the exception
Logger.LogError(ex);
}
This automatically records unexpected errors throughout the application.
Method 3: Use NLog (Recommended)
For production applications, use a logging framework such as NLog because it provides:
- File logging
- Database logging
- Email notifications
- Log rotation
- Different log levels (Info, Warn, Error, Fatal)
- Better performance
Example:
using NLog;
// Create a logger instance
private static Logger logger = LogManager.GetCurrentClassLogger();
try
{
// Code that may throw an exception
}
catch (Exception ex)
{
// Log the error
logger.Error(ex, "An unexpected error occurred.");
}
Best Practices
Store logs in a dedicated Logs folder outside publicly accessible content when possible.
Create a new log file daily or monthly to keep files manageable.
Include useful information such as:
- Timestamp
- Exception message
- Stack trace
- User ID (if applicable)
- URL requested
- IP address
Avoid logging sensitive information such as passwords, API keys, or credit card numbers.
Use a mature logging framework like Serilog, NLog, or log4net for production environments instead of manually writing files.
For small ASP.NET projects, the simple Logger class is often sufficient. For enterprise applications, a dedicated logging framework provides greater reliability, configurability, and long-term maintainability.
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Text;
using System.Threading.Tasks;
using System.Globalization;
public partial class _Defaut:System.Web.UI.page
{
protect void page_load(object sender,EventArgs e)
{
try{
var i=10;
var j=0;
var result= i/j;
Responce.Write(result);
}
catch(Exception e){
lblMessage.Text=“Exception generated! Plz check your Log Error File”;
createLogErrorFile(e.ToString());
}
}
private void createLogErrorFile(String errMessage) {
try{
string path=”~/”+DateTime.ToDay.ToString(“dd-mm-yy”)+”.txt”;
if(!File.Exists(System.Web.HttpContext.Current.Server.MathPath(path))
{
File.create(System.Web.HttpContext.Current.Server.MathPath(path)).close();
}
Using(StreamWriter w= File.AppenedText(System.Web.HttpContext.Current.Server.MathPath(path)))
w.WriteLine(“|n |n Log Entry : “);
w.WriteLine(“{0}”, DateTime.Now.ToString(CultureInfo.InvariantCulture));
String err=”Error in : “+System.Web.HttpContext.Current.Request.Url.ToString()+”|n |n Error Message : ”+ errMessage;
w.WriteLine(err);
W.WriteLine(“===========================================”);
w.Flush();
w.close();
}
catch{
throw;
}
}
}
-
0Thank You for the answer. Anonymous User | 7 years ago