public NLogLogProviderLoggingEnabledTests()
		{
			NLogLogManager.ProviderIsAvailableOverride = true;
			var config = new LoggingConfiguration();

			simpleLayoutTarget = new MemoryTarget
			{
				Layout = "${level:uppercase=true}|${message}|${exception}"
			};
			ndcLayoutTarget = new MemoryTarget
			{
				Layout = "${level:uppercase=true}|${ndc:bottomFrames=10:topFrames=10:separator=;}|${message}|${exception}"
			};
			mdcLayoutTarget = new MemoryTarget
			{
				Layout = "${level:uppercase=true}|${mdc:item=Key}|${message}|${exception}"
			};
			config.AddTarget("simpleLayoutMemory", simpleLayoutTarget);
			config.AddTarget("mdcLayoutTarget", mdcLayoutTarget);
			config.AddTarget("ndcLayoutMemory", ndcLayoutTarget);
			config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, simpleLayoutTarget));
			config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, mdcLayoutTarget));
			config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, ndcLayoutTarget));
			LogManager.Configuration = config;
			nLogLogManager = new NLogLogManager();
			sut = nLogLogManager.GetLogger("Test");
		}
        public void init()
        {
            _target = new MemoryTarget();
            _target.Layout = "${message}";

            NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(_target);
        }
예제 #3
0
        public void MemoryTarget_LogLevelTest()
        { 
            ILogger logger = LogManager.GetCurrentClassLogger(); 

            var memoryTarget = new MemoryTarget
            {
                Layout = "${level} ${message}" 
            };

            SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);

            Assert.True(memoryTarget.Logs.Count() == 0);
            logger.Trace("TTT");
            logger.Debug("DDD");
            logger.Info("III");
            logger.Warn("WWW");
            logger.Error("EEE");
            logger.Fatal("FFF"); 
            
            LogManager.Configuration = null;

            Assert.True(memoryTarget.Logs.Count() == 6);
            Assert.True(memoryTarget.Logs[0] == "Trace TTT");
            Assert.True(memoryTarget.Logs[1] == "Debug DDD");
            Assert.True(memoryTarget.Logs[2] == "Info III");
            Assert.True(memoryTarget.Logs[3] == "Warn WWW");
            Assert.True(memoryTarget.Logs[4] == "Error EEE");
            Assert.True(memoryTarget.Logs[5] == "Fatal FFF");
        }
예제 #4
0
        protected void ConfigureLogging()
        {
            var layout = GetStandardLayout();

            if (_memoryTarget == null)
            {
                _memoryTarget = new MemoryTarget
                                {
                                    Name = "Unit Test Log",
                                    Layout = layout
                                };
            }

            lock (typeof (LogManager))
            {
                LogManager.Configuration = new LoggingConfiguration();

                var targets = new List<Target>
                              {
                                  _memoryTarget,
                                  new OutputDebugStringTarget {Name = "Debug", Layout = layout},
                                  new TraceTarget {Name = "Trace", Layout = layout}
                              };

                foreach (var target in targets)
                {
                    LogManager.Configuration.AddTarget(target.Name, target);
                    LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
                }

                LogManager.EnableLogging();

                LogManager.ReconfigExistingLoggers();
            }
        }
예제 #5
0
        public void UsingLoggingAspectWithNLogShouldUseNlogger()
        {
            // arrange - setup nlog
            LoggingConfiguration config = new LoggingConfiguration();

            MemoryTarget memoryTarget = new MemoryTarget { Layout = @"${message}" };
            config.AddTarget("memory", memoryTarget);

            LoggingRule rule = new LoggingRule("*", LogLevel.Debug, memoryTarget);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            Mock<IConfigurationProvider> mock = new Mock<IConfigurationProvider>();
            mock.Setup(provider => provider.ShouldLog(It.IsAny<LogAttribute>())).Returns(true);
            LogAttribute.ConfigurationProvider = mock.Object;

            // arrange - setup logger
            LogAttribute.Logger = new NLogLogger("memory");

            // act
            Person person = new Person { Name = "test", Balance = 0.0d };
            person.Should().NotBeNull();

            // assert
            memoryTarget.Logs.Count.Should().Be(9, "because we called the logging 9 times");
        }
