[ create a new paste ] login | about

Link: http://codepad.org/p3gtJQPy    [ raw code | fork ]

C, pasted on Oct 23:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using NLog;
using NLog.Config;
using NLog.Targets;

namespace TestLogging
{
    

    public class Class2
    {
        private Logger _logger = null;

        // Constructor
        public Class2()
        {
            // Is logger set up?
            if (!LogWrapper.IsInited())
            {
                throw new Exception("Logging was not set up");
            }

            // Yes, get instance for this class
            _logger = LogManager.GetCurrentClassLogger();

        }

        // Test log writing
        public void TestMethod()
        {
            _logger.Error("Hello world");
        }
    }


    public class Class3
    {
        // Just used for setting up the logger
        public void foo1()
        {
            LogWrapper.LogInit("c:/myFolder/");  
        }
    }

    // This class is mainly used now to set up the logger
    class LogWrapper
    {
        private static bool _isInit = false;
        private static readonly object _locker = new object();

        public static bool IsInited()
        {
            lock (_locker)
            {
                return _isInit;
            }
        }

        public static void LogInit(string basedir)
        {

            lock (_locker)
            {
                // Make sure logger is initializes only once 
                if (!_isInit)
                {
                    var config = new LoggingConfiguration();

                    // Create target as file
                    var fileTarget = new FileTarget();
                    config.AddTarget("file", fileTarget);

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

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

                    // Activate the configuration
                    LogManager.Configuration = config;

                    _isInit = true;
                }
            }
        }

         
    }
}


Create a new paste based on this one


Comments: