.Net Core 使用NLog记录日志到文件和数据库的操作方法
程序员文章站
2022-11-01 17:56:10
nlog 记录日志是微软官方推荐使用。接下来,通过配置日志记录到文件和sql server数据库。第一步:首先添加包nlog.config (可通过微软添加包命令install-package 包名进...
nlog 记录日志是微软官方推荐使用。
接下来,通过配置日志记录到文件和sql server数据库。
第一步:首先添加包nlog.config (可通过微软添加包命令install-package 包名进行添加,也可以通过管理nuget程序包进行添加),添加成功后会生成nlog.config配置文件。并对该配置文件进行配置。详细配置可参考git上 nlog说明。
一下是我个人配置。
<?xml version="1.0" encoding="utf-8" ?> <nlog xmlns="http://www.nlog-project.org/schemas/nlog.xsd" xmlns:xsi="http://www.w3.org/2001/xmlschema-instance" xsi:schemalocation="http://www.nlog-project.org/schemas/nlog.xsd nlog.xsd" autoreload="true" throwexceptions="false" internalloglevel="warn" internallogfile="logs/nlog-internal.log"> <!--internalloglevel="off"--> <!-- optional, add some variables https://github.com/nlog/nlog/wiki/configuration-file#variables --> <variable name="myvar" value="myvalue"/> <!-- see https://github.com/nlog/nlog/wiki/configuration-file for information on customizing logging rules and outputs. --> <targets> <!-- add your targets here see https://github.com/nlog/nlog/wiki/targets for possible targets. see https://github.com/nlog/nlog/wiki/layout-renderers for the possible layout renderers. --> <!-- write events to a file with the date in the filename. <target xsi:type="file" name="f" filename="${basedir}/logs/${shortdate}.log" layout="${longdate} ${uppercase:${level}} ${message}" /> --> <!-- write logs to file --> <target xsi:type="file" name="allfile" filename="logs/${date:format=yyyymm}/nlog-all-${shortdate}.log" layout="${longdate}|${event-properties:item=eventid.id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" /> <target xsi:type="file" name="ownfile-web" filename="logs/${date:format=yyyymm}/nlog-own-${shortdate}.log" layout="${longdate}|${event-properties:item=eventid.id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" /> <target xsi:type="null" name="blackhole" /> <target xsi:type="database" name="database"> <connectionstring>${var:connectionstring}</connectionstring> <commandtext> insert into syslogs (application,levels,operatingtime,operatingaddress,userid,logger,callsite,requesturl,referrerurl,action,message,exception) values (@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callsite,@requesturl,@referrerurl,@action,@message,@exception); </commandtext> <parameter name="@application" layout="webapi" /> <parameter name="@levels" layout="${level}" /> <parameter name="@operatingtime" layout="${date}" /> <parameter name="@operatingaddress" layout="${aspnet-request-ip}" /> <parameter name="@userid" layout="1" /> <parameter name="@logger" layout="${logger}" /> <parameter name="@callsite" layout="${callsite}" /> <parameter name="@requesturl" layout="${aspnet-request-url}" /> <parameter name="@referrerurl" layout="${aspnet-request}" /> <parameter name="@action" layout="${aspnet-mvc-action}" /> <parameter name="@message" layout="${message}" /> <parameter name="@exception" layout="${exception:tostring}" /> </target> </targets> <rules> <!-- add your logging rules here --> <!-- write all events with minimal level of debug (so debug, info, warn, error and fatal, but not trace) to "f" <logger name="*" minlevel="debug" writeto="f" /> --> <!--all logs, including from microsoft--> <!--minlevel 改为trace 跟踪全部 error 只捕获异常--> <logger name="*" minlevel="error" writeto="allfile" /> <!--skip microsoft logs and so log only own logs--> <logger name="microsoft.*" minlevel="trace" writeto="blackhole" final="true" /> <logger name="*" minlevel="trace" writeto="ownfile-web" /> <logger name="*" minlevel="trace" writeto="database" /> </rules> </nlog> <!--增加引用 <packagereference include="nlog.extensions.logging" version="1.2.1" /> <packagereference include="nlog.web.aspnetcore" version="4.6.0" />-->
说明:targets 中有一节点为database,是配置将日志写入数据库中,注意需要在数据库中添加该记录日志表。
{ "connectionstrings": { "defaultconnection": "data source=192.168.30.133;initial catalog=test;user id=sa;password=123456;trusted_connection=true;multipleactiveresultsets=true;integrated security=false;" }, "logging": { "loglevel": { "default": "warning" } }, "allowedhosts": "*" }
第二步:添加包nlog.web.aspnetcore,在program.cs中的webhost加入".usenlog()"(该属于程序集nlog.web,需要添加引用using nlog.web;),即为添加nlog.
using microsoft.aspnetcore; using microsoft.aspnetcore.hosting; using nlog.web; namespace webapi { public class program { public static void main(string[] args) { createwebhostbuilder(args).build().run(); } public static iwebhostbuilder createwebhostbuilder(string[] args) => webhost.createdefaultbuilder(args) .usestartup<startup>() .usenlog(); //加入nlog日志 } }
第三步:在startup.cs中的configure方法中添加记日志代码,即需要加载的配置文件和配置日志写入数据库连接字符串代码。注意:为避免中文乱码问题需要添加system.text.encoding.codepages包。
public void configure(iapplicationbuilder app, ihostingenvironment env) { #region nlog记日志 //将日志记录到数据库 config/nlog.config nlog.logmanager.loadconfiguration("nlog.config").getcurrentclasslogger(); nlog.logmanager.configuration.variables["connectionstring"] = configuration.getconnectionstring("defaultconnection"); encoding.registerprovider(codepagesencodingprovider.instance); //避免日志中的中文输出乱码 #endregion if (env.isdevelopment()) app.usedeveloperexceptionpage(); else app.usehsts(); app.usehttpsredirection(); app.usemvc(); }
第四步:使用微软推荐的方式在在构造方法中将将日志对象注入。
public class userscontroller : controller { /// <summary> /// 日志对象 /// </summary> private readonly ilogger logger; public userscontroller(iloggerfactory loggerfactory) { this.logger = loggerfactory.createlogger<userscontroller>(); #region 测试日志 logger.logtrace("开发阶段调试,可能包含敏感程序数据", 1); logger.logdebug("开发阶段短期内比较有用,对调试有益。"); logger.loginformation("你访问了首页。跟踪程序的一般流程。"); logger.logwarning("警告信息!因程序出现故障或其他不会导致程序停止的流程异常或意外事件。"); logger.logerror("错误信息。因某些故障停止工作"); logger.logcritical("程序或系统崩溃、遇到灾难性故障!!!"); #endregion }
所有工作完成,运行程序。在配置nlog路径下生成日志文件,同时,在数据库中生成日志。
到此这篇关于.net core 使用nlog记录日志到文件和数据库的文章就介绍到这了,更多相关.net core记录日志到文件和数据库内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!
上一篇: jQuery实现带展开动画的导航栏效果
下一篇: 祖传千斤顶