예제 #6
0
        public SqlController()
        {
            var target = NLog.LogManager.Configuration.FindTargetByName("mysqlMemory");

            if (target != null)
            {
                _memoryTarget = target as MemoryTarget;
            }
        }
 public NLogLogProviderLoggingEnabledTests()
 {
     var config = new LoggingConfiguration();
     _target = new MemoryTarget();
     _target.Layout = "${level:uppercase=true}|${message}|${exception}";
     config.AddTarget("memory", _target);
     config.LoggingRules.Add(new LoggingRule("*", LogLevel.Trace, _target));
     LogManager.Configuration = config;
     _sut = new NLogLogProvider().GetLogger("Test");
 }
 private void ConfigureLogger(NLog.LogLevel nlogLogLevel)
 {
     var config = new LoggingConfiguration();
     _target = new MemoryTarget {Layout = "${level:uppercase=true}|${message}|${exception}"};
     config.AddTarget("memory", _target);
     var loggingRule = new LoggingRule("*", NLog.LogLevel.Trace, _target);
     loggingRule.DisableLoggingForLevel(nlogLogLevel);
     config.LoggingRules.Add(loggingRule);
     LogManager.Configuration = config;
     _sut = new NLogLogProvider().GetLogger("Test");
 }
        public void UsingCodeWithSpecific()
        {
            var target = new MemoryTarget();

            // This will log to the specified appender. 
            Configure.With()
                     .NLog(target)
                     .DefaultBuilder();
            
            Assert.IsNotEmpty(target.Logs);
        }
예제 #10
0
        public LogContextTests()
        {
            var config = new LoggingConfiguration();
            _memoryTarget = new MemoryTarget
            {
                Layout = new SimpleLayout("${message} ${mdlc:item=context1} ${mdlc:item=context2}")
            };
            config.AddTarget("memory", _memoryTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, _memoryTarget));
            LogManager.Configuration = config;

            _logger = LogManager.GetCurrentClassLogger();
        }
예제 #11
0
        public virtual void Dispose()
        {
            if (_memoryTarget != null)
            {
                LogManager.Flush();

                var logs = new List<string>(_memoryTarget.Logs); // must clone otherwise the statement below this one will throw a 'collection modified' exception

                logs.Each(l => _helper.WriteLine(l));

                _memoryTarget = null;
            }
        }
 private void ConfigureLogger(NLog.LogLevel nlogLogLevel)
 {
     NLogLogManager.ProviderIsAvailableOverride = true;
     var config = new LoggingConfiguration();
     target = new MemoryTarget();
     target.Layout = "${level:uppercase=true}|${message}|${exception}";
     config.AddTarget("memory", target);
     var loggingRule = new LoggingRule("*", LogLevel.Trace, target);
     loggingRule.DisableLoggingForLevel(nlogLogLevel);
     config.LoggingRules.Add(loggingRule);
     NLog.LogManager.Configuration = config;
     sut = new NLogLogManager().GetLogger("Test");
 }
예제 #13
0
        public void CanCreateTableWithQuotes()
        {
            var target = new MemoryTarget { Name = MigratorLogManager.LOGGER_NAME, Layout = new SimpleLayout("${message}") };
            MigratorLogManager.SetNLogTarget(target);

            var provider = CreateProvider(true);
            provider.AddTable("quoted", new Column("id", DbType.Int32));

            var sql = target.Logs.First();
            provider.RemoveTable("quoted");

            Assert.AreEqual("CREATE TABLE [quoted] ([id] INT)", sql);
        }
