最近想了解下面向对象开发,选择C# 语言 以及NET6.0
日志是开发中最常用的功能,本文记录下其中日志使用方法,理解不全的地方后续再学习补充
环境
- Ubuntu 22.04.2 LTS
- dotnet 6.0.411
准备工作
# https://learn.microsoft.com/zh-cn/dotnet/core/tools/dotnet-new-sdk-templates#web-others
# 使用worker模板创建一个项目,
# 项目能快速生成一个后台服务模板
dotnet new worker --use-program-main
# 安装NLog针对MicrosoftExtensions扩展
dotnet add package NLog.Extensions.Logging
## 添加日志功能
1. 根目录添加一个nlog.conf
<?xml version="1.0" encoding="utf-8" ?>
<!-- XSD manual extracted from package NLog.Schema: https://www.nuget.org/packages/NLog.Schema-->
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd" xsi:schemaLocation="NLog NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
autoReload="true"
internalLogFile="example.log"
internalLogLevel="Info" >
<!-- example.log文件名可以修改 -->
<!-- the targets to write to -->
<targets>
<!-- 同时写入文件和控制台 -->
<target xsi:type="File" name="logfile" fileName="example.log"
layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
<target xsi:type="Console" name="logconsole"
layout="${longdate}|${level}|${message} |${all-event-properties} ${exception:format=tostring}" />
</targets>
<!-- rules to map from logger name to target -->
<rules>
<!-- 可修改最低日志等级 -->
<logger name="*" minlevel="Trace" writeTo="logfile,logconsole" />
</rules>
</nlog>
2. 注册服务
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
# 只用加以下一段
services.AddLogging((builder) =>
{
builder.ClearProviders();
builder.AddNLog();
});
# 只用加以下一段结束
})
.Build();
3. 使用
模板中的wroker已自动注入进去,不需要修改
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
# 直接使用logger
# _logger.LogInformation()
# _logger.........
}
}
完整修改如下
Program.cs
namespace dotnet_demo;
using NLog.Extensions.Logging;
public class Program
{
public static void Main(string[] args)
{
IHost host = Host.CreateDefaultBuilder(args)
.ConfigureServices(services =>
{
services.AddHostedService<Worker>();
services.AddLogging((builder) =>
{
builder.ClearProviders();
builder.AddNLog();
});
})
.Build();
host.Run();
}
}
Worker.cs
namespace dotnet_demo;
public class Worker : BackgroundService
{
private readonly ILogger<Worker> _logger;
public Worker(ILogger<Worker> logger)
{
_logger = logger;
}
protected override async Task ExecuteAsync(CancellationToken stoppingToken)
{
while (!stoppingToken.IsCancellationRequested)
{
_logger.LogInformation("正在执行任务,时间是: {time}", DateTimeOffset.Now);
await Task.Delay(1000, stoppingToken);
}
}
}
效果
文章来源:https://www.toymoban.com/news/detail-507262.html
TODO
.NET Framework
,ASP.NET Core
,.NET Core Console
中使用方法参考文档
https://github.com/NLog/NLog文章来源地址https://www.toymoban.com/news/detail-507262.html
- 修改配置日志文件自动归档
到了这里,关于.NET Microsoft.Extensions.Logging + NLog 记录日志到文件的文章就介绍完了。如果您还想了解更多内容,请在右上角搜索TOY模板网以前的文章或继续浏览下面的相关文章,希望大家以后多多支持TOY模板网!