首先使用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")还未成功