예제 #14
0
 public NLogLogProviderLoggingTests()
 {
     var config = new LoggingConfiguration();
     _target = new MemoryTarget
     {
         Layout = "${level:uppercase=true}|${ndc}|${mdc:item=key}|${message}|${exception}"
     };
     config.AddTarget("memory", _target);
     config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, _target));
     LogManager.Configuration = config;
     _logProvider = new NLogLogProvider();
     _sut = new LoggerExecutionWrapper(new NLogLogProvider().GetLogger("Test"));
 }
예제 #15
0
        internal static MemoryTarget AssignMemoryTarget(string name, string layout, NLog.LogLevel minLogLevel = null)
        {
            var target = new MemoryTarget { Layout = layout };

            lock (config)
            {
                config.AddTarget(name, target);
                config.LoggingRules.Add(new LoggingRule("*", minLogLevel ?? NLog.LogLevel.Debug, target));

                NLog.LogManager.Configuration = config;
            }

            return target;
        }
예제 #16
0
        public MemoryTarget GetTestLogger()
        {
            var memoryTarget = new MemoryTarget() { Layout = @"${message}" };

            var config = new LoggingConfiguration();
            config.AddTarget("memory", memoryTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, memoryTarget));

            LogManager.Configuration = config;

            Trace.Listeners.Add(new NLogTraceListener());

            return memoryTarget;
        }
예제 #17
0
파일: Example.cs 프로젝트: CharlieBP/NLog
    static void Main(string[] args)
    {
        MemoryTarget target = new MemoryTarget();
        target.Layout = "${message}";

        NLog.Config.SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");

        foreach (string s in target.Logs)
        {
            Console.Write("logged: {0}", s);
        }
    }
예제 #18
0
        private void EnableCustomLogger()
        {
            // Make WebUtils log to Console as well as to Memory
            LoggingConfiguration logConf = new LoggingConfiguration();
            this.memoryTarget = new MemoryTarget();
            ConsoleTarget consoleTarget = new ConsoleTarget();

            logConf.AddTarget("MemoryTarget", memoryTarget);
            logConf.AddTarget("ConsoleTarget", consoleTarget);
            logConf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, memoryTarget));
            logConf.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget));

            LogManager.Configuration = logConf;
            WebUtils.logger = LogManager.GetLogger("TestLogger");
        }
        public LogContextInterceptorTests()
        {
            var config = new LoggingConfiguration();
            _memoryTarget = new MemoryTarget
            {
                Layout = new SimpleLayout("${message} ${mdlc:item=context}")
            };
            config.AddTarget("memory", _memoryTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, _memoryTarget));
            LogManager.Configuration = config;

            _container = new WindsorContainer();
            _container.Register(Component.For<ILogContextResolver>().ImplementedBy<TestLogContextResolver>());
            _container.Register(Component.For<LogContextInterceptor>());
            _container.Register(Component.For<A>().Interceptors<LogContextInterceptor>());
        }
예제 #20
0
        public void Setup()
        {
            // arrange - setup nlog
            LoggingConfiguration config = new LoggingConfiguration();

            _memoryTarget = new MemoryTarget { Layout = @"${level} ${message}" };
            config.AddTarget("memory", _memoryTarget);

            LoggingRule rule = new LoggingRule("*", LogLevel.Trace, _memoryTarget);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;

            // arrange - setup logger
            _logger = new NLogLogger("memory");
        }
예제 #21
0
        public void Setup(string templateName, bool debug)
        {
            LogManager.ThrowExceptions = true;
            var loggingConfig = new LoggingConfiguration();

            _target = new MemoryTarget
            {
                Layout = $"${{mustache:{templateName}:debug={debug}}}"
            };
            loggingConfig.AddTarget("memory", _target);
            loggingConfig.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, _target));

            LogManager.Configuration = loggingConfig;

            _logger = LogManager.GetLogger("Tests");
        }
