欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页  >  IT编程

.net core使用NLog记录

程序员文章站 2022-08-30 23:15:23
首先使用Nugut安装NLog, NLog.Extensions.Logging,using NLog.Web,并且加上配置文件 ”nlog.config“,配置文件内容网上都可以百度的到。这是我自己的: 创建表: CREATE TABLE `sys_log` ( `Id` int(11) NOT ......

 首先使用nugut安装nlog, nlog.extensions.logging,using nlog.web,并且加上配置文件 ”nlog.config“,配置文件内容网上都可以百度的到。这是我自己的:

创建表:

create table `sys_log` (
`id` int(11) not null auto_increment,
`account` varchar(20) character set utf8 collate utf8_general_ci null default null,
`actiontype` varchar(10) character set utf8 collate utf8_general_ci null default null,
`level` varchar(5) character set utf8 collate utf8_general_ci null default null,
`message` longtext character set utf8 collate utf8_general_ci null,
`date` datetime(0) null default null,
primary key (`id`) using btree,
unique index `id_unique`(`id`) using btree
) engine = innodb auto_increment = 11 character set = utf8 collate = utf8_general_ci row_format = compact;

  配置config文件

<?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="true"
internalloglevel="off" internallogfile="c:\temp\nlog-internal.log">

<!-- optional, add some variables
https://github.com/nlog/nlog/wiki/configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>

<!--
-->
<targets>
<target name="console" xsi:type ="console" />
<target name="debugger" xsi:type="debugger" layout="${date:format=hh\:mm\:ss.fff}: ${message}" />
<target name="error_file" xsi:type="file"
filename="${basedir}/logs/error/${shortdate}/error.txt" maxarchivefiles="30"
layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
<target name="info" xsi:type="file"
filename="${basedir}/logs/info/${shortdate}/info.txt" maxarchivefiles="30"
layout="${longdate} | ${level:uppercase=false} | ${message} ${onexception:${exception:format=tostring} ${newline} ${stacktrace} ${newline}" />
<target name="database" xsi:type="database">
<connectionstring>${var:connectionstrings}</connectionstring>
<commandtext>
insert into lifehome.sys_log (account,actiontype,level,message,date) values(@account,@actiontype,@level,@message,@date)
</commandtext>
<parameter name = "@account" layout = "${event-context:item=account}"/>
<parameter name = "@actiontype" layout = "${event-context:item=actiontype}"/>
<parameter name = "@level" layout = "${event-context:item=level}" />
<parameter name = "@message" layout = "${event-context:item=message}" />
<parameter name = "@date" layout = "${event-context:item=date}" />
<dbprovider>mysql.data.mysqlclient.mysqlconnection,mysql.data</dbprovider>
</target>
</targets>
<rules>
<logger name="*" writeto="console" />
<logger name="*" minlevel="debug" writeto="debugger" />
<logger name="*" minlevel="error" writeto="error_file" />
<logger name="*" level="info" writeto="info" />
<logger name="*" writeto="database" />
</rules>
</nlog>

 因为之前一直无法将日志写入数据库,于是百度了好久,将”throwexceptions“设置为true,部署在生产环境建议改为false,这样就可以调试看到错误了,我的原因是sql错误。

  <connectionstring>此处是为了灵活配置sql连接。

 之后在startup.cs里面加上如下代码:

public void configure(iapplicationbuilder app, ihostingenvironment env,iloggerfactory loggerfactory)
{

         //加载nlog
         loggerfactory.addnlog();

         //加载配置文件
         env.configurenlog("nlog.config");

         //读取数据库连接
         nlog.logmanager.configuration.variables["connectionstrings"]=_configuration.getconnectionstring("connection");

      );
   });
}

然后在program.cs里面写上

public static iwebhost buildwebhost(string[] args) =>
   webhost.createdefaultbuilder(args)
    .usestartup<startup>().usenlog()
.       build();

然后使用过滤器

  

/// <summary>
/// 全局异常过滤
/// </summary>
public class exceptionfilter : attribute,iexceptionfilter
{
     private readonly ilogger logger;
     public exceptionfilter()
     {
          logger = logmanager.getcurrentclasslogger();
      }
      public void onexception(exceptioncontext context)
      {

       //如果异常未处理
     if(context.exceptionhandled==false)
       {
          logeventinfo lei = new logeventinfo();
          lei.level = loglevel.error;
          lei.properties["account"] = "1";
          lei.properties["date"] =datetime.now;
          lei.properties["actiontype"] = "1";
          lei.properties["level"] = "1";
          lei.properties["message"] = "1";
          logger.log(lei);
          //异常已处理
         context.exceptionhandled = true;
    }
   }
}

 数据可以记录到数据库,但是使用简单写法如: logger.error("12344")还未成功