.net core使用NLog记录
首先使用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")还未成功
上一篇: 揭秘一个撸羊毛打卡赚钱“骗局”
下一篇: 贫穷不可怕,可怕的是人生毁在这两个字上
推荐阅读
-
ASP.NET Core部署前期准备 使用Hyper-V安装Ubuntu Server 16.10
-
使用 xUnit 编写 ASP.NET Core WebAPI单元测试
-
Asp.net core WebApi 使用Swagger生成帮助页实例
-
.net core使用redis基于StackExchange.Redis
-
ASP.NET core Web中使用appsettings.json配置文件的方法
-
使用.Net Core + Vue + IdentityServer4 + Ocelot 实现一个简单的DEMO +源码
-
.Net Core 下使用ZKWeb.System.Drawing实现验证码功能(图形验证码)
-
详解在ASP.NET Core 中使用Cookie中间件
-
在.NET Core中使用异步编程的方法步骤
-
详解.NET Core使用Quartz执行调度任务进阶