简体   繁体   English

程序化NLog配置不起作用

[英]Programmatic NLog configuration isn't working

I am setting up a test app using Nlog and I want the configuration to be editable through code. 我正在使用Nlog设置测试应用,并且我希望配置可以通过代码进行编辑。 I have set up the configuration correctly, however I am unable to actually see anything logging. 我已经正确设置了配置,但是实际上看不到任何日志记录。 I am not sure if this is because I have coded it incorrectly or if I have it implemented incorrectly. 我不确定这是因为我编码不正确还是实现不正确。 I am not seeing a file being created nor am I getting a colored console. 我没有看到正在创建的文件,也没有看到彩色的控制台。 Any help is appreciated as there is not too much documentation on programmatic configuration. 感谢您提供任何帮助,因为关于程序配置的文档不足。

using System;
using NLog;
using NLog.Targets;
using NLog.Targets.Wrappers;
using NLog.Config;

namespace NLogArchitecture
{
    class ApplicationFramework
    {
        public static Logger log = LogManager.GetCurrentClassLogger();
        public static int sum = 0;

        public static void Main()
        {

            SetupLoggingConfiguration();

            F1();
            F2();
            F3();
            F4();
        }

        public static void F1()
        {
            int[] array1 = new int[5] { 1, 2, 3, 4, 5 };

            for (int i = 0; i > array1.Length; i++)
            {
                sum += array1[i];
            }

            log.Trace("The sum of array1 is: " + sum);
        }

        public static void F2()
        {
            int sumException = 0;
            try
            {
                sumException = sum / 0;
            }

            catch(Exception ex)
            {
                log.Error("Invalid operation: " + ex);
            }
        }

        public static void F3()
        {
            sum = sum + 3;

            log.Debug("Consider a different syntax");
        }

        public static void F4()
        {
            if (sum > 12) log.Info("The sum has been calculated well");
            if (sum <= 10) log.Info("The sum has been calculated incorrectly");
        }

        public static void SetupLoggingConfiguration()
        {


            // Intialize Config Object
            LoggingConfiguration config = new LoggingConfiguration();

            // Initialize Console Target
            var consoleTarget = new ColoredConsoleTarget("Console Target")
            {
                Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}"
            };

            // Initialize the AsyncWrapper for the ConsoleTarget
            AsyncTargetWrapper consoleWrapper = new AsyncTargetWrapper();
            consoleWrapper.WrappedTarget = consoleTarget;
            consoleWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;
            consoleWrapper.QueueLimit = 5000;

            // Initialize the AsyncFlushTargetWrapper for the ConsoleWrapper
            AutoFlushTargetWrapper consoleFlushWrapper = new AutoFlushTargetWrapper();
            consoleFlushWrapper.WrappedTarget = consoleWrapper;

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            consoleFlushWrapper.Condition = "level >= LogLevel.Trace";

            // Adding the target to the config
            config.AddTarget("console", consoleFlushWrapper);


            // Initialize File Target
            var fileTarget = new FileTarget("File Target")
            {
                FileName = "@C:/logs/log.txt",
                KeepFileOpen = false,
                Layout = @"${time} ${longdate} ${uppercase: ${level}} ${logger} ${message} ${exception: format=ToString}"
            };

            // Initialize the AsyncWrapper for the fileTarget
            AsyncTargetWrapper fileWrapper = new AsyncTargetWrapper();
            fileWrapper.WrappedTarget = fileTarget;
            fileWrapper.QueueLimit = 5000;
            fileWrapper.OverflowAction = AsyncTargetWrapperOverflowAction.Block;

            // Initialize the AsyncFlushTargetWrapper for the FileWrapper
            AutoFlushTargetWrapper fileFlushWrapper = new AutoFlushTargetWrapper();
            fileFlushWrapper.WrappedTarget = fileWrapper;

            // This condition controls when the log is flushed. Set the LogLevel to be equivalent to the maximum level specified in the targetRule
            fileFlushWrapper.Condition = "level >= LogLevel.Trace";

            // Adding the target to the config
            config.AddTarget("file", fileFlushWrapper);

            // Creating the Log Level rules for each target and adding them to the config
            // Edit these to change what methods are logged
            var fileRule = new LoggingRule("FileRule", fileTarget);
            fileRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
            fileRule.EnableLoggingForLevel(LogLevel.Error);
            config.LoggingRules.Add(fileRule);

            var consoleRule = new LoggingRule("ConsoleRule", consoleTarget);
            consoleRule.EnableLoggingForLevels(LogLevel.Trace, LogLevel.Info);
            consoleRule.EnableLoggingForLevel(LogLevel.Error);
            config.LoggingRules.Add(consoleRule);

            // Assigning the configuration to the logger
            LogManager.Configuration = config;

        }
    }
}

Your issue is in your LoggingRule Pattern. 您的问题出在您的LoggingRule模式中。 NLog does not know what 'ConsoleRule' or 'FileRule' is. NLog不知道“ ConsoleRule”或“ FileRule”是什么。 There are no matching patterns in your logger name like that since you are using default. 由于您使用的是默认记录,因此您的记录器名称中没有匹配的模式。

var consoleRule = new LoggingRule("ConsoleRule", consoleTarget);
var fileRule = new LoggingRule("FileRule", fileTarget);

Change it to '*' to match all or give your logger a name to match on for the rule. 将其更改为“ *”以匹配所有内容,或为记录器命名以匹配规则。

var consoleRule = new LoggingRule("*", consoleTarget);
var fileRule = new LoggingRule("*", fileTarget);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM