如何在整个DLL中只使用单个NLog实例

时间:2015-10-22 12:19:21

标签: c# multithreading nlog

我想在DLL中使用NLog这是我的代码

namespace TestLogging
{
    public class Class2
    {
        public void foo()
        {
            LogWrapper.initlog();
            LogWrapper.write("Error message");
        }
    }


    public static class LogWrapper
    {
        private static bool isInit = false;
        private static Logger _logger = null;

        public static void initlog()
        {


            // Make sure logger is initialized only once 
            if (!isInit)
            {
                var config = new LoggingConfiguration();

                var fileTarget = new FileTarget();
                config.AddTarget("file", fileTarget);

                // Step 3. Set target properties 
                fileTarget.Layout = @"${date:format=HH\:mm\:ss} - ${message}";
                fileTarget.FileName = "c:/myFolder/" + "${date:format=yyyy-MM-dd}.log";

                var rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
                config.LoggingRules.Add(rule2);

                // Step 5. Activate the configuration
                LogManager.Configuration = config;

                // Example usage
                _logger = LogManager.GetLogger("Example");

                isInit = true;
            }
        }

        public static void write(string s)
        {
            if (isInit == false)
                throw new Exception("Not initialized");

            _logger.Error(s);

        }
    }
}

我的目标是DLL中的许多不同类应该能够通过此日志包装器使用NLog。配置应该完成一次。我的方法是否正确实施?它是线程安全吗?

1 个答案:

答案 0 :(得分:0)

在类级别声明一个静态对象

private static object _locker = new object();
在initlog中

对其进行了锁定

lock(_locker)
{
    //your code
}
你的写方法中的

做同样的

    lock(_locker)
{
       if (isInit == false)
            throw new Exception("Not initialized");

        _logger.Error(s);

}