webapi日志记录(TXT存储)
程序员文章站
2022-05-29 13:28:41
记录webapi日志我使用了两种办法,一种是存储TXT的log文档,但我发现使用使用了我接口的日志都会存储到我电脑上。后面改用数据库存储log。数据库存储log信息这种方法个人比较推荐。之前花费了一些时间来写TXT存储还是想记录下来。 转载自:https://blog.csdn.net/lordwi ......
记录webapi日志我使用了两种办法,一种是存储txt的log文档,但我发现使用使用了我接口的日志都会存储到我电脑上。后面改用数据库存储log。数据库存储log信息这种方法个人比较推荐。之前花费了一些时间来写txt存储还是想记录下来。
转载自:https://blog.csdn.net/lordwish/article/details/72353851
1、引用nlog类库
打开项目的nuget包管理器,搜索nlog,为项目添加程序包引用。
2、修改项目配置文件
在webapi项目的web.config中进行nlog的配置。首先在节点configuration>configsections下添加节点:
此处name必需为nlog,否则配置信息将不能被读取。 然后在configuration节点下添加节点nlog:
这里定义了日志文件的保存路径、命名格式以及日志记录类型和监听级别。
注意:<configsections>必须要紧跟在<configuration>下方
<configuration> <configsections> <section name="nlog" type="nlog.config.configsectionhandler,nlog" /> </configsections> <nlog xmlns:xsi="http://www.w3.org/2001/xmlschema"> <targets> <target name="logfile" xsi:type="file" filename="${basedir}/logfile/${date:format=yyyy/mm/dd}-api.txt"/> <target name="eventlog" xsi:type="eventlog" layout="${message}" log="application" source="api services"/> </targets> <rules> <logger name="*" minlevel="trace" writeto="logfile"/> <logger name="*" minlevel="trace" writeto="eventlog"/> </rules> </nlog> </configuration>
3、创建日志及跟踪类
创建日志跟踪类applog,继承于system.web.http.tracing下的跟踪编写器接口itracewriter,用于日志生成和写入:
using newtonsoft.json; using nlog; using system; using system.collections.generic; using system.linq; using system.net.http; using system.text; using system.web; using system.web.http.tracing; namespace insidemesapi.log { public sealed class applog : itracewriter { //日志写入 private static readonly logger applogger = logmanager.getcurrentclasslogger(); private static readonly lazy<dictionary<tracelevel, action<string>>> loggingmap = new lazy<dictionary<tracelevel, action<string>>>(() => new dictionary<tracelevel, action<string>> { {tracelevel.info,applogger.info }, {tracelevel.debug,applogger.debug }, {tracelevel.error,applogger.error }, {tracelevel.fatal,applogger.fatal }, {tracelevel.warn,applogger.warn } }); private dictionary<tracelevel, action<string>> logger { get { return loggingmap.value; } } /// <summary> /// 跟踪编写器接口实现 /// </summary> /// <param name="request"></param> /// <param name="category"></param> /// <param name="level"></param> /// <param name="traceaction"></param> public void trace(httprequestmessage request, string category, tracelevel level, action<tracerecord> traceaction) { if (level != tracelevel.off)//未禁用日志跟踪 { if (traceaction != null && traceaction.target != null) { category = category + environment.newline + "action parameters : " + jsonconvert.serializeobject(traceaction.target); } var record = new tracerecord(request, category, level); if (traceaction != null) { traceaction(record); } // traceaction?.invoke(record); log(record); } //throw new notimplementedexception(); } /// <summary> /// 日志写入 /// </summary> /// <param name="record"></param> private void log(tracerecord record) { var message = new stringbuilder(); /**************************运行日志****************************/ if (!string.isnullorwhitespace(record.message)) { message.append("").append(record.message + environment.newline); } if (record.request != null) { if (record.request.method != null) { message.append("method : " + record.request.method + environment.newline); } if (record.request.requesturi != null) { message.append("").append("url : " + record.request.requesturi + environment.newline); } if (record.request.headers != null && record.request.headers.contains("token") && record.request.headers.getvalues("token") != null && record.request.headers.getvalues("token").firstordefault() != null) { message.append("").append("token : " + record.request.headers.getvalues("token").firstordefault() + environment.newline); } } if (!string.isnullorwhitespace(record.category)) { message.append("").append(record.category); } //if (!string.isnullorwhitespace(record.operator)) //{ // message.append(" ").append(record.operator).append(" ").append(record.operation); //} //***************************异常日志***********************************// if (record.exception != null && !string.isnullorwhitespace(record.exception.getbaseexception().message)) { var exceptiontype = record.exception.gettype(); message.append(environment.newline); message.append("").append("error : " + record.exception.getbaseexception().message + environment.newline); } //日志写入本地文件 logger[record.level](convert.tostring(message) + environment.newline); } } }
创建日志筛选器类logfilterattribute,继承于system.web.http.filters下的筛选器特性基类,用于定义日志内容:
using system; using system.web.http; using system.web.http.controllers; using system.web.http.tracing; namespace insidemesapi.log { public class logfilterattribute : system.web.http.filters.actionfilterattribute { public override void onactionexecuting(httpactioncontext actioncontext) { globalconfiguration.configuration.services.replace(typeof(itracewriter), new applog()); var trace = globalconfiguration.configuration.services.gettracewriter(); //trace.info(actioncontext.request, "controller : " + actioncontext.controllercontext.controllerdescriptor.controllertype.fullname + environment.newline + "action : " + actioncontext.actiondescriptor.actionname, "json", actioncontext.actionarguments); //base.onactionexecuting(actioncontext); } } }
创建异常筛选器类abnormalfilterattribute,继承于system.web.http.filters下的异常筛选器类,用于异常信息的跟踪筛选:
using system; using system.componentmodel.dataannotations; using system.net; using system.net.http; using system.web.http; using system.web.http.filters; using system.web.http.tracing; namespace insidemesapi.log { public class abnormalfilterattribute : system.web.http.filters.exceptionfilterattribute { public override void onexception(httpactionexecutedcontext actionexecutedcontext) { globalconfiguration.configuration.services.replace(typeof(itracewriter), new applog()); var trace = globalconfiguration.configuration.services.gettracewriter(); trace.error(actionexecutedcontext.request, "controller : " + actionexecutedcontext.actioncontext.controllercontext.controllerdescriptor.controllertype.fullname + environment.newline + "action : " + actionexecutedcontext.actioncontext.actiondescriptor.actionname, actionexecutedcontext.exception); var exceptiontype = actionexecutedcontext.exception.gettype(); if (exceptiontype == typeof(validationexception)) { var resp = new httpresponsemessage(httpstatuscode.badrequest) { content = new stringcontent(actionexecutedcontext.exception.message), reasonphrase = "validationexception" }; throw new httpresponseexception(resp); } else if (exceptiontype == typeof(unauthorizedaccessexception)) { throw new httpresponseexception(actionexecutedcontext.request.createresponse(httpstatuscode.unauthorized)); } else { throw new httpresponseexception(actionexecutedcontext.request.createresponse(httpstatuscode.internalservererror)); } //base.onexception(actionexecutedcontext); } } }
4、应用配置
public static class webapiconfig { public static void register(httpconfiguration config) { 日志配置 config.filters.add(new log.logfilterattribute()); config.filters.add(new log.abnormalfilterattribute()); } }