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