文章目录
- .Net日志组件之NLog的使用和配置
-
- 1、新建.Net8控制台项目
- 2、Nuget安装NLog组件
- 3、添加配置文件nlog.config
- [4、右键文件nlog.config,修改属性为"始终复制 or 较新则复制"](#4、右键文件nlog.config,修改属性为“始终复制 or 较新则复制”)
- 5、编写nlog.config配置文件内容
- 6、编写c#代码测试记录简单日志
- 7、编写c#代码测试记录实体日志
- 8、配置文件参考链接
.Net日志组件之NLog的使用和配置
1、新建.Net8控制台项目
2、Nuget安装NLog组件
install-package NLog.Extensions.Logging
3、添加配置文件nlog.config
4、右键文件nlog.config,修改属性为"始终复制 or 较新则复制"
5、编写nlog.config配置文件内容
xml
<?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">
<!--输出目标,往哪里输出-->
<targets>
<!--此部分中的所有目标将自动异步-->
<default-wrapper xsi:type="AsyncWrapper"></default-wrapper>
<!--type:日志输出类型 File:文件 ColoredConsole:控制台-->
<!--fileName:日志存储的路径及名称-->
<!--layout:日志输出格式-->
<!-- archiveFileName:要用于存档的文件的名称 可以指定日志 -->
<!-- archiveAboveSize:以字节为单位的大小,超过该大小的日志文件将被自动存档 -->
<!-- archiveNumbering:对文件档案进行编号的方式 -->
<!-- concurrentWrites:当使用keepFileOpen = true时,支持从同一机器主机上的多个进程优化并发写入同一日志文件。通过使用一种特殊的技术,它可以让文件从多个进程中打开。如果只有单个进程(和单个 AppDomain)应用程序正在记录日志,那么设置为concurrentWrites = False会更快。 -->
<!-- keepFileOpen:指示是否在每次记录事件时保持日志文件打开,将此属性更改为 true 将大大提高性能,但也会保持文件句柄锁定。启用此选项时,请考虑设置openFileCacheTimeout = 30,因为它将允许存档操作并对被删除的日志文件做出反应。 -->
<!--项目日志保存文件路径说明fileName="${basedir}/保存目录,以年月日的格式创建/${shortdate}/${记录器名称}-${单级记录}-${shortdate}.txt"-->
<target name="info_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/info_${shortdate}.txt"
layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring}"
archiveFileName="${basedir}/archives/info_${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false" />
<target name="error_file" xsi:type="File"
fileName="${basedir}/Logs/${shortdate}/error_${shortdate}.txt"
layout="${longdate} | ${event-properties:item=EventId_Id:whenEmpty=0} | ${uppercase:${level}} | ${logger} | ${message} ${exception:format=tostring}"
archiveFileName="${basedir}/archives/error_${shortdate}-{#####}.txt"
archiveAboveSize="102400"
archiveNumbering="Sequence"
concurrentWrites="true"
keepFileOpen="false" />
<target
xsi:type="ColoredConsole"
name="colorConsole"
encoding="Encoding"
detectConsoleAvailable="true"
detectOutputRedirected="false"
useDefaultRowHighlightingRules="false"
header="--------------------"
layout="${longdate}|${level:uppercase=true}|${logger}|${message}|${exception} ${newline} ${stacktrace} ${newline}"
footer="---------------------"
>
<highlight-row condition="level == LogLevel.Trace" foregroundColor="DarkGray"/>
<highlight-row condition="level == LogLevel.Debug" foregroundColor="DarkBlue"/>
<highlight-row condition="level == LogLevel.Info" foregroundColor="White"/>
<highlight-row condition="level == LogLevel.Warn" foregroundColor="DarkYellow"/>
<highlight-row condition="level == LogLevel.Error" foregroundColor="Red"/>
<highlight-row condition="level == LogLevel.Fatal" foregroundColor="DarkRed"/>
</target>
<!--使用可自定义的着色将日志消息写入控制台-->
<!-- <target name="console" xsi:type="ColoredConsole" layout="[${date:format=HH\:mm\:ss}]:${message} ${exception:format=message}" /> -->
</targets>
<!--规则配置,final - 最终规则匹配后不处理任何规则-->
<!--定义使用哪个target输出-->
<rules>
<!-- 优先级从高到低依次为:OFF、FATAL、ERROR、WARN、INFO、DEBUG、TRACE、 ALL -->
<!-- 将所有日志输出到文件 -->
<logger name="*" minlevel="Trace" maxlevel="Warn" writeTo="info_file" />
<logger name="*" minlevel="Error" writeTo="error_file" />
<!-- 将所有日志输出到控制台 -->
<logger name="*" minlevel="Debug" writeTo="colorConsole" />
</rules>
</nlog>
6、编写c#代码测试记录简单日志
csharp
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 测试记录日志
/// </summary>
public static void TestWriteLog()
{
//记录日志
_logger.Info("测试NLog写日志 - Info");
try
{
//转换
var a = Convert.ToInt32("测试NLog写日志 - Error");
}
catch (Exception e)
{
//记录日志
_logger.Error(e, "测试NLog写日志 - Error");
}
}
log
2024-09-19 14:25:52.0496 | 0 | INFO | TestNLogApp.TestNLogService | 测试NLog写日志 - Info
2024-09-19 14:35:45.2005 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"f387511d-5f9d-4173-be77-4e3d0d535002", "Name":"姓名 - 0", "Age":23, "Birthday":"12/20/2024", "Hobbys":[]}
2024-09-19 14:35:45.2311 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"1ae83538-3e8d-4113-8417-5d6715e2cfaf", "Name":"姓名 - 1", "Age":25, "Birthday":"12/17/2026", "Hobbys":[]}
2024-09-19 14:35:45.2501 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"55d545af-f9fc-4a3c-817e-6713f697e0f3", "Name":"姓名 - 2", "Age":22, "Birthday":"10/26/2028", "Hobbys":[]}
2024-09-19 14:35:45.2501 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"ea8d300d-caf9-4afb-a02f-a88f5a2ef946", "Name":"姓名 - 3", "Age":18, "Birthday":"03/12/2015", "Hobbys":["篮球,足球,羽毛球,麻将"]}
2024-09-19 14:35:45.2501 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"57b1bbf7-87b2-4847-b404-dac0b8ff66e9", "Name":"姓名 - 4", "Age":26, "Birthday":"04/01/2031", "Hobbys":[]}
2024-09-19 14:35:45.2501 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"e4fc8688-a6fd-48c4-be56-def34edfce9b", "Name":"姓名 - 5", "Age":33, "Birthday":"11/05/2019", "Hobbys":["篮球,足球,羽毛球,麻将"]}
2024-09-19 14:35:45.2501 | 0 | INFO | TestNLogApp.TestNLogService | New SystemUser at 2024-09-19 14:35:45,Detail is {"Id":"4db7bd7f-aef8-42df-a10d-a5bf822cbff2", "Name":"姓名 - 6", "Age":26, "Birthday":"05/02/2017", "Hobbys":[]}
log
2024-09-19 14:25:52.0526 | 0 | ERROR | TestNLogApp.TestNLogService | 测试NLog写日志 - Error System.FormatException: The input string '测试NLog写日志 - Error' was not in a correct format.
at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
at System.Convert.ToInt32(String value)
at TestNLogApp.TestNLogService.TestWriteLog() in D:\01.lingbug\04.code\15.testMiniAuth20240918\TestNLogApp\TestNLogService.cs:line 24
2024-09-19 14:56:30.6702 | 0 | ERROR | TestNLogApp.TestNLogService | 测试NLog写日志 - Error System.FormatException: The input string '测试NLog写日志 - Error' was not in a correct format.
at System.Number.ThrowFormatException[TChar](ReadOnlySpan`1 value)
at System.Convert.ToInt32(String value)
at TestNLogApp.TestNLogService.TestWriteLog() in D:\01.lingbug\04.code\15.testMiniAuth20240918\TestNLogApp\TestNLogService.cs:line 25
7、编写c#代码测试记录实体日志
csharp
public class SystemUser
{
public Guid Id { get; set; }
public string Name { get; set; }
public int Age { get; set; }
public DateOnly Birthday { get; set; }
public List<string> Hobbys { get; set; }
}
private static Logger _logger = LogManager.GetCurrentClassLogger();
/// <summary>
/// 测试记录日志 - 实体
/// </summary>
public static void TestWriteEntityLog()
{
for (int i = 0; i < 10; i++)
{
//初始化
var systemUser = new SystemUser();
//赋值
systemUser.Id = Guid.NewGuid();
systemUser.Name = $"姓名 - {i}";
systemUser.Age = Random.Shared.Next(18, 35);
systemUser.Birthday = DateOnly.FromDateTime(DateTime.Now.AddYears(Random.Shared.Next(-10, 10)).AddMonths(Random.Shared.Next(-10, 10)).AddDays(Random.Shared.Next(-30, 30)));
systemUser.Hobbys = new List<string>() { "篮球,足球,羽毛球,麻将" }.Skip(Random.Shared.Next(0, 2)).ToList();
//记录日志
_logger.Info("New SystemUser at {now},Detail is {@systemUser}", DateTime.Now, systemUser);
}
}