.NET WebAPI 用ExceptionFilterAttribute实现错误(异常)日志的记录(log4net做写库操作)

时间:2021-06-11 04:22:36

好吧,还是那个社区APP,非管理系统,用户行为日志感觉不是很必要的,但是,错误日志咱还是得记录则个。总不能上线后报bug了让自己手足无措吧,虽然不管有木有错误日志报bug都是件很头疼的事...

我们知道webAPI也有好几个Filter,上篇文章我们做token与权限用到了ActionFilterAttribute,这次我们用ExceptionFilterAttribute来做异常日志的记录。首先我们的代码里面会主动的捕获一些异常手动抛出,例如对用户输入数据的验证,权限的验证,业务的验证等。也会有一些我们无法预料的异常,可能是代码的漏洞或者逻辑的漏洞...那么我们肯定是想能够在一个切面全部拦截这些异常,记录到错误日志中,以便作分析使用...

博主使用的log4net做日志的写库操作,这里就不介绍log4net的基本用法了,直接上代码:

 <log4net>
<!--<appender name="RollingFileAppender" type="log4net.Appender.RollingFileAppender">
<file value="C:\testlog.txt" />
<appendToFile value="true" />
<maxSizeRollBackups value="" />
<maximumFileSize value="" />
<rollingStyle value="Date" />
<datePattern value="yyyy-MM-dd" />
<staticLogFileName value="true" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="记录时间:%date 线程ID:[%thread] 日志级别:%-5level 出错类:%logger property:[%property{NDC}] - 错误描述:%message%newline " />
</layout>
</appender>-->
<appender name="AdoNetAppender_Sqlserver" type="log4net.Appender.AdoNetAppender">
<connectionType value="System.Data.SqlClient.SqlConnection,System.Data, Version=4.0.0.0, Culture=neutral,PublicKeyToken=b77a5c561934e089" />
<connectionString value="Data Source=.;database=RCBLog;Integrated Security=True; MultipleActiveResultSets=True;" />
<commandText value="INSERT INTO ErrorLog (LOGID,LOG_DATE,LOG_MESSAGE,LOG_EXCEPTION,LOG_LEVEL,LOGGER,LOG_SOURCE,OPERATORID,OPERATORACCOUNTNAME) VALUES (@LogId,@log_date,@LogMessage,@LogException,@log_level, @logger, @source,@LogOperator,@OperatorAccountName)" />
<bufferSize value="10" />
<parameter>
<parameterName value="@log_date" />
<dbType value="DateTime" />
<layout type="log4net.Layout.RawTimeStampLayout" />
</parameter>
<parameter>
<parameterName value="@log_level" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%level" />
</layout>
</parameter>
<parameter>
<parameterName value="@logger" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%logger" />
</layout>
</parameter>
<parameter>
<parameterName value="@source" />
<dbType value="String" />
<size value="" />
<layout type="log4net.Layout.PatternLayout">
<conversionPattern value="%file:%line" />
</layout>
</parameter>
<!--自定义属性-->
<parameter>
<parameterName value="@LogId" />
<dbType value="String" />
<size value="" />
<layout type="MP.Infrastructure.SystemLog.CustomLayout,MP.Infrastructure">
<conversionPattern value="%LogId" />
</layout>
</parameter>
<parameter>
<parameterName value="@LogException" />
<dbType value="String" />
<size value="" />
<layout type="MP.Infrastructure.SystemLog.CustomLayout,MP.Infrastructure">
<conversionPattern value="%LogException" />
</layout>
</parameter>
<parameter>
<parameterName value="@LogMessage" />
<dbType value="String" />
<size value="" />
<layout type="MP.Infrastructure.SystemLog.CustomLayout,MP.Infrastructure">
<conversionPattern value="%LogMessage" />
</layout>
</parameter>
<parameter>
<parameterName value="@LogOperator" />
<dbType value="String" />
<size value="" />
<layout type="MP.Infrastructure.SystemLog.CustomLayout,MP.Infrastructure">
<conversionPattern value="%OperatorId" />
</layout>
</parameter>
<parameter>
<parameterName value="@OperatorAccountName" />
<dbType value="String" />
<size value="" />
<layout type="MP.Infrastructure.SystemLog.CustomLayout,MP.Infrastructure">
<conversionPattern value="%OperatorAccountName" />
</layout>
</parameter>
</appender>
<logger name="RCB.Logger.Error">
<level value="ERROR" />
<!--<appender-ref ref="RollingFileAppender" />-->
<appender-ref ref="AdoNetAppender_Sqlserver" />
</logger>
</log4net>

注:

1.<log4net>节点需要在<configuration>节点下

2.注释掉的2-13行与97行是写文件

3.第23行的数值表示缓存值,调试阶段可以设置成0,才能及时的在数据库看到错误日志

4.博主使用到了自定义属性,就顺便说说自定义属性的用法,先看看博主的错误日志类:

     /// <summary>
/// 系统错误日志
/// </summary>
public class ErrorLog
{
/// <summary>
/// ID(GUID字符串)
/// </summary>
public string LOGID { get; set; } /// <summary>
/// 日志时间
/// </summary>
public DateTime LOG_DATE { get; set; } /// <summary>
/// 日志错误信息
/// </summary>
public string LOG_MESSAGE { get; set; } /// <summary>
/// 异常信息详情
/// </summary>
public string LOG_EXCEPTION { get; set; } /// <summary>
/// 错误级别
/// </summary>
public string LOG_LEVEL { get; set; } /// <summary>
/// 记录器(PRMMS.Logger)
/// </summary>
public string LOGGER { get; set; } /// <summary>
/// 日志产生位置
/// </summary>
public string LOG_SOURCE { get; set; } /// <summary>
/// 操作人ID
/// </summary>
public string OperatorId { get; set; } /// <summary>
/// 操作账户名
/// </summary>
public string OperatorAccountName { get; set; } /// <summary>
/// 自动创建ID
/// </summary>
public ErrorLog()
{
this.LOGID = Guid.NewGuid().ToString("N").ToUpper();
}
}

