.Net Core 使用NLog记录日志到文件和数据库
时间:2021-07-01 10:21:17
帮助过:12人阅读
<?xml version="1.0" encoding="utf-8" ?>
2 <nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
3 xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
4 xsi:schemaLocation="http://www.nlog-project.org/schemas/NLog.xsd NLog.xsd"
5 autoReload="true"
6 throwExceptions="false"
7 internalLogLevel="Warn"
8 internalLogFile="Logs/nlog-internal.log">
9
10 <!--internalLogLevel="Off"-->
11 <!-- optional, add some variables
12 https://github.com/nlog/NLog/wiki/Configuration-file#variables
13 -->
14 <variable name="myvar" value="myvalue"/>
15
16 <!--
17 See https://github.com/nlog/nlog/wiki/Configuration-file
18 for information on customizing logging rules and outputs.
19 -->
20 <targets>
21
22 <!--
23 add your targets here
24 See https://github.com/nlog/NLog/wiki/Targets for possible targets.
25 See https://github.com/nlog/NLog/wiki/Layout-Renderers for the possible layout renderers.
26 -->
27
28 <!--
29 Write events to a file with the date in the filename.
30 <target xsi:type="File" name="f" fileName="${basedir}/logs/${shortdate}.log"
31 layout="${longdate} ${uppercase:${level}} ${message}" />
32 -->
33
34 <!-- write logs to file -->
35 <target xsi:type="File" name="allfile" fileName="Logs/${date:format=yyyyMM}/nlog-all-${shortdate}.log"
36 layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline}" />
37
38 <target xsi:type="File" name="ownFile-web" fileName="Logs/${date:format=yyyyMM}/nlog-own-${shortdate}.log"
39 layout="${longdate}|${event-properties:item=EventId.Id}|${uppercase:${level}}|${logger} ${newline}${message} ${exception} ${newline} --- |url: ${aspnet-request-url}|action: ${aspnet-mvc-action}" />
40
41 <target xsi:type="Null" name="blackhole" />
42
43 <target xsi:type="Database" name="database">
44 <connectionString>${var:connectionString}
</connectionString>
45 <commandText>
46 insert into syslogs (Application,Levels,Operatingtime,Operatingaddress,Userid,Logger,Callsite,Requesturl,Referrerurl,Action,Message,Exception)
47 values (@application,@levels,@operatingtime,@operatingaddress,@userid,@logger,@callSite,@requesturl,@referrerurl,@action,@message,@exception);
48 </commandText>
49 <parameter name="@application" layout="WebApi" />
50 <parameter name="@levels" layout="${level}" />
51 <parameter name="@operatingTime" layout="${date}" />
52 <parameter name="@operatingaddress" layout="${aspnet-Request-IP}" />
53 <parameter name="@userid" layout="1" />
54 <parameter name="@logger" layout="${logger}" />
55 <parameter name="@callSite" layout="${callsite}" />
56 <parameter name="@requesturl" layout="${aspnet-request-url}" />
57 <parameter name="@referrerurl" layout="${aspnet-request}" />
58 <parameter name="@action" layout="${aspnet-mvc-action}" />
59 <parameter name="@message" layout="${message}" />
60 <parameter name="@exception" layout="${exception:tostring}" />
61 </target>
62
63 </targets>
64
65 <rules>
66 <!-- add your logging rules here -->
67
68 <!--
69 Write all events with minimal level of Debug (So Debug, Info, Warn, Error and Fatal, but not Trace) to "f"
70 <logger name="*" minlevel="Debug" writeTo="f" />
71 -->
72
73 <!--All logs, including from Microsoft-->
74 <!--minlevel 改为Trace 跟踪全部 Error 只捕获异常-->
75 <logger name="*" minlevel="Error" writeTo="allfile" />
76
77 <!--Skip Microsoft logs and so log only own logs-->
78 <logger name="Microsoft.*" minlevel="Trace" writeTo="blackhole" final="true" />
79 <logger name="*" minlevel="Trace" writeTo="ownFile-web" />
80 <logger name="*" minlevel="Trace" writeTo="database" />
81
82 </rules>
83 </nlog>
84
85
86 <!--增加引用
87 <PackageReference Include="NLog.Extensions.Logging" Version="1.2.1" />
88 <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方法中添加记日志代码,即需要加载的配置文件和配置日志写入数据库连接字符串代码。
1 public void Configure(IApplicationBuilder app, IHostingEnvironment env)
2 {
3
4 #region Nlog记日志
5 //将日志记录到数据库 config/NLog.config
6 NLog.LogManager.LoadConfiguration("nlog.config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("DefaultConnection"); Encoding.RegisterProvider(CodePagesEncodingProvider.Instance); //避免日志中的中文输出乱码
7 #endregion
8
9 if (env.IsDevelopment())
10 app.UseDeveloperExceptionPage();
11 else
12 app.UseHsts();
13 app.UseHttpsRedirection();
14
15 app.UseMvc();
16 }
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路径下生成日志文件,同时,在数据库中生成日志。
.Net Core 使用NLog记录日志到文件和数据库
标签:created ack render inf tab hub 出现 tor 错误信息