Record error log in Asp.Net MVC and save to local txt file

In order to facilitate the query of system errors, it is necessary to get an error log for maintenance and operation.

1. In app start of Asp.Net MVC project, add a file ErrorLog for handling exception class to let it inherit HandleErrorAttribute class and override OnException method

public class ErrorLog: HandleErrorAttribute
        public override void OnException(ExceptionContext filterContext)
                //current Controller Name
                string controllName = (string)filterContext.RouteData.Values["controller"];
                //current Action
                string actionName = (string)filterContext.RouteData.Values["action"];
                //Define a HandErrorInfo,Be used for Error View shows exception information
                HandleErrorInfo model = new HandleErrorInfo(filterContext.Exception, controllName, actionName);
                //Time for txt name
                string thisTime = DateTime.Now.ToString("yyyyMMdd");
                string errorDetails = $"Error time:{DateTime.Now.ToString()},The error occurred in{model.ControllerName}Controller{model.ActionName},Error type:{model.Exception.Message}";
                string splitLine = "============================Next item==============================";
                //Log storage location: one folder a month and one file a day in the project directory
                string path = HttpContext.Current.Server.MapPath(@"\ErrorLog\" + DateTime.Now.Year.ToString()+ @"\" + DateTime.Now.ToString("MM") + @"\" );
                //Create if the folder does not exist
                if (!Directory.Exists(path))
                //Write log
                using (System.IO.StreamWriter file = new System.IO.StreamWriter(path + thisTime+".txt", true))

                //Error jump to the specified page, if Global.asax Wrote Application_Error Method can not be written
                ViewResult result = new ViewResult
                    ViewName = this.View,//Set the 404 page to jump to in case of exception
                    ViewData = new ViewDataDictionary<HandleErrorInfo>(model)  //Definition ViewData,generic paradigm
                filterContext.Result = result;
                filterContext.ExceptionHandled = true;//Setting exception handled


Add an Error view under the shared folder in the view, which is the Error log, similar to the 404 page

2. Configure in the FilterConfig.cs file under the app start folder

public class FilterConfig
        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
            filters.Add(new ErrorLog() { View="Error"});


ErrorLog, don't write it wrong. There is an original HandleErrorAttribute class renamed as the one you added in the first step

3. At last, look at Gloabl.asax. There is no FilterConfig registered in Gloabl.asax. Generally, there are

public class MvcApplication : System.Web.HttpApplication
        protected void Application_Start()

4. Call the instance, upload a picture I wrote, no folder throwing exception

/// <summary>
        /// Picture upload
        /// </summary>
        /// <param name="file">picture</param>
        /// <returns></returns>
        public ActionResult FileUpLoad1(HttpPostedFileBase file)
            var ret = string.Empty;
                string fileName = Guid.NewGuid()+file.FileName;
                string filePath = Server.MapPath(@"\FileUp2\");
                //if (!Directory.Exists(filePath))
                   // Directory.CreateDirectory(filePath);
                file.SaveAs(Path.Combine(filePath, fileName));

            catch (Exception ex)
                ret = ex.Message + ":" + ex.InnerException;
                throw new Exception (ex.Message + ":" + ex.InnerException);
                return Json(new { code = "0", msg = "File upload succeeded!", data = "" });
                return Json(new { code = "1", msg = "File upload failed!", data = ret });

Note that if you want to record the log, you must throw out the exception, that is, throw new Exception (ex.Message + ":" + ex.InnerException);

5. The following effects


Posted on Fri, 08 Nov 2019 16:04:23 -0500 by raven2009