.NET_NLog

步骤

1. 添加依赖

①Microsoft.Extensions.DependencyInjection

②NLog.Extensions.Logging(或Microsoft.Extensions.Logging.___)

Tutorial · NLog/NLog Wiki · GitHub

2.添加nlog.config文件(默认名称, 可改为其他名称, 但需要另行配置)

文件的基础格式可从此处获取: Tutorial · NLog/NLog Wiki · GitHubNLog - Advanced and Structured Logging for Various .NET Platforms - Tutorial · NLog/NLog Wikihttps://github.com/NLog/NLog/wiki/Tutorial#configure-nlog-targets-for-output格式参考(关于config文件的说明在注释部分):

XML 复制代码
<?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="logs/console-example-internal.log"
      internalLogLevel="Info" >

	<!-- the targets to write to -->
	<targets>
		<!-- write logs to file -->
		<!-- archiveAboveSize: 日志文件的最大体积(字节数)|maxArchiveFiles: 日志文件的最大数量|maxArchiveDays: 日志文件的最大天数 -->
		<target xsi:type="File" name="logfile" fileName="logs/console-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><!-- 从上至下依次匹配 -->
		<!-- name: 匹配规则(类名)|minlevel: 最小日志输出等级|maxlevel: 最大日志输出等级|writeTo: 日志输出文件|final=true: 若匹配成功则不再向下匹配 -->
		<logger name="*" minlevel="Trace" writeTo="logfile,logconsole"/>
	</rules>
</nlog>

3.将nlog.config文件设置为"始终复制"或在项目设置页中将"Never"改为"Always"

示例

Program.cs

cs 复制代码
internal class Program
{
    static void Main(string[] args)
    {
        ServiceCollection services = new();

        services.AddLogging(logBuilder=> {
            //logBuilder.AddConsole();                    // Microsoft.Extensions.Logging
            //logBuilder.SetMinimumLevel(LogLevel.Debug); // Microsoft.Extensions.Logging
            logBuilder.AddNLog();
        });
        services.AddScoped<Example_1>();

        using ServiceProvider serviceProvider = services.BuildServiceProvider();
        Example_1 example_1 = serviceProvider.GetRequiredService<Example_1>();
        example_1.Start();
    }
}

Example_1.cs

cs 复制代码
internal class Example_1
{
    ILogger<Example_1> logger;
    public Example_1(ILogger<Example_1> logger)
    {
        this.logger = logger;
    }

    public void Start()
    {
        logger.LogDebug("运行中...");
        try
        {
            File.ReadAllText("A:\\text.txt");
            logger.LogDebug("文件读取成功");
        }
        catch (Exception e)
        {
            logger.LogError(e, "发生错误");
        }
        logger.LogDebug("结束");
    }
}

运行效果

相关推荐
吃汤圆的抹香鲸2 小时前
Rider 安装包 绿色版 Win/Mac/Linux 适合.NET和游戏开发者使用 2025全栈开发终极指南:从零配置到企业级实战
linux·运维·windows·sql·游戏·macos·.net
学海无涯,行者无疆11 小时前
使用Jenkins实现Windows服务器下C#应用程序发布
windows·c#·jenkins·.net·cicd·自动发布·一键发布
喵叔哟15 小时前
7. 【.NET 8 实战--孢子记账--从单体到微服务--转向微服务】--微服务基础工具与技术--Ocelot 网关--路由
微服务·架构·.net
玩c#的小杜同学16 小时前
从“Switch-case“到“智能模式“:C#模式匹配的终极进化指南
开发语言·前端·c#·.net
MicrosoftReactor19 小时前
技术速递|.NET 9 网络优化
网络·.net
瓜皮弟子头很铁20 小时前
.net websocket 使用
网络·websocket·网络协议·.net
今晚打老虎z1 天前
MailKit: 在 .NET 中实现高效电子邮件发送与接收
git·github·.net
今晚打老虎z2 天前
SSH.NET: .NET 平台上的安全 Shell 库
安全·ssh·.net
今晚打老虎z2 天前
FFMpegCore:.NET 中进行音视频处理解决方案
.net·音视频
今晚打老虎z2 天前
FFmpeg.NET:.NET 平台上的音视频处理利器
.net