Logging errors in ASP.NET MVC

前端 未结 6 1340
温柔的废话
温柔的废话 2020-12-07 06:55

I\'m currently using log4net in my ASP.NET MVC application to log exceptions. The way I\'m doing this is by having all my controllers inherit from a BaseController class.

6条回答
  •  暖寄归人
    2020-12-07 07:28

    MVC3
    Create Attribute that inherits from HandleErrorInfoAttribute and includes your choice of logging

    public class ErrorLoggerAttribute : HandleErrorAttribute 
    {
        public override void OnException(ExceptionContext filterContext)
        {
            LogError(filterContext);
            base.OnException(filterContext);
        }
    
        public void LogError(ExceptionContext filterContext)
        {
           // You could use any logging approach here
    
            StringBuilder builder = new StringBuilder();
            builder
                .AppendLine("----------")
                .AppendLine(DateTime.Now.ToString())
                .AppendFormat("Source:\t{0}", filterContext.Exception.Source)
                .AppendLine()
                .AppendFormat("Target:\t{0}", filterContext.Exception.TargetSite)
                .AppendLine()
                .AppendFormat("Type:\t{0}", filterContext.Exception.GetType().Name)
                .AppendLine()
                .AppendFormat("Message:\t{0}", filterContext.Exception.Message)
                .AppendLine()
                .AppendFormat("Stack:\t{0}", filterContext.Exception.StackTrace)
                .AppendLine();
    
            string filePath = filterContext.HttpContext.Server.MapPath("~/App_Data/Error.log");
    
            using(StreamWriter writer = File.AppendText(filePath))
            {
                writer.Write(builder.ToString());
                writer.Flush();
            }
        }
    

    Place attribute in Global.asax RegisterGlobalFilters

        public static void RegisterGlobalFilters(GlobalFilterCollection filters)
        {
           // filters.Add(new HandleErrorAttribute());
            filters.Add(new ErrorLoggerAttribute());
        }
    

提交回复
热议问题