首先使用Nugut安裝NLog, NLog.Extensions.Logging,using NLog.Web,而且加上配置文件 」nlog.config「,配置文件內容網上均可以百度的到。這是我本身的:git
建立表:github
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;sql
配置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">app
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>ide
<!--
-->
<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>ui
由於以前一直沒法將日誌寫入數據庫,因而百度了很久,將」throwExceptions「設置爲true,部署在生產環境建議改成false,這樣就能夠調試看到錯誤了,個人緣由是sql錯誤。debug
<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")還未成功