예제 #22
0
        public void UsingCodeWithImplied()
        {

            var config = new LoggingConfiguration();
            var target = new MemoryTarget();
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));
            config.AddTarget("target", target);
            LogManager.Configuration = config;

            //This will log to all appenders currently configured in Log4net
            SetLoggingLibrary.NLog();
            Configure.With()
                     .DefaultBuilder();

            Assert.IsNotEmpty(target.Logs);
        }
예제 #23
0
        public void TestFixtureSetUp()
        {
            var config = new LoggingConfiguration();

            _logTarget = new MemoryTarget();
            _logTarget.Layout = "${level:uppercase=true}|${message}|${exception:format=tostring}";
            config.AddTarget("memory", _logTarget);

            var consoleTarget = new ConsoleTarget();
            consoleTarget.Layout = "${longdate}|${logger}|${level:uppercase=true}|${message}|${exception:format=tostring}";
            config.AddTarget("console", consoleTarget);

            var rule = new LoggingRule("*", LogLevel.Trace, _logTarget);
            rule.Targets.Add(consoleTarget);
            config.LoggingRules.Add(rule);

            LogManager.Configuration = config;
        }
예제 #24
0
        public void When_disable_logging_via_property_then_should_not_log()
        {
            var config = new LoggingConfiguration();
            var target = new MemoryTarget
            {
                Layout = "${level:uppercase=true}|${ndc}|${mdc:item=key}|${message}|${exception}"
            };
            config.AddTarget("memory", target);
            config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, target));
            LogManager.Configuration = config;
            LogProvider.SetCurrentLogProvider(new NLogLogProvider());

            LogProvider.IsDisabled = true;
            var logger = LogProvider.GetLogger("DisableLogging");
            logger.Info("test");

            target.Logs.Should().BeEmpty();
        }
예제 #25
0
        public static LogHelper InterceptLogging(params Type[] typesToIntercept)
        {
            var config = new LoggingConfiguration();
            var target = new MemoryTarget
                             {
                                 Layout = "${level}|${logger}|${message}"
                             };
            config.AddTarget("UnitTest", target);
            foreach (var type in typesToIntercept)
            {
                config.LoggingRules.Add(
                    new LoggingRule(type.FullName, LogLevel.Trace, target));
            }

            var oldConfig = LogManager.Configuration;
            LogManager.Configuration = config;
            LogManager.ReconfigExistingLoggers();
            return new LogHelper(oldConfig, target.Logs);
        }
        public void IndexLogsEvents()
        {
            // Initialise the configuration
            var config = new LoggingConfiguration();
            var target = new MemoryTarget
                {
                    Layout = "${Logger}|${Level}|${Message}"
                };
            config.AddTarget("unitTesting", target);
            var rule = new LoggingRule("*", LogLevel.Debug, target);
            config.LoggingRules.Add(rule);

            // Generate the logger
            var factory = new LogFactory
                {
                    Configuration = config
                };
            var logger = factory.GetLogger(typeof(DynamicController).FullName);
            try
            {
                DynamicController.OverrideLogger(logger);
                var controller = new DynamicController();

                // Resolve an action that doesn't exist - we are only interested that logging is actually workig
                controller.Index("blankServerName", "blankProjectName", "blankBuildName", "nowherenonsenseaction");

                var expectedMessages = new[] 
                    {
                        MakeMessage("Dynamically resolving request", LogLevel.Debug),
                        MakeMessage("Generating request context", LogLevel.Debug),
                        MakeMessage("Action is a build level report", LogLevel.Debug),
                        MakeMessage("Retrieving action handler for nowherenonsenseaction", LogLevel.Debug),
                        MakeMessage("Unable to find action handler for nowherenonsenseaction", LogLevel.Info),
                        MakeMessage("Generating error message", LogLevel.Debug)
                    };
                Assert.That(target.Logs.ToArray(), Is.EqualTo(expectedMessages));
            }
            finally
            {
                DynamicController.ResetLogger();
            }
        }
