---
title: "How to create a log error file in ASP.NET Programming Language?"  
description: "How to create a log error file in ASP.NET Programming Language?"  
author: "Arti Mishra"  
published: 2018-10-21  
updated: 2026-07-20  
canonical: https://answers.mindstick.com/qa/50863/how-to-create-a-log-error-file-in-asp-dot-net-programming-language  
category: "asp.net"  
tags: ["asp.net", "log"]  
reading_time: 4 minutes  

---

# How to create a log error file in ASP.NET Programming Language?

How to create a [log error](https://www.mindstick.com/interview/34476/how-to-log-error-in-dot-net-core) [file](https://www.mindstick.com/articles/59/encrypting-and-decrypting-files-using-c-sharp) in [ASP.NET](https://www.mindstick.com/articles/257/ajax-toolkit-calendarextender-control-in-asp-dot-net) [Programming](https://www.mindstick.com/articles/12214/web-development-company-in-india-laid-on-the-foundation-of-concrete-java-programming) [Language](https://www.mindstick.com/startup/28/preply-the-fast-growing-platform-transforming-language-learning)?

## Answers

### Answer by Arti Mishra

**“[Log](https://www.mindstick.com/articles/126269/the-main-uses-of-log-cabins) file”**In any programming language for **tracking our application performance** as well as for **maintaining the history of any bugs or [error](https://www.mindstick.com/forum/459/iis-7-error-503-service-unavailable)**, we generally **create a log file in any temporary folder.** That helps us tosave our time for easily finding the bugs in a whole application.\
\
**Here is the simple example where we can create a log error file in ASP.NET programming language.**\

```
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;
}
}
}
```

\
**Log File : 21-10-18.txt**\
\
Log Entry :21/10/2018 11 : 37 : 15Error In : ..........................................................Error Message : ................................................======================================.\

### Answer by user

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**.

```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

```cs
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:

```plaintext
----------------------------------------
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:

```cs
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:

```cs
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.


---

Original Source: https://answers.mindstick.com/qa/50863/how-to-create-a-log-error-file-in-asp-dot-net-programming-language

Copyright © MindStick Software Pvt. Ltd. This Markdown version is provided for developers, AI systems, and offline reading.
