【问题标题】:log4net custom properties not working with multi-threaded applog4net 自定义属性不适用于多线程应用程序
【发布时间】:2013-04-19 04:37:54
【问题描述】:

我有一个应用程序正在使用 log4net AdoNetAppender(DB appender)将我的日志写入数据库。它正在将记录写入数据库,但自定义字段均为 NULL。它们在我的单元测试中使用相同的代码可以正常工作,但在应用程序运行时调用它们时就不行了。它是一个多线程应用程序,用于处理来自消息队列的消息。

对于多线程应用程序的 DB appender 的自定义属性,是否存在任何已知问题(任何人都知道)?这是我对为什么在启动应用程序时它们不工作的唯一猜测,因为我无法在单元测试等中重现。

默认的 log4net 字段可以通过。

我在单例中设置自定义属性值:

   public sealed class Logger
    {
        private static readonly Logger instance = new Logger();
        public static readonly ILog Log = LogManager.GetLogger(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType);


        /// <summary>
        /// Static constructor which sets the properties for the database logging using log4net. This enables analysts to view the log events
        /// inside the database as well as in the local application log file. 
        /// </summary>
        static Logger()
        {
            GlobalContext.Properties["Application"] = "MyApp";
            GlobalContext.Properties["ApplicationVersion"] = Utility.GetApplicationVersion();
            var windowsHost = System.Net.Dns.GetHostName();
            if (!String.IsNullOrEmpty(windowsHost))
                LogicalThreadContext.Properties["Host"] = windowsHost;
            //ThreadContext.Properties["LogTime"] = DateTime.Now;
            var windowsIdentity = System.Security.Principal.WindowsIdentity.GetCurrent();
            if (windowsIdentity != null)
                GlobalContext.Properties["CreatedBy"] = windowsIdentity.Name;
        }

        private Logger()
        {

        }

        public static Logger Instance
        {
            get { return instance; }
        }
    }

编辑:

发现这将尝试添加额外的 log4net 调试。

http://logging.apache.org/log4net/release/faq.html#internalDebug

在 log4nets 内部日志中没有看到任何错误,所以仍然不清楚发生了什么。

【问题讨论】:

    标签: c# log4net


    【解决方案1】:

    我终于明白了。这就是我们尝试全局设置自定义属性的方式。相反,我在我的任何实例绑定到队列和处理消息之前设置应用程序启动时的属性。这似乎做到了....不知道为什么我一开始没有想到这一点。只需使用 log4net GlobalContext 并像魅力一样工作。

    --S

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-12-20
      • 1970-01-01
      • 2019-02-26
      • 1970-01-01
      • 2016-03-29
      • 2011-10-21
      相关资源
      最近更新 更多