Home > database >  How to log exceptions to a file?
How to log exceptions to a file?

Time:12-14

Using this example for my MVC project, I want to log my exception on a file, even without attaching a debugger, when I run my project after publishing it on IIS, not in output window when the project is in debug.

My code is the same as the one presented in the link.

using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Linq;
using System.Web;


namespace ServerSide
{
    public class MyLoggerService : DevExpress.XtraReports.Web.ClientControls.LoggerService
    {
        public override void Info(string message)
        {
            System.Diagnostics.Debug.WriteLine("[{0}]: Info: '{1}'.", DateTime.Now, message);
        }
        public override void Error(Exception exception, string message)
        {
            System.Diagnostics.Debug.WriteLine("[{0}]: Exception occured. Message: '{1}'. Exception Details:\r\n{2}",
                DateTime.Now, message, exception);
        }
    }
}

How could I change this code in order to make it log exceptions to a file?

CodePudding user response:

In case anyone needs it, the solution is to add in Error method this code:

    string filePath = @"C:\ReportDesigner\server\publish\Exceptions.txt";


    using (StreamWriter writer = new StreamWriter(filePath, true))
    {
        writer.WriteLine("-----------------------------------------------------------------------------");
        writer.WriteLine("Date : "   DateTime.Now.ToString());
        writer.WriteLine();

        while (exception != null)
        {
            writer.WriteLine(exception.GetType().FullName);
            writer.WriteLine("Message : "   exception.Message);
            writer.WriteLine("StackTrace : "   exception.StackTrace);

            exception = exception.InnerException;
        }
    }
  • Related