.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")还未成功
上一篇: .net core 控制台程序使用依赖注入(Autofac)
下一篇: 就你懂拼音
推荐阅读
-
详解ASP.NET Core应用中如何记录和查看日志
-
详解Asp.net Core 使用Redis存储Session
-
建议收藏:.net core 使用EPPlus导入导出Excel详细案例,精心整理源码已更新至开源模板
-
.NET Core 使用NPOI读取Excel返回泛型List集合
-
在ASP.NET Core中使用托管启动(hosting startup)程序集,实现批量注册service
-
asp.net core 3.0 中使用 swagger
-
.net core控制台程序中使用原生依赖注入
-
.net core 使用ViewComponent
-
.net core 使用Rotativa创建PDF文档
-
ASP.NET Core Kestrel 中使用 HTTPS (SSL)