Introduction

How to capture the errors from application and write it in a log file. We have to mention the directory path in Webconfig file.

Background

This code is to capture the error log in log file with all information.

The code

Code: CSharp

public class LogError
{
    private DateTime errorDt;
    private string src;
    private Exception errorInfo;
    public static string strDirectoryPath;
    public DateTime ErrorDate
    {
        get {return errorDt; }
        set { errorDt = value;}
    }
    public string ErrorSrc
    {
        get { return src; }
        set { src = value; }
    }
    public Exception ErrorInformation
    {
        get { return errorInfo; }
        set { errorInfo = value; }
    }
 
    public static void Log_Err(string strErrorSource, Exception Ex)
    {
        LogError errInfo = new LogError();
        errInfo.ErrorDate = System.DateTime.Now;
        errInfo.ErrorSrc = strErrorSource;
        errInfo.ErrorInformation = Ex;
        LogError.LogErr(errInfo); 
    }
 
 
    public static void LogErr(LogError errorDTO)
    {
        try
        {
            string directoryPath = strDirectoryPath;
            if (!string.IsNullOrEmpty(strDirectoryPath))
            {
                string path = directoryPath + "\\" + "ErrorLog.txt";
                StreamWriter swErrorLog = null;
                DirectoryInfo dtDirectory = null;
                if (!Directory.Exists(directoryPath))
                {
                    dtDirectory = Directory.CreateDirectory(directoryPath);
                    dtDirectory = null;
                }
                if (File.Exists(path))
                {
                    swErrorLog = new StreamWriter(path, true); //append the error message
                    swErrorLog.WriteLine("Date and Time of Exception: " + errorDTO.ErrorDate);
                    swErrorLog.WriteLine("Source of Exception: " + errorDTO.ErrorSrc);
                    swErrorLog.WriteLine(" ");
                    swErrorLog.WriteLine("Error Message: " + errorDTO.ErrorInformation);
                    swErrorLog.WriteLine("------------------------------------------- ");
                    swErrorLog.WriteLine(" ");
                    //swErrorLog.WriteLine(System.Security.Principal.WindowsIdentity.GetCurrent().Name);
                    swErrorLog.Close();
                    swErrorLog = null;
                }
                else
                {
                    swErrorLog = File.CreateText(path);
                    swErrorLog = new StreamWriter(path, true); //append the error message
                    swErrorLog.WriteLine("Date and Time of Exception: " + errorDTO.ErrorDate);
                    swErrorLog.WriteLine("Source of Exception: " + errorDTO.ErrorSrc);
                    swErrorLog.WriteLine(" ");
                    swErrorLog.WriteLine("Error Message: " + errorDTO.ErrorInformation);
                    swErrorLog.WriteLine("------------------------------------------- ");
                    swErrorLog.WriteLine(" ");
                    swErrorLog.Close();
                    swErrorLog = null;
                }
            }
        }
        catch (NullReferenceException)
        {
            throw;
        } 
    }

the original topic:

Dani AI

Generated

The code sample from is a useful starting point, but rolling your own StreamWriter logger for production brings common risks: file-locking and concurrency, missing request context, lack of rotation/retention, and permission failures. Capture unhandled exceptions at the application level (Global.asax Application_Error) so every request-side error is seen in one place rather than scattered try/catch blocks. (See Microsoft guidance on application-level error handling.) Application_Error / global handler

Practical checklist before shipping:

  • Log the full exception (use the Exception object string/stacktrace and inner exceptions) plus request context (URL, method, authenticated user or correlation id). Exception details & StackTrace
  • Never persist secrets or raw PII — mask or exclude sensitive fields. OWASP Logging Cheat Sheet
  • Store logs outside the web-accessible folder (App_Data or a path outside the site) and grant the IIS application pool identity appropriate ACLs. App‑Pool identities & ACL guidance
  • Use a logger that supports rolling files, async/buffered writes, and safe multi-process writes so logging does not block requests or corrupt files. See mature options below.

On libraries: is right to suggest a real logging framework. NLog and Serilog (and log4net) provide targets/sinks, rolling, async buffering and structured events; they avoid many edge cases of a custom StreamWriter. For file-specific behavior and multi-process sharing see Serilog file sink and NLog file-target notes. NLog (project) · Serilog file sink

Quick troubleshooting tips: permission-denied errors show in Event Viewer; enable the logger’s internal diagnostics (Serilog SelfLog / NLog InternalLogger) to reveal config or IO errors; test logging very early in app startup and ensure proper shutdown/flush when using async sinks. Serilog debugging / SelfLog

Recommended Answers

All 2 Replies

I use . It's free and does more than you could ask for.

.Net framework offers Trace-functionality. When you want to log some within your code you call:

System.Diagnostics.Trace.Write("message");
//or
System.Diagnostics.Trace.WriteLine("message");
//or
System.Diagnostics.Trace.WriteIf(TraceSwitch, "message");
//or
System.Diagnostics.Trace.WriteLineIf(TraceSwitch, "message");

The TraceSwitch catches the loglevel, with the properties Trace.... (e.g TraceInfo).
The TraceSwitch and the tracelistner can be configured in your config file.
The tracelistner catches your trace events and handle them, e.g. write them into a file.

See also:

and
http://msdn.microsoft.com/en-us/library/system.diagnostics.traceswitch.aspx

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.