【问题标题】:Log4Net logging from custom interface来自自定义界面的 Log4Net 日志记录
【发布时间】:2015-01-19 15:51:23
【问题描述】:

我想知道如何使用 log4net(在我的示例中)以 %logger 模式打印正确的类名。

在我的应用程序中,我正在使用实现日志接口的日志类(遵循 SOLID)。其他类使用日志接口抽象来执行实际的日志记录。我想切换到 Log4Net,但我正在考虑保留日志记录抽象。自定义日志记录类方法将对象作为参数并根据它们的状态创建日志。

因此,在下面的示例中,%logger 模式将记录“MyLogger”,这是预期的,但我想记录调用类名称(在本例中为 ObjectManipulator)。

using System.Reflection;
using log4net;

namespace LoggingTestur
{
    class Program
    {
        class AnObject
        {
            public string State { get; set; }
        }

        interface IMyLogger
        {
            void LogObjectStateChenge(AnObject anObject);
        }

        class MyLogger : IMyLogger
        {
            private static readonly ILog Log = LogManager.GetLogger(MethodBase.GetCurrentMethod().DeclaringType);

            public void LogObjectStateChenge(AnObject anObject)
            {
                Log.InfoFormat("AnObject's state is: {0}", anObject.State);
            }
        }

        class ObjectManipulator
        {
            private readonly IMyLogger _logger;

            public ObjectManipulator(IMyLogger logger)
            {
                _logger = logger;
            }

            public void Manipulate()
            {
                var anObject = new AnObject { State = "New" };
                _logger.LogObjectStateChenge(anObject);
            }
        }

        static void Main(string[] args)
        {
            var logger = new MyLogger();
            var manipulator = new ObjectManipulator(logger);
            manipulator.Manipulate();
        }
    }
}

【问题讨论】:

    标签: c# logging log4net


    【解决方案1】:

    你有几个选项来获取类名:

    1. 将其作为参数传递,即LogObjectStateChange(AnObject anObject, Type type = null);

    2. 如果您的目标是 4.5 运行时,您可以使用 CallerFilePath 属性来获取文件名,并从中提取类名(假设每个类有一个文件,文件名是与类名相同),即LogObjectStateChange(AnObject anObject, [CallerFilePath] string fileName = "")

    3. 使用反射从 CallStack 和 StackFrame 类中获取调用类。请注意,尽管在 Release 版本中,编译器可能会内联方法或以其他方式重新排列事物,从而导致堆栈跟踪中的信息不正确。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2012-09-25
      • 1970-01-01
      • 1970-01-01
      • 2010-12-21
      • 2010-12-28
      • 1970-01-01
      • 2016-04-23
      • 1970-01-01
      相关资源
      最近更新 更多