.net 控制台 Nlog的使用

nuget引入NLog组件

 

 NLog.config 记得改为始终复制

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
<?xml version="1.0" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
      xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
      autoReload="true"
      throwExceptions="false"
      internalLogLevel="Trace">
 
    <variable name="fileFormat"
         value="
            ${newline}date: ${date}
            ${newline}level: ${level}
            ${newline}logger: ${logger}
            ${newline}machinename: ${machinename}
            ${newline}message: ${message}
            ${newline}------------------------------------------------------------" />
    <targets>
 
    <target name="logfile"
    xsi:type="File"
    maxArchiveFiles="1"
    layout="${fileFormat}"
    archiveAboveSize="102400000"
    fileName="${basedir}/Logs/${date:format=yyyy-MM}/${shortdate}.log" />
 
    </targets>
    <!--写入到文件-->
    <rules>
        <logger name="*" minlevel="Debug" writeTo="logfile" />
    </rules>
</nlog>

  NLogHelper

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
 
namespace ConsoleApp
{
    public class NLogHelper
    {
        private static NLog.Logger _logger = NLog.LogManager.GetCurrentClassLogger();
 
        private NLogHelper() { }
 
        public static void Trace(string strMsg)
        {
            _logger.Trace(strMsg);
        }
 
        public static void Debug(string strMsg)
        {
            _logger.Debug(strMsg);
        }
 
        public static void Info(string strMsg)
        {
            _logger.Info(strMsg);
        }
 
        public static void Warn(string strMsg)
        {
            _logger.Warn(strMsg);
        }
 
        public static void Error(string strMsg)
        {
            _logger.Error(strMsg);
        }
 
        public static void Fatal(string strMsg)
        {
            _logger.Fatal(strMsg);
        }
 
    }
}

  使用方法

1
2
3
4
5
6
7
8
for (int i = 0; i < 100; i++)
{
    var date = DateTime.Now;
    NLogHelper.Warn("LogTest:" + date.ToString());
    NLogHelper.Info("LogTest:" + date.ToString());
    NLogHelper.Error("LogTest:" + date.ToString());
    NLogHelper.Debug("LogTest:" + date.ToString());
}

  输出效果

 

 Nlog和Log4net相比,配置更少更简便,输出内容格式更清晰,使用方便。

posted @   互联网CV工程师  阅读(197)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· 阿里巴巴 QwQ-32B真的超越了 DeepSeek R-1吗?
· 如何调用 DeepSeek 的自然语言处理 API 接口并集成到在线客服系统
· 【译】Visual Studio 中新的强大生产力特性
· 2025年我用 Compose 写了一个 Todo App
点击右上角即可分享
微信分享提示