如何在NLog

时间:2016-08-22 11:20:07

标签: c# log4net nlog

我使用log4Net粘贴我的代码段,

- 简而言之:

我正在创建一个新的滚动appender和一个内存appender,并将它们连接到logger存储库中的记录器,用于每个新线程。

无论我在滚动appender中写什么,都会自动进入特定线程的内存追加器。

我想使用NLog

实现相同目的

我尝试了NLog,但我有两个行为

  1. 所有文件目标写入相同的内存目标,而不是特定于线程的目标。
  2. 设置新的appender后,所有内容都会被写入新的appender。

    class Program {
    private static Random rnd = new Random();
    private static object sync = new object();
    
    static void Main(string[] args)
    {
        List<Task> tasks = new List<Task>();
        // Execute the task 10 times.
        for (int ctr = 1; ctr <= 5; ctr++)
        {
            tasks.Add(Task.Factory.StartNew(FirstWorldTask));
            Thread.Sleep(10);
        }
        Task.WaitAll(tasks.ToArray());
    }
    
    private static void FirstWorldTask()
    {
        string loggerName = "Logger";
        string randomName = rnd.Next().ToString();
    
        lock (sync)
        {
            loggerName += randomName;
            Console.WriteLine(loggerName);
        }
    
        log4net.Layout.PatternLayout patternLayout = new log4net.Layout.PatternLayout("%message%newline");
        patternLayout.ActivateOptions();
    
        RollingFileAppender rollingFileAppender = new RollingFileAppender();
        rollingFileAppender.AppendToFile = false;
        rollingFileAppender.RollingStyle = RollingFileAppender.RollingMode.Size;
        rollingFileAppender.MaxSizeRollBackups = 0;
        rollingFileAppender.MaximumFileSize = "20MB";
        rollingFileAppender.Layout = patternLayout;
        rollingFileAppender.File = "./" + randomName + "/logfile.txt";
        //appender.File = GlobalSettings.FOLDER_NAME + "logfile" + currentCount.ToString() + ".txt";
        rollingFileAppender.ActivateOptions();
    
        MemoryAppender memoryAppender = new MemoryAppender();
        memoryAppender.AddFilter(new log4net.Filter.LevelRangeFilter() { LevelMin = log4net.Core.Level.Info, LevelMax = log4net.Core.Level.Fatal });
    
        log4net.Repository.Hierarchy.Hierarchy hierarchy = (log4net.Repository.Hierarchy.Hierarchy)log4net.LogManager.GetRepository();
        log4net.Repository.Hierarchy.Logger logger = hierarchy.GetLogger(loggerName) as log4net.Repository.Hierarchy.Logger;
    
        logger.AddAppender(rollingFileAppender);
        logger.AddAppender(memoryAppender);
        hierarchy.Configured = true;
    
        var m_log = log4net.LogManager.GetLogger(loggerName);
    
    
        for (int i = 0; i < 5; i++)
        {
            m_log.Info(i + " " + randomName);
            Thread.Sleep(10);
        }
    
        StringBuilder stringBuilder = new StringBuilder();
        foreach (var loggingEvent in memoryAppender.GetEvents())
        {
            stringBuilder.AppendLine(loggingEvent.MessageObject.ToString());
        }
    
        memoryAppender.Clear();
        Console.WriteLine(stringBuilder.ToString());
    }
    

    }

  3. NLog配置:

        <target name="LogFile"
                xsi:type="File"
                fileName="${mdc:item=LogsDirectory}/logfile.txt"
                layout="${message}"
                maxArchiveFiles="10"
                archiveAboveSize="20000000"
                archiveNumbering="Sequence"
                archiveFileName="${mdc:item=LogsDirectory}/logfile.{#}.txt"/>
        <target name="Memory" xsi:type="Memory" layout="${message}"/>
    
      <rules>
        <logger name="LogFile" minlevel="Debug" writeTo="LogFile" />
        <logger name="LogFile" minlevel="Info" writeTo="Memory" />
    </rules>
    

    FirstWorldTask的NLog代码

        private static void FirstWorldTask()
        {
            var folderName = rnd.Next();
            NLog.MappedDiagnosticsContext.Set("LogsDirectory", folderName);
            ILog logger = LogManager.GetLogger("LogFile");
            var memoryTarget = (MemoryTarget)NLog.LogManager.Configuration.FindTargetByName("Memory");
            memoryTarget.Logs.Clear();
            for (int i = 0; i < 5; i++)
            {
                logger.Info(i + " " + folderName);
                Thread.Sleep(10);
            }
            int j = 0;
    
            while (j < memoryTarget.Logs.Count)
            {
                Console.WriteLine(memoryTarget.Logs[j] + "\t" + folderName);
                memoryTarget.Logs.RemoveAt(j);
    
                j++;
            }
        }
    

0 个答案:

没有答案