WPF下使用NLog

1 线从nuget中现在Nlog,由于我使用的是.net core 3.0 所以下载如图的Nlog

2 创建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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
<?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">
 <!--<variable name="LogDir" value="LogDir"/>-->
  <targets>

    <!-- Log in a separate thread, possibly queueing up to
        5000 messages. When the queue overflows, discard any
        extra messages-->

    <!-- write logs to file -->
    <target name="file" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
      <target xsi:type="File" fileName="${basedir}/logs/${shortdate}/${Other}/${shortdate}.log"
              layout="${longdate} ${level:uppercase=true} ${event-context:item=Action} ${message} ${event-context:item=Amount} ${stacktrace}" />
    </target>

    <!-- write log message to database -->
    <target name="db" xsi:type="AsyncWrapper" queueLimit="5000" overflowAction="Discard">
      <target type="Database" dbProvider="mssql"
              connectionString="Data Source=.\SQLEXPRESS;Initial Catalog=EFinance;Persist Security Info=True;User ID=sa;Password=123456;">
        <commandText>
          INSERT INTO Log(Timestamp,Level,Message,Action,Amount,StackTrace) VALUES(@time_stamp, @level, @message, @action, @amount, @stacktrace);
        </commandText>

        <!-- database connection parameters -->
        <parameter name="@time_stamp" layout="${date}" />
        <parameter name="@level" layout="${level:uppercase=true}" />
        <parameter name="@message" layout="${message}" />
        <parameter name="@action" layout="${event-context:item=Action}" />
        <parameter name="@amount" layout="${event-context:item=Amount}" />
        <parameter name="@stacktrace" layout="${stacktrace}" />
      </target>
    </target>

    <!--write log message to Visual Studio Output-->
    <target name="debugger" xsi:type="Debugger" layout="NLog: ${date:format=HH\:mm\:ss} | ${level:uppercase=true:padding=-5} | ${message}" />
    <!--    -->

    <target xsi:type="File"  name="ESDLog"
    fileName="${basedir}/logs/${shortdate}/${var:LogDir}/${date:format=yyyy-MM-dd HH}.log"
    layout ="${longdate} ${message}"/>
   
  </targets>

  <rules>
    <!--TRACE,DEBUG,INFO,WARN,ERROR,FATAL-->
    <!--<logger name="*" minlevel="Trace" writeTo="debugger" />
    --><!--INFO,WARN,ERROR,FATAL--><!--
    <logger name="*" minlevel="Info" writeTo="db" />
    --><!--DEBUG,INFO,WARN,ERROR,FATAL--><!--
    <logger name="*" minlevel="Debug" writeTo="file" />-->
 
    <logger name="ESDLog" minlevel="Info" writeTo="ESDLog"></logger>
  </rules>
</nlog>

3.写一个Logger类这里使用线程 以及线程锁。

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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
using NLog;
using System;
using System.Collections.Generic;
using System.Configuration;
using System.IO;
using System.Text;
using System.Threading;

namespace com.aaa.Util
{
    public class Logger
    {
        static readonly object locker = new object();
        NLog.Logger _logger;

        private Logger(NLog.Logger logger)
        {
            _logger = logger;
        }

        public Logger(string name) : this(LogManager.GetLogger(name))
        {

        }

        public static Logger Default { get; private set; }
        static Logger()
        {
            Default = new Logger(NLog.LogManager.GetCurrentClassLogger());
        }

        public static void WriteLog1(string name, string msg)
        {
            LogModels lm = new LogModels();
            lm.Name = name;
            lm.msg = msg;

            ParameterizedThreadStart tStart = new ParameterizedThreadStart(ThreadWriteLog);
            Thread thread = new Thread(tStart);
            thread.Start(lm);//传递参数
        }

        public static void ThreadWriteLog(object arg)
        {
            lock (locker)
            {
                LogModels lm = (LogModels)arg;
                LogManager.Configuration.Variables["LogDir"] = lm.Name;
                Logger logger = new Logger("ESDLog");
                logger.Info(lm.msg);
            }
        }

        #region Debug
        public void Debug(string msg, params object[] args)
        {
            _logger.Debug(msg, args);
        }

        public void Debug(string msg, Exception err)
        {
            _logger.Debug(err, msg);
        }
        #endregion

        #region Info
        public void Info(string msg, params object[] args)
        {
            _logger.Info(msg, args);
        }

        public void Info(string msg, Exception err)
        {
            _logger.Info(err, msg);
        }
        #endregion
        #region Custom
        #endregion

    }

    public class MyLogEventInfo : LogEventInfo
    {
        public MyLogEventInfo() { }
        public MyLogEventInfo(LogLevel level, string loggerName, string message) : base(level, loggerName, message)
        { }

        public override string ToString()
        {
            //Message format
            //Log Event: Logger='XXX' Level=Info Message='XXX' SequenceID=5
            return FormattedMessage;
        }
    }

    public class LogModels
    {
        public string Name { set; get; }
        public string msg { set; get; }
    }


}

4.C#中使用日志记录

1
2
3
4
5
6
7
8
9
10
11
12
13
  1.写入Exception目录              
catch (Exception ex)
   {
     string msg = string.Format("Exception  ={0} }", ex.Message);
     Logger.WriteLog1("Exception",msg);
   }

  2.写入Exception\abc目录
 catch (Exception ex)
     {
        string msg = string.Format("Exception  ={0} }", ex.Message);
        Logger.WriteLog1(@"Exception\abc",msg);
     }