.Net Core 使用Nlog 记录日志
一、使用Nlog将日志记录到TXT文本中
参考:https://www.cnblogs.com/qmhuang/p/8305915.html
-
1、安装两个Nugget包:
Nlog安装后的效果NLog
和NLog.Web.AspNetCore
如下图:
-
2、新建Nlog配置文件
Nlog.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" autoReload="true" internalLogLevel="Warn" internalLogFile="internal-nlog.txt"> <!--define various log targets--> <targets> <!--write logs to file--> <target xsi:type="File" name="allfile" fileName="logs/all/nlog-all-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="File" name="ownFile-web" fileName="logs/my/nlog-my-${shortdate}.log" layout="${longdate}|${logger}|${uppercase:${level}}|${message} ${exception}" /> <target xsi:type="Null" name="blackhole" /> </targets> <rules> <!--All logs, including from Microsoft--> <logger name="*" minlevel="Trace" 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" /> </rules> </nlog>
-
3、修改Startup,注入Nlog和引入
Nlog.Config
// This method gets called by the runtime. Use this method to configure the HTTP request pipeline. public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory) { //使用NLog作为日志记录工具 loggerFactory.AddNLog(); //引入Nlog配置文件 env.ConfigureNLog("nlog.config"); if (env.IsDevelopment()) { app.UseDeveloperExceptionPage(); } else { app.UseHsts(); } app.UseHttpsRedirection(); app.UseMvc(); }
-
效果如下图:
新增高亮部分的代码 -
4、在接口中依赖Nlog,记录日志
private ILogger<ValuesController> logger; //依赖Nlog public ValuesController(ILogger<ValuesController> _logger) { logger = _logger; } // GET api/values [HttpGet] public ActionResult<IEnumerable<string>> Get() { logger.LogError("自定义记录日志");//使用Nlog记录 return new string[] { "value1", "value2" }; }
二、使用Nlog将日志记录到sql server数据库
-
1、安装Nugget包:
图片.pngNLog.Web.AspNetCore
效果如下:
-
2、新建Nlog配置文件
Nlog.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="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="error">
<connectionString>${var:connectionString}</connectionString>
<commandText>
INSERT INTO [dbo].[Error]
([Application]
,[Level]
,[Logger]
,[Callsite]
,[RequestHeaders]
,[RequestBody]
,[RequestURL]
,[Response]
,[Referrerurl]
,[Action]
,[Message]
,[Exception]
,[Operatingtime]
,[ServerAddress]
,[RemoteAddress])
VALUES
(@application
,@levels
,@logger
,@callSite
,@requestHeaders
,@requestBody
,@requestURL
,@response
,@referrerurl
,@action
,@message
,@exception
,@operatingtime
,@serverAddress
,@remoteAddress);
</commandText>
<parameter name="@application" layout="BackendAPI" />
<parameter name="@levels" layout="${level}" />
<parameter name="@logger" layout="${logger}" />
<parameter name="@callSite" layout="${callsite}" />
<parameter name="@requestHeaders" layout="Null" />
<parameter name="@requestBody" layout="${event-context:item=requestBody}" />
<parameter name="@requesturl" layout="${aspnet-request-url}" />
<parameter name="@response" layout="${event-context:item=response}" />
<parameter name="@referrerurl" layout="${aspnet-request}" />
<parameter name="@action" layout="${aspnet-mvc-action}" />
<parameter name="@message" layout="${event-context:item=message}" />
<parameter name="@exception" layout="${event-context:item=exception}" />
<!--<parameter name="@exception" layout="${exception:tostring}" />-->
<parameter name="@operatingTime" layout="${date}" />
<parameter name="@serverAddress" layout="${machinename}" />
<parameter name="@remoteAddress" layout="${aspnet-Request-IP}" />
</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="Error" writeTo="error" />
</rules>
</nlog>
-
3、全局配置Nlog
-
在
Startup
文件中添加配置NLog.LogManager.LoadConfiguration("Nlog.Config").GetCurrentClassLogger(); NLog.LogManager.Configuration.Variables["connectionString"] = Configuration.GetConnectionString("Test");
-
在
Program
文件中使用Nlog.UseNLog();
全部配置如下图:
全局配置Nlog
appsettings.json
文件内容如下:
{
"ConnectionStrings": {
"Test": "Server=.; Initial Catalog=TestDB; Persist Security Info=True; User ID=**; Password=***;"
},
"Logging": {
"LogLevel": {
"Default": "Warning"
}
},
"AllowedHosts": "*"
}
- 4、使用方法
方法一:
private readonly Logger _logger = LogManager.GetCurrentClassLogger();
var logEventInfo = new LogEventInfo() { };
logEventInfo.Properties["requestBody"] = "requestBody";
logEventInfo.Properties["exception"] = "exception";
logEventInfo.Properties["message"] = "context.Exception.Message";
logEventInfo.Properties["response"] = "response.ToJSON()";
_logger.Log(LogLevel.Error, logEventInfo);
方法二:
NLog.Logger logger = LogManager.GetCurrentClassLogger();
var logEventInfo = new LogEventInfo() { };
logEventInfo.Properties["requestBody"] = "requestBody";
logEventInfo.Properties["exception"] = "exception";
logEventInfo.Properties["message"] = "context.Exception.Message";
logEventInfo.Properties["response"] = "response.ToJSON()";
//_logger.Log(LogLevel.Error, logEventInfo);
logger.Log(LogLevel.Error, logEventInfo);
三、其他
- 网络参考资料
1、Nlog 在.net core中 记录请求上下文的标识符 - 官方参考资料
https://github.com/nlog/NLog/wiki/Layout%20Renderers
https://github.com/nlog/NLog/wiki/Targets
https://github.com/NLog/NLog/releases/
http://nlog-project.org/
LogCritical,用来记录严重的事情
LogDebug,记录调试信息
LogError,记录异常
LogInformation,记录信息性的事情
LogTrace,记录追踪信息
LogWarning,记录警告信息
下面是ASP.NET Core里面定义的LogLevel(它是个枚举), 按严重性从低到高排序的:
Trace = 0, 它可以包含敏感拘束, 默认在生产环境中它是被禁用掉的.
Debug = 1, 也是在调试使用, 应该在生产环境中禁用, 但是遇到问题需要调试可以临时启用.
Information = 2, 用来追踪应用程序的总体流程.
Warning = 3, 通常用于记录非正常或意外的事件, 也可以包括不会导致应用程序停止的错误和其他事件, 例如验证错误等.
Error = 4, 用于记录无法处理的错误和异常, 这些信息意味着当前的活动或操作发生了错误, 但不是应用程序级别的错误.
Critical = 5, 用于记录需要立即处理的事件, 例如数据丢失或磁盘空间不足.
None = 6, 如果你不想输出日志, 你可以把程序的最低日志级别设置为None, 此外还可以用来过滤日志.