其中,LogId、LogMessage、OperatorId、OperatorAccountName、LogException等字段是log4net不带有的,属于自定义属性,需要做一个配置。我们新建一个CustomLayout类,继承于PatternLayout

     public class CustomLayout : PatternLayout
{
public CustomLayout()
{
base.AddConverter("LogId", typeof(LogId));
base.AddConverter("LogMessage", typeof(LogMessage));
base.AddConverter("OperatorId", typeof(OperatorId));
base.AddConverter("OperatorAccountName", typeof(OperatorAccountName));
base.AddConverter("LogException", typeof(LogException));
}
}

其中,typeof(LogId)中的LogId是需要我们新建类继承PatternLayoutConverter实现Convert方法的

     internal sealed class LogId : PatternLayoutConverter
{
protected override void Convert(TextWriter writer, LoggingEvent loggingEvent)
{
var content = loggingEvent.MessageObject as ErrorLog;
if (content != null)
{
writer.Write(content.LOGID);
}
}
}

当然,剩余几个typeof()做同样处理即可。

log4net写库配置好了,我们还需要一个日志工具类,用来调用log4net写日志,博主在这儿简单写了几个方法,其中截取2000长度纯属个人原因,没有特别意义:

     /// <summary>
/// 日志工具类
/// </summary>
public class LogUtils
{
private static readonly log4net.ILog errorLog = log4net.LogManager.GetLogger("RCB.Logger.Error"); /// <summary>
/// 将指定的<see cref="Exception"/>实例详细信息写入错误日志。
/// </summary>
/// <returns></returns>
public static void ErrorLog(Guid userId, string userName, Exception exception)
{
if (exception != null)
{
var exceptionString = exception.ToString();
if (exceptionString.Length > )
{
exceptionString = exceptionString.Substring(, );
}
errorLog.Error(new ErrorLog
{
OperatorId = userId.ToString("N").ToUpper(),
OperatorAccountName = userName,
LOG_MESSAGE = exception.Message,
LOG_EXCEPTION = exceptionString
});
}
} /// <summary>
/// 将指定的<see cref="Exception"/>实例详细信息写入错误日志。
///
/// 记录IP地址
/// </summary>
/// <returns></returns>
public static void ErrorLog(string userIp, Exception exception)
{
if (exception != null)
{
var exceptionString = exception.ToString();
if (exceptionString.Length > )
{
exceptionString = exceptionString.Substring(, );
}
errorLog.Error(new ErrorLog
{
OperatorId = userIp,
LOG_MESSAGE = exception.Message,
LOG_EXCEPTION = exceptionString
});
}
} /// <summary>
/// 将指定的<see cref="Exception"/>实例详细信息写入错误日志。
/// </summary>
/// <returns></returns>
public static void ErrorLog(Exception exception)
{
if (exception != null)
{
var exceptionString = exception.ToString();
if (exceptionString.Length > )
{
exceptionString = exception.ToString().Substring(, );
}
errorLog.Error(new ErrorLog
{
LOG_MESSAGE = exception.Message,
LOG_EXCEPTION = exceptionString
});
}
}
}

接下来,我们就是要写Filter了。新建一个ExceptionFilter类,继承于ExceptionFilterAttribute

     /// <summary>
/// 异常拦截器
/// </summary>
public class ExceptionFilter : ExceptionFilterAttribute
{
private HttpResponseMessage GetResponse(int code, string message)
{
var resultModel = new ApiModelsBase() { Code = code, Message = message }; return new HttpResponseMessage()
{
Content = new ObjectContent<ApiModelsBase>(
resultModel,
new JsonMediaTypeFormatter(),
"application/json"
)
};
} public override void OnException(HttpActionExecutedContext actionExecutedContext)
{
var code = -;
var message = "请求失败!"; if (actionExecutedContext.Exception is UserDisplayException)
{
message = actionExecutedContext.Exception.Message;
}
if (actionExecutedContext.Exception is UserLoginException)
{
code = -;
message = actionExecutedContext.Exception.Message;
} if (actionExecutedContext.Response == null)
{
actionExecutedContext.Response = GetResponse(code, message);
} //记录错误日志
LogUtils.ErrorLog(SecurityHelper.GetUserIp(), actionExecutedContext.Exception); base.OnException(actionExecutedContext);
}
}

注:

1.博主单独把登录异常通过特定code值返回,方便客户端分辨处理

2.GetResponse()方法主要是填充json数据到response

到这一步,还是没办法写日志的,为什么呢???因为我们的ExceptionFilter还没有注册,在App_Start文件夹下WebApiConfig.cs文件Register方法添加下句代码:

 config.Filters.Add(new ExceptionFilter());

OK,至此我们的错误日志记录就算搞定了。只需要在代码中抛出手动捕获的异常,或者意料之外未捕获的异常都会记录在错误日志中,并友好反馈到客户端。

当然,log4net的配置信息也是需要注册的,千万别忘了在Global.asax中Application_Start方法加上这样一句代码

log4net.Config.XmlConfigurator.Configure();

博主自知水平有限,如有不对的地方或各位有更好的解决方案,请随意指点,必当虚心请假,希望共同进步....