mvc里全局错误日志

第一步在项目中找到App_Start文件夹下建立一个错误日志过滤器。

第二步在Global.asax文件中注册下日志过滤器

第三步: 继承一个ExceptionFilterAtrribute

第四步:重写基类

/// <summary>
/// 重写基类的异常处理方法
/// </summary>
/// <param name="actionExecutedContext"></param>
public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
//1.异常日志记录(正式项目里面一般是用log4net记录异常日志)
//HttpContext.Current.Response.Write(
var LogName = "Log";
var FileAddress = "Log.txt";
var path = HttpContext.Current.Server.MapPath("~/");
string[] temp = path.Split("\\".ToCharArray());
string LevelPath = "";
for (int i = 0; i < temp.Length - 2; i++)
{
LevelPath += temp[i];
LevelPath += "\\";
}
if (!Directory.Exists(LevelPath + "\\" + LogName))//如果不存在就创建file文件夹
{
Directory.CreateDirectory(LevelPath + "\\" + LogName);
}

FileStream fs = null;
if (!File.Exists(LevelPath + "\\" + LogName + "\\" + FileAddress))
{
fs = new FileStream(LevelPath + "\\" + LogName + "\\" + FileAddress, FileMode.Create);
}
else
{
fs = new FileStream(LevelPath + "\\" + LogName + "\\" + FileAddress, FileMode.Append);
}
StreamWriter sw = new StreamWriter(fs);
sw.WriteLine("------------------------------------");
sw.WriteLine("时间:" + DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss"));
sw.WriteLine("异常信息:" + actionExecutedContext.Exception.GetType().ToString() + "||" + actionExecutedContext.Exception.Message);
sw.WriteLine("堆栈信息:" + actionExecutedContext.Exception.StackTrace);
sw.WriteLine("------------------------------------");

//var d = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss") + "——" +
// actionExecutedContext.Exception.GetType().ToString() + ":" + actionExecutedContext.Exception.Message + "——堆栈信息:" +
// actionExecutedContext.Exception.StackTrace;
////);

//2.返回调用方具体的异常信息 501 不支持请求的函数
if (actionExecutedContext.Exception is NotImplementedException)
{
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotImplemented);
}
//错误码 408 超时
else if (actionExecutedContext.Exception is TimeoutException)
{
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.RequestTimeout);
}
//错误码 403 拒绝访问
else if (actionExecutedContext.Exception is NotImplementedException)
{
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.Forbidden);

}
//错误码404
else if (actionExecutedContext.Exception is NotImplementedException)
{
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.NotFound);

}

//.....这里可以根据项目需要返回到客户端特定的状态码。如果找不到相应的异常,统一返回服务端错误500
else
{
actionExecutedContext.Response = new HttpResponseMessage(HttpStatusCode.InternalServerError);
}

base.OnException(actionExecutedContext);
}

注:  我不知道我描述的清不清楚, 实在看不懂 代码粘贴过去就可以用。

posted @ 2017-08-30 16:11  爱与和平  阅读(891)  评论(0编辑  收藏  举报