Write log in mvc using HandleErrorInfo

Easy to write log in mvc using StreamWriter


public static class Log
{
    public static void Write(String message)
        {
            try
            {
                string location = HttpContext.Current.Server.MapPath("~/") + "log.txt";
                if (!File.Exists(location))
                {
                    FileStream fs;
                    using (fs = new FileStream(location, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
                    {
                    }
                    fs.Close();
                }
                using (StreamWriter sw = new StreamWriter(location, true))
                {
                    sw.Write("DateTime       : " + DateTime.Now.ToString() + Environment.NewLine + message + Environment.NewLine);
                    sw.Write("================================================================" + Environment.NewLine + Environment.NewLine);
                    sw.Close();
                }
            }
            catch (Exception ex)
            {
                EventLog.WriteEntry("Application", "Error in CreateLogFile" + ex.Message.ToString(), EventLogEntryType.Error, 6000);
            }
        }

    public static void Write(Exception exception)
        {
            Write("Message " + exception.Message + Environment.NewLine + "InnerException " + exception.InnerException);
        }

    public static HandleErrorInfo Write(System.Web.Mvc.HandleErrorInfo exception)
        {
            Write("ActionName     : " + exception.ActionName + " ControllerName : " + exception.ControllerName + Environment.NewLine + "Message        : " + exception.Exception.Message + Environment.NewLine + "InnerException : " + exception.Exception.InnerException);
            return exception;
        }
}

Now call in model. @Log.Write(Model)
@model System.Web.Mvc.HandleErrorInfo
@using htmlHelper.Helper // add namespace
@{
    ViewBag.Title = "Error";
}
<hgroup class="title">
    <h1 class="error">Error.</h1>
    @Html.DisplayFor(m => m.Exception.Message)
    <br />
    @Html.DisplayFor(m => m.Exception.InnerException.Message)
    @Log.Write(Model)
</hgroup>

now call in Controller
Log.Write("Edit Event Call");

pass Exception in log
Exception ex = new Exception();
Log.Write(ex);
Write log in mvc using HandleErrorInfo Write log in mvc using HandleErrorInfo Reviewed by Bhaumik Patel on 11:04 PM Rating: 5