nlog 的包装函数 - 分配日志级别 [英] Wrapper function for nlog - assigning log level

查看:42
本文介绍了nlog 的包装函数 - 分配日志级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想要一个自定义日志类,然后将其属性注入 nlog Logger.该类应该初始化 nlog target 和 config ,然后其他人可以使用它而无需知道这些细节.

I want to have a custom log class, which then injects its properties to nlog Logger. The class should initialize nlog target and config , and then others can use it without the need to know those details.

public interface ILogger
{
  void Log(LogEntry entry);
}

public enum LoggingEventType { Debug, Information, Warning, Error, Fatal};

public class LogEntry 
{

   public readonly LoggingEventType Level;
   public readonly string Message;
   public readonly Exception Ex;

   public LogEntry(LoggingEventType level, string message, Exception exception = null)
    {
      this.Level = severity;
      this.Message = message;
      this.Ex = exception;
    }
}


public static Main(){

   //Should happen in Class MyLogger that implements ILogger 

   var config = new NLog.Config.LoggingConfiguration();
   var logfile = new NLog.Targets.FileTarget("logfile") { FileName 
   "file.txt" };
   var logconsole = new NLog.Targets.ConsoleTarget("logconsole");

   config.AddRule(LogLevel.Debug, LogLevel.Fatal, logfile);

   NLog.LogManager.Configuration = config;


  LogEntery log = new LogEntry( Error , "Bad stuff" , IOException);
  Logger nlog  = logger.Error( log.Ex , log.Message);
  //How can I inject log level to Nlog class Logger?
  }

如何向 Nlog 类 Logger 注入日志级别?

How can I inject log level to Nlog class Logger?

推荐答案

也许是这样的:

class NLogLogger : ILogger
{
    private readonly NLog.Logger _logger;

    public NLogLogger(string name)
    {
        _logger = NLog.LogManager.GetLogger(name);
    }

    public void Log(LogEntry entry)
    {
        var nlogLevel = GetNLogLevel(entry.Level);
        if (_logger.IsEnabled(nlogLevel))
        {
           var nlogEvent = NLog.LogEventInfo.Create(nlogLevel, _logger.Name, entry.Message, entry.Ex);
           _logger.Log(typeof(NLogLogger), nlogEvent);
        }
    }

    NLog.LogLevel GetNLogLevel(LoggingEventType level)
    {
        switch (level)
        {
           case LoggingEventType.Debug: return NLog.LogLevel.Debug;
           case LoggingEventType.Information: return NLog.LogLevel.Info;
           case LoggingEventType.Warning: return NLog.LogLevel.Warn;
           case LoggingEventType.Error: return NLog.LogLevel.Error;
           case LoggingEventType.Fatal: return NLog.LogLevel.Fatal;
           default: return NLog.LogLevel.Trace;
        }
    }
}

对于任何语法错误,我们深表歉意.

Sorry for any syntax-errors.

另见:https://github.com/NLog/NLog/wiki/Custom-extension-of-Logger-interface

这篇关于nlog 的包装函数 - 分配日志级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