예제 #27
0
        public void MemoryTarget_ReconfigureTest_SameTarget_ExpectLogsEmptied()
        {
            ILogger logger = LogManager.GetCurrentClassLogger();

            var memoryTarget = new MemoryTarget
            {
                Layout = "${level} ${message}"
            };

            SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);

            logger.Debug("DDD");
            logger.Info("III");
            logger.Warn("WWW");

            Assert.True(memoryTarget.Logs.Count() == 3);
            Assert.True(memoryTarget.Logs[0] == "Debug DDD");
            Assert.True(memoryTarget.Logs[1] == "Info III");
            Assert.True(memoryTarget.Logs[2] == "Warn WWW");

            LogManager.Configuration = null;

            //
            // Reconfigure the logger using the same MemoryTarget.

            memoryTarget = new MemoryTarget
            {
                Layout = "${level} ${message}"
            };

            SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);

            logger.Trace("TTT");
            logger.Error("EEE");
            logger.Fatal("FFF");

            Assert.True(memoryTarget.Logs.Count() == 3);
            Assert.True(memoryTarget.Logs[0] == "Trace TTT");
            Assert.True(memoryTarget.Logs[1] == "Error EEE");
            Assert.True(memoryTarget.Logs[2] == "Fatal FFF");
        }
예제 #28
0
		public void Should_preserve_correct_callsite_information()
		{
			// Step 1. Create configuration object 
			var config = new LoggingConfiguration();

			// Step 2. Create targets and add them to the configuration 
			var target = new MemoryTarget();
			config.AddTarget("target", target);

			// Step 3. Set target properties 
			target.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${callsite} ${message}";

			// Step 4. Define rules
			var rule = new LoggingRule("*", LogLevel.Debug, target);
			config.LoggingRules.Add(rule);


			var factory = new NLogFactory(config);

			WriteLogMessage(factory);
			var logMessage = target.Logs[0];
			StringAssert.Contains("NLogTests.WriteLogMessage", logMessage);
		}
예제 #29
0
        public void When_enable_logging_via_env_var_then_should_log()
        {
            Environment.SetEnvironmentVariable(LogProvider.DisableLoggingEnvironmentVariable, "true");
            var config = new LoggingConfiguration();
            var target = new MemoryTarget
            {
                Layout = "${level:uppercase=true}|${ndc}|${mdc:item=key}|${message}|${exception}"
            };
            config.AddTarget("memory", target);
            config.LoggingRules.Add(new LoggingRule("*", NLog.LogLevel.Trace, target));
            LogManager.Configuration = config;
            LogProvider.SetCurrentLogProvider(new NLogLogProvider());

            Environment.SetEnvironmentVariable(LogProvider.DisableLoggingEnvironmentVariable, "false");
            var logger = LogProvider.GetLogger("DisableLogging");
            logger.Info("test");

            target.Logs.Should().NotBeEmpty();
        }
예제 #30
0
        public void ExceptionTest()
        {
            var target = new MemoryTarget { Layout = @"${exception:format=tostring}" };
            SimpleConfigurator.ConfigureForTargetLogging(target);
            var logger = LogManager.GetCurrentClassLogger();

            try
            {
                throw new InvalidOperationException();
            }
            catch (Exception ex)
            {
                Thread.CurrentThread.CurrentUICulture = new CultureInfo("en-US", false);
                Thread.CurrentThread.CurrentCulture = new CultureInfo("en-US", false);
                logger.Error(ex, "");

                Thread.CurrentThread.CurrentUICulture = new CultureInfo("de-DE", false);
                Thread.CurrentThread.CurrentCulture = new CultureInfo("de-DE", false);
                logger.Error(ex, "");

                Assert.Equal(2, target.Logs.Count);
                Assert.NotNull(target.Logs[0]);
                Assert.NotNull(target.Logs[1]);
                Assert.Equal(target.Logs[0], target.Logs[1]);
            }
        }