NLog类库使用探索——编程配置

    以编程的方式配置,这是我项目中的,我都不知道为什么使用编程。直接配置不很好吗,估计他也没有研究。直接上步骤和代码:

  1. 创建一个LoggingConfiguration对象,用来保存配置信息
  2. 至少创建一个输出目标对象
  3. 设置该输出目标对象的属性
  4. 设置LoggingRule对象,并将其添加到LoggingConfiguration对象的LoggingRules集合中
  5. 启用该LoggingConfiguration对象(将LogManager.Configuration设定为该LoggingConfiguration对象即可)
using NLog; 

using NLog.Targets; 

using NLog.Config; 

using NLog.Win32.Targets; 

 

class Example 

{ 

    static void Main(string[] args) 

    { 

        // Step 1. Create configuration object 

         

        LoggingConfiguration config = new LoggingConfiguration(); 

         

        // Step 2. Create targets and add them to the configuration 

 

        ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget(); 

        config.AddTarget("console", consoleTarget); 

         

        FileTarget fileTarget = new FileTarget(); 

        config.AddTarget("file", fileTarget); 

         

        // Step 3. Set target properties 

         

        consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}"; 

        fileTarget.FileName = "${basedir}/file.txt"; 

        fileTarget.Layout = "${message}"; 

         

        // Step 4. Define rules 

         

        LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget); 

        config.LoggingRules.Add(rule1); 

 

        LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget); 

        config.LoggingRules.Add(rule2); 

         

        // Step 5. Activate the configuration 

 

        LogManager.Configuration = config; 

         

        // Example usage 

 

        Logger logger = LogManager.GetLogger("Example"); 

        logger.Trace("trace log message"); 

        logger.Debug("debug log message"); 

        logger.Info("info log message"); 

        logger.Warn("warn log message"); 

        logger.Error("error log message"); 

        logger.Fatal("fatal log message"); 

    } 

}

你可能感兴趣的:(log)