NLog 記錄日誌是微軟官方推薦使用。
接下來,通過配置日誌記錄到文件和Sql Server數據庫。
第一步:首先添加包NLog.Config (可通過微軟添加包命令Install-Package 包名進行添加,也可以通過管理NuGet程序包進行添加),添加成功後會生成NLog.config配置文件。並對該配置文件進行配置。詳細配置可參考Git上 NLog說明。
以下是我個人配置:
<?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="false"
internalLogLevel="Warn"
internalLogFile="Logs/nlog-internal.log">
<!--internalLogLevel="Off"-->
<!-- optional, add some variables
https://github.com/nlog/NLog/wiki/Configuration-file#variables
-->
<variable name="myvar" value="myvalue"/>
<!--
See https://github.com/nlog/nlog/wiki/Configuration-file
for information on customizing logging rules and outputs.
-->
<targets>
<!--
add your targets here
See https://github.com/nlog/NLog/wiki/Targets for possible targets.
See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
-->
<!--
Write events to a file with the date in the filename.
<target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
layout="${longdate} ${uppercase:${level}} ${message}" />
-->
<!-- write logs to file -->
<target xsi:type="File" name="allfile" fileName="Logs/${date:format=yyyyMM}/nlog-all-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" />
<target xsi:type="File" name="ownFile-web" fileName="Logs/${date:format=yyyyMM}/nlog-own-${shortdate}.log"
layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
<target xsi:type="Null" name="blackhole" />
<target xsi:type="Database" name="database">
<connectionString>${var:connectionString}</connectionString>
<commandText>
insert into syslogs (Application,Levels,Operatingtime,Operatingaddress,Userid,Logger,Callsite,Requesturl,Referrerurl,Action,Message,Exception)
values (@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callSite,@requesturl,@referrerurl,@action,@message,@exception);
</commandText>
<parameter name="@application" layout="WebApi" />
<parameter name="@levels" layout="${level}" />
<parameter name="@operatingTime" layout="${date}" />
<parameter name="@operatingaddress" layout="${aspnet-Request-IP}" />
<parameter name="@userid" layout="1" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite}" />
<parameter name="@requesturl" layout="${aspnet-request-url}" />
<parameter name="@referrerurl" layout="${aspnet-request}" />
<parameter name="@action" layout="${aspnet-mvc-action}" />
<parameter name="@message" layout="${message}" />
<parameter name="@exception" layout="${exception:tostring}" />
</target>
</targets>
<rules>
<!-- add your logging rules here -->
<!--
Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
<logger name="*" minlevel="Debug" writeTo="f" />
-->
<!--All logs, including from Microsoft-->
<!--minlevel 改爲Trace 跟蹤全部 Error 只捕獲異常-->
<logger name="*" minlevel="Error" writeTo="allfile" />
<!--Skip Microsoft logs and so log only own logs-->
<logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
<logger name="*" minlevel="Trace" writeTo="ownFile-web" />
<logger name="*" minlevel="Trace" writeTo="database" />
</rules>
</nlog>
<!--增加引用
<PackageReference Include="NLog.Extensions.Logging" Version="1.2.1" />
<PackageReference Include="NLog.Web.AspNetCore" Version="4.6.0" />-->
NLog.config
說明:targets 中有一節點爲Database,是配置將日誌寫入數據庫中,注意需要在數據庫中添加該記錄日誌表。
{
"ConnectionStrings": {
"DefaultConnection": "Data Source=192.168.30.133;Initial Catalog=Test;User ID=sa;Password=123456;Trusted_Connection=True;MultipleActiveResultSets=true;Integrated Security=false;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
appsettings.json
第二步:添加包NLog.Web.AspNetCore,在Program.cs中的WebHost加入".UseNLog()"(該屬於程序集NLog.Web,需要添加引用using NLog.Web;),即爲添加nlog.
using Microsoft.AspNetCore;
using Microsoft.AspNetCore.Hosting;
using NLog.Web;
namespace WebApi
{
public class Program
{
public static void Main(string[] args)
{
CreateWebHostBuilder(args).Build().Run();
}
public static IWebHostBuilder CreateWebHostBuilder(string[] args) =>
WebHost.CreateDefaultBuilder(args)
.UseStartup<Startup>()
.UseNLog(); //加入nlog日誌
}
}
Program.cs
第三步:在Startup.cs中的Configure方法中添加記日誌代碼,即需要加載的配置文件和配置日誌寫入數據庫連接字符串代碼。注意:爲避免中文亂碼問題需要添加System.Text.Encoding.CodePages包。
public void Configure(IApplicationBuilder app, IHostingEnvironment env)
{
#region Nlog記日誌
//將日誌記錄到數據庫 config/NLog.config
NLog.LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日誌中的中文輸出亂碼
#endregion
if (env.IsDevelopment())
app.UseDeveloperExceptionPage();
else
app.UseHsts();
app.UseHttpsRedirection();
app.UseMvc();
}
Configure方法
第四步:使用微軟推薦的方式在在構造方法中將將日誌對象注入。
public class UsersController : Controller
{
/// <summary>
/// 日誌對象
/// </summary>
private readonly ILogger logger;
public UsersController(ILoggerFactory loggerFactory)
{
this.logger = loggerFactory.CreateLogger<UsersController>();
#region 測試日誌
logger.LogTrace("開發階段調試,可能包含敏感程序數據", 1);
logger.LogDebug("開發階段短期內比較有用,對調試有益。");
logger.LogInformation("你訪問了首頁。跟蹤程序的一般流程。");
logger.LogWarning("警告信息!因程序出現故障或其他不會導致程序停止的流程異常或意外事件。");
logger.LogError("錯誤信息。因某些故障停止工作");
logger.LogCritical("程序或系統崩潰、遇到災難性故障!!!");
#endregion
}
構造方法中注入
所有工作完成,運行程序。在配置NLog路徑下生成日誌文件,同時,在數據庫中生成日誌。
MySql的問題:
#1樓 2019-04-30 14:35 3369
你好,我這邊使用Pomelo.EntityFrameworkCore.MySql連接mysql,dbProvider="Pomelo.EntityFrameworkCore.MySql",可以向文件中寫入日誌,但是無法向數據庫中寫入日誌
支持(0) 反對(0)
修改 刪除#2樓 2019-12-10 18:03 佔位符,😐!
@ 3369
還得安裝下:MySql.Data
這個還是:dbProvider="MySql.Data.MySqlClient.MySqlConnection, MySql.Data",
不知道有沒有更好的方法