码迷,mamicode.com
首页 > 其他好文 > 详细

ExceptionLogger

时间:2017-09-22 19:01:23      阅读:139      评论:0      收藏:0      [点我收藏+]

标签:service   string   led   http   serve   att   gas   logger   bsp   

应用1:webconfig.cs中设置

    public static class WebApiConfig
    {
        public static void Register(HttpConfiguration config)
        {

            // Web API routes
            config.MapHttpAttributeRoutes();

            config.Routes.MapHttpRoute(
                name: "DefaultApi",
                routeTemplate: "api/{controller}/{id}",
                defaults: new { id = RouteParameter.Optional }
            );

            //error log
            GlobalConfiguration.Configuration.IncludeErrorDetailPolicy = IncludeErrorDetailPolicy.Always;
            config.Services.Add(typeof(IExceptionLogger), new ApiExceptionLogger());
        }
    }

 

应用二:Global.asax.cs

       protected void Application_Error(object sender, EventArgs e)
        {
            Response.Filter = null;
            var lastError = Server.GetLastError();
            if (lastError != null)
            {
                _logger.Error(lastError, "CRM site exception");
            }
        }    

 

 

ApiExceptionLogger.cs:

 

    public class ApiExceptionLogger: ExceptionLogger
    {
        public ApiExceptionLogger(){}

        public override void Log(ExceptionLoggerContext context)
        {
            StringBuilder sb = new StringBuilder();
            var r = context.Request;
            if (r != null)
            {
                sb.AppendLine($"Unhandled exception processing {r.Method} for {r.RequestUri}");
                if (r.Headers.Count() > 0)
                {
                    sb.AppendLine("Headers Begin:");
                    sb.AppendLine($"{r.Headers.ToString()}");
                    sb.AppendLine("Headers End.");
                }
                if (r.Content!=null)
                {
                    var content = r.Content.ReadAsStringAsync().Result;
                    sb.AppendLine("Contents Begin:");
                    sb.AppendLine(content);
                    sb.AppendLine("Contents End.");
                }
            }
            IIocHelper ioc = IocFactory.Instance;
            var logger = ioc.GetInstance<ILogBase>();
            logger.Error(sb.ToString(), context.Exception);
        }

    }

  

logger:可以使用NLog实现

 

ExceptionLogger

标签:service   string   led   http   serve   att   gas   logger   bsp   

原文地址:http://www.cnblogs.com/panpanwelcome/p/7576094.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!