public void NestedXmlConfigElementTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <extensions>
                    <add type='" + typeof(StructuredDebugTarget).AssemblyQualifiedName + @"' />
                </extensions>
                <targets>
                    <target type='StructuredDebugTarget'>
                      <name>structuredTgt</name>
                      <layout>${message}</layout>
                      <config platform='any'>
                        <parameter name='param1' />
                      </config>
                    </target>
                </targets>
            </nlog>");

            var t = c.FindTargetByName("structuredTgt") as StructuredDebugTarget;

            Assert.NotNull(t);
            Assert.Equal("any", t.Config.Platform);
            Assert.Equal("param1", t.Config.Parameter.Name);
        }
示例#2
0
        public static async Task ExecuteInNlogWrap(string loggerName, Func <Task> hostRunTaskFactory)
        {
            var curDir = Directory.GetCurrentDirectory();
            var cfg    = new XmlLoggingConfiguration(Path.Combine(curDir, "nlog.config"));

            LogManager.Configuration = cfg;
            var logger = LogManager.GetLogger(loggerName);

            try
            {
                await hostRunTaskFactory();
            }
            catch (Exception exception)
            {
                //NLog: catch setup errors
                logger.Error(exception, "Stopped program because of exception");
                throw;
            }
            finally
            {
                // Ensure to flush and stop internal timers/threads before application-exit (Avoid segmentation fault on Linux)
                LogManager.Shutdown();
            }
        }
示例#3
0
        public void AggregateExceptionSingleTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='debug1' type='Debug' layout='${exception:format=message,shorttype:maxInnerExceptionLevel=5}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug1' />
                </rules>
            </nlog>");

            var task1 = System.Threading.Tasks.Task.Factory.StartNew(() => { throw new Exception("Test exception 1", new Exception("Test Inner 1")); },
                                                                     System.Threading.CancellationToken.None, System.Threading.Tasks.TaskCreationOptions.None, System.Threading.Tasks.TaskScheduler.Default);

            var aggregateExceptionMessage = "nothing thrown!";

            try
            {
                System.Threading.Tasks.Task.WaitAll(new[] { task1 });
            }
            catch (AggregateException ex)
            {
                aggregateExceptionMessage = ex.ToString();
                logger.Error(ex, "msg");
            }

            Assert.Contains(typeof(AggregateException).Name, aggregateExceptionMessage);
            Assert.Contains("Test exception 1", aggregateExceptionMessage);
            Assert.Contains("Test Inner 1", aggregateExceptionMessage);

            var lastMessage = GetDebugLastMessage("debug1");

            Assert.StartsWith("Test exception 1", lastMessage);
            Assert.Contains("Test Inner 1", lastMessage);
        }
示例#4
0
        public void AsyncTaskTarget_SkipAsyncTargetWrapper()
        {
            try
            {
                ConfigurationItemFactory.Default.RegisterType(typeof(AsyncTaskTestTarget), null);
                LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
            <targets async='true'>
                <target name='asyncDebug' type='AsyncTaskTest' />
                <target name='debug' type='Debug' />
            </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

                Assert.NotNull(LogManager.Configuration.FindTargetByName <AsyncTaskTestTarget>("asyncDebug"));
                Assert.NotNull(LogManager.Configuration.FindTargetByName <NLog.Targets.Wrappers.AsyncTargetWrapper>("debug"));
            }
            finally
            {
                ConfigurationItemFactory.Default = null;
            }
        }
示例#5
0
        public void CustomInnerException_ObsoleteMethodTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='debug1' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message}' />
                    <target name='debug2' type='Debug' layout='${exception:format=shorttype,message:maxInnerExceptionLevel=1:innerExceptionSeparator=&#13;&#10;----INNER----&#13;&#10;:innerFormat=type,message,data}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug1' />
                    <logger minlevel='Info' writeTo='debug2' />
                </rules>
            </nlog>");

            var t   = (DebugTarget)LogManager.Configuration.AllTargets[0];
            var elr = ((SimpleLayout)t.Layout).Renderers[0] as ExceptionLayoutRenderer;

            Assert.Equal("\r\n----INNER----\r\n", elr.InnerExceptionSeparator);

            string       exceptionMessage   = "Test exception";
            const string exceptionDataKey   = "testkey";
            const string exceptionDataValue = "testvalue";
            Exception    ex = GetNestedExceptionWithStackTrace(exceptionMessage);

            ex.InnerException.Data.Add(exceptionDataKey, exceptionDataValue);
#pragma warning disable 0618
            // Obsolete method requires testing until completely removed.
            logger.ErrorException("msg", ex);
#pragma warning restore 0618
            AssertDebugLastMessage("debug1", "ApplicationException Wrapper2" +
                                   "\r\n----INNER----\r\n" +
                                   "System.ArgumentException Wrapper1");
            AssertDebugLastMessage("debug2", string.Format("ApplicationException Wrapper2" +
                                                           "\r\n----INNER----\r\n" +
                                                           "System.ArgumentException Wrapper1 " + ExceptionDataFormat, exceptionDataKey, exceptionDataValue));
        }
        public void NormalStringFormatTest()
        {
            LogEventInfo logEventInfo = new LogEventInfo(LogLevel.Info, "MyLogger", null, "{0:X} - Login request from {1} for {2} with userid {0}", new object[]
            {
                42,
                "John",
                "BestApplicationEver"
            });

            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog throwExceptions='true'>
                    <targets>
                        <target name='debug' type='Debug'  >
                                <layout type='JsonLayout' IncludeAllProperties='true'>
                                    <attribute name='LogMessage' layout='${message:raw=true}' />
                                </layout>
                        </target>
                    </targets>
                    <rules>
                        <logger name='*' levels='Info' writeTo='debug' />
                    </rules>
                </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            logEventInfo.LoggerName = logger.Name;
            logger.Log(logEventInfo);
            AssertDebugLastMessage("debug", "{ \"LogMessage\": \"{0:X} - Login request from {1} for {2} with userid {0}\" }");

            Assert.Equal("2A - Login request from John for BestApplicationEver with userid 42", logEventInfo.FormattedMessage);

            Assert.Contains(new MessageTemplateParameter("0", 42, "X", CaptureType.Normal), logEventInfo.MessageTemplateParameters);
            Assert.Contains(new MessageTemplateParameter("1", "John", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters);
            Assert.Contains(new MessageTemplateParameter("2", "BestApplicationEver", null, CaptureType.Normal), logEventInfo.MessageTemplateParameters);
            Assert.Contains(new MessageTemplateParameter("0", 42, null, CaptureType.Normal), logEventInfo.MessageTemplateParameters);
        }
示例#7
0
        public static void Init(bool forceInit = false)
        {
            if (!_init || forceInit)
            {
#if NET_CORE
                string nlogConfigPath = Path.Combine(SpiderConsts.BaseDirectory, "nlog.netcore.config");
#else
                string nlogConfigPath = Path.Combine(SpiderConsts.BaseDirectory, "nlog.net45.config");
#endif
                if (!File.Exists(nlogConfigPath))
                {
                    File.AppendAllText(nlogConfigPath, Resource.nlog);
                }
                XmlLoggingConfiguration configuration = new XmlLoggingConfiguration(nlogConfigPath);
                var connectString       = Configuration.GetValue("logAndStatusConnectString");
                var logAndStatusTargets = configuration.AllTargets.Where(t => t.Name == "dblog" || t.Name == "dbstatus").ToList();
                if (!string.IsNullOrEmpty(connectString))
                {
                    foreach (var logAndStatusTarget in logAndStatusTargets)
                    {
                        DatabaseTarget dbTarget = (DatabaseTarget)logAndStatusTarget;
                        dbTarget.ConnectionString = connectString;
                    }
                }

                var needDeleteRules = configuration.LoggingRules.Where(r => r.Targets.Any(t => t is DatabaseTarget && ((DatabaseTarget)t).ConnectionString == null)).ToList();
                foreach (var rule in needDeleteRules)
                {
                    configuration.LoggingRules.Remove(rule);
                }

                configuration.Install(new InstallationContext());
                LogManager.Configuration = configuration;
                _init = true;
            }
        }
示例#8
0
        public void IncludeAllJsonPropertiesMutableNestedXml()
        {
            // Arrange
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
                <targets>
                    <target name='asyncDebug' type='BufferingWrapper'>
                        <target name='debug' type='Debug'>
                            <layout type='JsonLayout'>
                                <attribute name='properties' encode='false' >
                                    <layout type='JsonLayout' IncludeAllProperties='true' ExcludeProperties='Excluded1,Excluded2' />
                                </attribute>
                            </layout>
                        </target>
                    </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='asyncDebug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            // Act
            var logEventInfo      = CreateLogEventWithExcluded();
            var stringPropBuilder = new System.Text.StringBuilder(logEventInfo.Properties["StringProp"].ToString());

            logEventInfo.Properties["StringProp"] = stringPropBuilder;
            logger.Debug(logEventInfo);
            stringPropBuilder.Clear();

            LogManager.Flush();

            // Assert
            AssertDebugLastMessageContains("debug", ExpectedIncludeAllPropertiesWithExcludes);
        }
示例#9
0
        public static void InitLogCenter()
        {
#if !NET_CORE
            string nlogConfigPath = Path.Combine(Env.BaseDirectory, "nlog.net45.config");
#else
            string nlogConfigPath = Path.Combine(Env.BaseDirectory, "nlog.config");
#endif
            if (!File.Exists(nlogConfigPath))
            {
                File.AppendAllText(nlogConfigPath, GetDefaultConfigString());
            }
            XmlLoggingConfiguration configuration = new XmlLoggingConfiguration(nlogConfigPath);

            if (Env.SystemConnectionStringSettings == null)
            {
                var needDeleteRules = configuration.LoggingRules.Where(r => r.Targets.Any(t => t is DatabaseTarget && ((DatabaseTarget)t).ConnectionString == null)).ToList();
                foreach (var rule in needDeleteRules)
                {
                    configuration.LoggingRules.Remove(rule);
                }
                configuration.RemoveTarget("dblog");
            }
            else
            {
                var dblog = configuration.AllTargets.FirstOrDefault(t => t.Name == "dblog");
                if (dblog != null)
                {
                    DatabaseTarget dbTarget = (DatabaseTarget)dblog;
                    dbTarget.ConnectionString = Env.SystemConnectionStringSettings.ConnectionString;
                }
            }

            configuration.Install(new InstallationContext());
            LogManager.Configuration = configuration;
            Logger = GetLogger();
        }
示例#10
0
        public void LayoutCounterTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
           
                <targets><target name='debug' type='Debug' layout='${message} ${counter:sequence=${event-context:item=context1}} ${counter}' /></targets>
                <rules>
                    <logger name='*' minlevel='Info' writeTo='debug' />
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");



            logger.Info().Message("a").Property("context1", "seq1").Write();
            AssertDebugLastMessage("debug", "a 1 1");
            logger.Info().Message("a").Property("context1", "seq1").Write();
            AssertDebugLastMessage("debug", "a 2 2");
            logger.Info().Message("a").Property("context1", "seq2").Write();
            AssertDebugLastMessage("debug", "a 1 3");
            logger.Info().Message("a").Property("context1", "seq1").Write();
            AssertDebugLastMessage("debug", "a 3 4");
        }
示例#11
0
        public void AssignArrayPropertyFromStringWillResultInNotSupportedExceptionSomeWhereDeep()
        {
            // Arrange
            var config = @"
            <nlog throwExceptions='true'>
                <targets>
                  <target name='f' type='File' filename='test.log'>
                    <layout type='CSVLayout' column='a'>
                    </layout>
                  </target>
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='f' />
                </rules>
            </nlog>";

            // Act
            var ex = Assert.Throws <NLogConfigurationException>(() => XmlLoggingConfiguration.CreateFromXmlString(config));

            // Assert
            Assert.IsType <NLogConfigurationException>(ex.InnerException);
            Assert.IsType <NotSupportedException>(ex.InnerException.InnerException);
            Assert.Contains("is an array, and cannot be assigned a scalar value", ex.InnerException.InnerException.Message);
        }
示例#12
0
        public void UpperCaseTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
                <TARGETS><TARGET NAME='DEBUG' TYPE='DEBUG' LAYOUT='${MESSAGE}' /></TARGETS>
                <RULES>
                    <LOGGER NAME='*' MINLEVEL='INFO' APPENDTO='DEBUG'>
                        <FILTERS DEFAULTACTION='LOG'>
                            <WHENCONTAINS LAYOUT='${MESSAGE}' SUBSTRING='msg' ACTION='IGNORE' />
                        </FILTERS>
                    </LOGGER>
                </RULES>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            logger.Debug("msg");
            logger.Info("msg");
            logger.Warn("msg");
            logger.Error("msg");
            logger.Fatal("msg");
            logger.Debug("message");
            AssertDebugCounter("debug", 0);

            logger.Info("message");
            AssertDebugCounter("debug", 1);

            logger.Warn("message");
            AssertDebugCounter("debug", 2);

            logger.Error("message");
            AssertDebugCounter("debug", 3);

            logger.Fatal("message");
            AssertDebugCounter("debug", 4);
        }
示例#13
0
        public void ExceptionWithSeparatorForExistingRender()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>                                        
                    <target name='debug1' type='Debug' layout='${exception:format=tostring,data:separator=\r\nXXX}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug1' />
                </rules>
            </nlog>");

            const string exceptionMessage    = "message for exception";
            const string exceptionDataKey1   = "testkey1";
            const string exceptionDataValue1 = "testvalue1";

            Exception ex = GetExceptionWithoutStackTrace(exceptionMessage);

            ex.Data.Add(exceptionDataKey1, exceptionDataValue1);

            logger.Error(ex);

            AssertDebugLastMessage("debug1", string.Format(ExceptionDataFormat, ex.GetType().FullName, exceptionMessage) + "\r\nXXX" + string.Format(ExceptionDataFormat, exceptionDataKey1, exceptionDataValue1));
        }
示例#14
0
        static LogCenter()
        {
#if !NET_CORE
            string nlogConfigPath = Path.Combine(Environment.BaseDirectory, "nlog.net45.config");
#else
            string nlogConfigPath = Path.Combine(Environment.BaseDirectory, "nlog.config");
#endif
            if (!File.Exists(nlogConfigPath))
            {
                File.AppendAllText(nlogConfigPath, GetDefaultConfigString());
            }
            XmlLoggingConfiguration configuration = new XmlLoggingConfiguration(nlogConfigPath);
            var connectString       = Config.GetValue("connectString");
            var logAndStatusTargets = configuration.AllTargets.Where(t => t.Name == "dblog" || t.Name == "dbstatus").ToList();
            if (!string.IsNullOrEmpty(connectString))
            {
                foreach (var logAndStatusTarget in logAndStatusTargets)
                {
                    DatabaseTarget dbTarget = (DatabaseTarget)logAndStatusTarget;
                    dbTarget.ConnectionString = connectString;
                }
            }
            else
            {
                var needDeleteRules = configuration.LoggingRules.Where(r => r.Targets.Any(t => t is DatabaseTarget && ((DatabaseTarget)t).ConnectionString == null)).ToList();
                foreach (var rule in needDeleteRules)
                {
                    configuration.LoggingRules.Remove(rule);
                }
                configuration.RemoveTarget("dblog");
                configuration.RemoveTarget("dbstatus");
            }

            configuration.Install(new InstallationContext());
            LogManager.Configuration = configuration;
        }
示例#15
0
        public void XmlConfig_attributes_shouldNotLogWarningsToInternalLog(string @namespace)
        {
            // Arrange
            var xml = $@"<?xml version=""1.0"" encoding=""utf-8""?>
<nlog xmlns=""http://www.nlog-project.org/schemas/NLog.xsd"" 
      xmlns:{@namespace}=""http://www.w3.org/2001/XMLSchema-instance"" 
      {@namespace}:schemaLocation=""somewhere"" 
      {@namespace}:type=""asa""
      internalLogToConsole=""true"" internalLogLevel=""Warn"">
</nlog>";


            try
            {
                // ReSharper disable once UnusedVariable
                var factory = ConfigurationItemFactory.Default; // retrieve factory for calling preload and so won't assert those warnings

                TextWriter textWriter = new StringWriter();
                InternalLogger.LogWriter        = textWriter;
                InternalLogger.IncludeTimestamp = false;

                // Act
                XmlLoggingConfiguration.CreateFromXmlString(xml);

                // Assert
                InternalLogger.LogWriter.Flush();

                var warning = textWriter.ToString();
                Assert.Equal("", warning);
            }
            finally
            {
                // cleanup
                InternalLogger.LogWriter = null;
            }
        }
示例#16
0
        public void Can_configure_from_xml_file()
        {
            string configXml = $@"
                <nlog throwConfigExceptions='true'>
                    <extensions>
                        <add type='{typeof(SentryTarget).AssemblyQualifiedName}' />
                    </extensions>
                    <targets>
                        <target type='Sentry' name='sentry' dsn='{ValidDsnWithoutSecret}'>
                            <options>
                                <environment>Development</environment>
                            </options>
                        </target>
                    </targets>
                </nlog>";

            var c = XmlLoggingConfiguration.CreateFromXmlString(configXml);

            var t = c.FindTargetByName("sentry") as SentryTarget;

            Assert.NotNull(t);
            Assert.Equal(ValidDsnWithoutSecret, t.Options.Dsn.ToString());
            Assert.Equal("Development", t.Options.Environment);
        }
示例#17
0
        public void ExceptionNewLineSeparatorTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='debug1' type='Debug' layout='${exception:format=message,shorttype:separator=&#13;&#10;}' />
                </targets>
                <rules>
                    <logger minlevel='Info' writeTo='debug1' />
                </rules>
            </nlog>");

            string    exceptionMessage = "Test exception";
            Exception ex = GetExceptionWithStackTrace(exceptionMessage);

#pragma warning disable 0618
            // Obsolete method requires testing until completely removed.
            logger.ErrorException("msg", ex);
            AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
#pragma warning restore 0618

            logger.Error(ex, "msg");
            AssertDebugLastMessage("debug1", "Test exception\r\n" + typeof(CustomArgumentException).Name);
        }
示例#18
0
        public void APITest()
        {
            // this is mostly to make Clover happy

            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug'>
                    <filters>
                        <whenContains layout='${message}' substring='zzz' action='Ignore' />
                    </filters>
                    </logger>
                </rules>
            </nlog>");

            Assert.True(LogManager.Configuration.LoggingRules[0].Filters[0] is WhenContainsFilter);
            var wcf = (WhenContainsFilter)LogManager.Configuration.LoggingRules[0].Filters[0];

            Assert.IsType <SimpleLayout>(wcf.Layout);
            Assert.Equal("${message}", ((SimpleLayout)wcf.Layout).Text);
            Assert.Equal("zzz", wcf.Substring);
            Assert.Equal(FilterResult.Ignore, wcf.Action);
        }
示例#19
0
        public static LogFactory ConfigureNLog(string application, string configFile = DefaultNLogConfigFile)
        {
            if (string.IsNullOrEmpty(configFile))
            {
                throw new ArgumentNullException(nameof(configFile));
            }

            var file = configFile;

            if (!File.Exists(file))
            {
                file = ResolveSharedFileLocation(configFile);
                if (string.IsNullOrEmpty(file))
                {
                    throw new FileNotFoundException("File not exists.", file);
                }
            }

            var configuration = new XmlLoggingConfiguration(file);

            configuration.Variables["FeiniuBus-Application"] = application;

            return(NLogBuilder.ConfigureNLog(configuration));
        }
示例#20
0
        public void LoggingRule_LevelOff_NotSetAsActualLogLevel()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='l1' type='Debug' layout='${message}' />
                    <target name='l2' type='Debug' layout='${message}' />
                </targets>

                <rules>
                    <logger name='a' level='Off' appendTo='l1' />
                    <logger name='a' minlevel='Debug' appendTo='l2' />
                </rules>
            </nlog>");

            LogManager.Configuration = c;
            LogManager.GetLogger("a");

            Assert.Equal(2, c.LoggingRules.Count);
            Assert.False(c.LoggingRules[0].IsLoggingEnabledForLevel(LogLevel.Off), "Log level Off should always return false.");
            // The two functions below should not throw an exception.
            c.LoggingRules[0].EnableLoggingForLevel(LogLevel.Debug);
            c.LoggingRules[0].DisableLoggingForLevel(LogLevel.Debug);
        }
示例#21
0
        public void LoggingRule_LevelsLayout_ParseLevel(string levelsVariable, LogLevel[] expectedLevels)
        {
            var config = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog>"
                                                                     + (!string.IsNullOrEmpty(levelsVariable) ? $"<variable name='var_levels' value='{levelsVariable}'/>" : "") +
                                                                     @"<targets>
                        <target name='d1' type='Debug' layout='${message}' />
                    </targets>
                    <rules>
                        <logger name='*' levels='${var:var_levels}' writeTo='d1' />
                    </rules>
                </nlog>");

            LogManager.Configuration = config;
            var logger = LogManager.GetLogger(nameof(LoggingRule_LevelsLayout_ParseLevel));

            AssertLogLevelEnabled(logger, expectedLevels);

            // Verify that runtime override also works
            LogManager.Configuration.Variables["var_levels"] = LogLevel.Fatal.ToString();
            LogManager.ReconfigExistingLoggers();

            AssertLogLevelEnabled(logger, LogLevel.Fatal);
        }
示例#22
0
        public void FiltersTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='d1' type='Debug' />
                    <target name='d2' type='Debug' />
                    <target name='d3' type='Debug' />
                    <target name='d4' type='Debug' />
                </targets>

                <rules>
                    <logger name='*' level='Warn' writeTo='d1,d2,d3'>
                        <filters>
                            <when condition=""starts-with(message, 'x')"" action='Ignore' />
                            <when condition=""starts-with(message, 'z')"" action='Ignore' />
                        </filters>
                    </logger>
                </rules>
            </nlog>");

            Assert.Equal(1, c.LoggingRules.Count);
            var rule = c.LoggingRules[0];

            Assert.Equal(2, rule.Filters.Count);
            var conditionBasedFilter = rule.Filters[0] as ConditionBasedFilter;

            Assert.NotNull(conditionBasedFilter);
            Assert.Equal("starts-with(message, 'x')", conditionBasedFilter.Condition.ToString());
            Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);

            conditionBasedFilter = rule.Filters[1] as ConditionBasedFilter;
            Assert.NotNull(conditionBasedFilter);
            Assert.Equal("starts-with(message, 'z')", conditionBasedFilter.Condition.ToString());
            Assert.Equal(FilterResult.Ignore, conditionBasedFilter.Action);
        }
示例#23
0
        public void MultipleTargetsTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='d1' type='Debug' />
                    <target name='d2' type='Debug' />
                    <target name='d3' type='Debug' />
                    <target name='d4' type='Debug' />
                </targets>

                <rules>
                    <logger name='*' level='Warn' writeTo='d1,d2,d3' />
                </rules>
            </nlog>");

            Assert.Equal(1, c.LoggingRules.Count);
            var rule = c.LoggingRules[0];

            Assert.Equal(3, rule.Targets.Count);
            Assert.Same(c.FindTargetByName("d1"), rule.Targets[0]);
            Assert.Same(c.FindTargetByName("d2"), rule.Targets[1]);
            Assert.Same(c.FindTargetByName("d3"), rule.Targets[2]);
        }
示例#24
0
        public void NoLevelsTest()
        {
            LoggingConfiguration c = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets>
                    <target name='d1' type='Debug' />
                </targets>

                <rules>
                    <logger name='*' writeTo='d1' />
                </rules>
            </nlog>");

            Assert.Equal(1, c.LoggingRules.Count);
            var rule = c.LoggingRules[0];

            Assert.Equal(6, rule.Levels.Count);
            Assert.Contains(LogLevel.Trace, rule.Levels);
            Assert.Contains(LogLevel.Debug, rule.Levels);
            Assert.Contains(LogLevel.Info, rule.Levels);
            Assert.Contains(LogLevel.Warn, rule.Levels);
            Assert.Contains(LogLevel.Error, rule.Levels);
            Assert.Contains(LogLevel.Fatal, rule.Levels);
        }
示例#25
0
        public void LowerCaseTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='debug' layout='${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='info' appendto='debug'>
                        <filters defaultAction='log'>
                            <whencontains layout='${message}' substring='msg' action='ignore' />
                        </filters>
                    </logger>
                </rules>
            </nlog>");

            ILogger logger = LogManager.GetLogger("A");

            logger.Debug("msg");
            logger.Info("msg");
            logger.Warn("msg");
            logger.Error("msg");
            logger.Fatal("msg");
            logger.Debug("message");
            AssertDebugCounter("debug", 0);

            logger.Info("message");
            AssertDebugCounter("debug", 1);

            logger.Warn("message");
            AssertDebugCounter("debug", 2);

            logger.Error("message");
            AssertDebugCounter("debug", 3);

            logger.Fatal("message");
            AssertDebugCounter("debug", 4);
        }
示例#26
0
        public void Log4JXmlTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog throwExceptions='true'>
                <targets>
                    <target name='debug' type='Debug' layout='${log4jxmlevent:includeCallSite=true:includeSourceInfo=true:includeNdlc=true:includeMdc=true:IncludeNdc=true:includeMdlc=true:IncludeAllProperties=true:ndcItemSeparator=\:\::includenlogdata=true:loggerName=${logger}}' />
                </targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            MappedDiagnosticsContext.Clear();
            NestedDiagnosticsContext.Clear();

            MappedDiagnosticsContext.Set("foo1", "bar1");
            MappedDiagnosticsContext.Set("foo2", "bar2");

            MappedDiagnosticsLogicalContext.Clear();
            MappedDiagnosticsLogicalContext.Set("foo3", "bar3");

            NestedDiagnosticsLogicalContext.Push("boo1");
            NestedDiagnosticsLogicalContext.Push("boo2");

            NestedDiagnosticsContext.Push("baz1");
            NestedDiagnosticsContext.Push("baz2");
            NestedDiagnosticsContext.Push("baz3");

            ILogger logger       = LogManager.GetLogger("A");
            var     logEventInfo = LogEventInfo.Create(LogLevel.Debug, "A", new Exception("Hello Exception", new Exception("Goodbye Exception")), null, "some message");

            logEventInfo.Properties["nlogPropertyKey"] = "nlogPropertyValue";
            logger.Log(logEventInfo);
            string result        = GetDebugLastMessage("debug");
            string wrappedResult = "<log4j:dummyRoot xmlns:log4j='http://log4j' xmlns:nlog='http://nlog'>" + result + "</log4j:dummyRoot>";

            Assert.NotEqual("", result);
            // make sure the XML can be read back and verify some fields
            StringReader stringReader = new StringReader(wrappedResult);

            var foundsChilds = new Dictionary <string, int>();

            var requiredChilds = new List <string>
            {
                "log4j.event",
                "log4j.message",
                "log4j.NDC",
                "log4j.locationInfo",
                "nlog.locationInfo",
                "log4j.properties",
                "nlog.properties",
                "log4j.throwable",
                "log4j.data",
                "nlog.data",
            };

            using (XmlReader reader = XmlReader.Create(stringReader))
            {
                while (reader.Read())
                {
                    var key     = reader.LocalName;
                    var fullKey = reader.Prefix + "." + key;
                    if (!foundsChilds.ContainsKey(fullKey))
                    {
                        foundsChilds[fullKey] = 0;
                    }
                    foundsChilds[fullKey]++;

                    if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "log4j")
                    {
                        switch (reader.LocalName)
                        {
                        case "dummyRoot":
                            break;

                        case "event":
                            Assert.Equal("DEBUG", reader.GetAttribute("level"));
                            Assert.Equal("A", reader.GetAttribute("logger"));

                            var  epochStart = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);
                            long timestamp  = Convert.ToInt64(reader.GetAttribute("timestamp"));
                            var  time       = epochStart.AddMilliseconds(timestamp);
                            var  now        = DateTime.UtcNow;
                            Assert.True(now.Ticks - time.Ticks < TimeSpan.FromSeconds(3).Ticks);

                            Assert.Equal(Thread.CurrentThread.ManagedThreadId.ToString(), reader.GetAttribute("thread"));
                            break;

                        case "message":
                            reader.Read();
                            Assert.Equal("some message", reader.Value);
                            break;

                        case "NDC":
                            reader.Read();
                            Assert.Equal("baz1::baz2::baz3::boo1 boo2", reader.Value);
                            break;

                        case "locationInfo":
                            Assert.Equal(MethodBase.GetCurrentMethod().DeclaringType.FullName, reader.GetAttribute("class"));
                            Assert.Equal(MethodBase.GetCurrentMethod().ToString(), reader.GetAttribute("method"));
                            break;

                        case "properties":
                            break;

                        case "throwable":
                            reader.Read();
                            Assert.Contains("Hello Exception", reader.Value);
                            Assert.Contains("Goodbye Exception", reader.Value);
                            break;

                        case "data":
                            string name  = reader.GetAttribute("name");
                            string value = reader.GetAttribute("value");

                            switch (name)
                            {
                            case "log4japp":
                                Assert.Equal(AppDomain.CurrentDomain.FriendlyName + "(" + Process.GetCurrentProcess().Id + ")", value);
                                break;

                            case "log4jmachinename":
                                Assert.Equal(Environment.MachineName, value);
                                break;

                            case "foo1":
                                Assert.Equal("bar1", value);
                                break;

                            case "foo2":
                                Assert.Equal("bar2", value);
                                break;

                            case "foo3":
                                Assert.Equal("bar3", value);
                                break;

                            case "nlogPropertyKey":
                                Assert.Equal("nlogPropertyValue", value);
                                break;

                            default:
                                Assert.True(false, "Unknown <log4j:data>: " + name);
                                break;
                            }
                            break;

                        default:
                            throw new NotSupportedException("Unknown element: " + key);
                        }
                        continue;
                    }

                    if (reader.NodeType == XmlNodeType.Element && reader.Prefix == "nlog")
                    {
                        switch (key)
                        {
                        case "eventSequenceNumber":
                            break;

                        case "locationInfo":
                            Assert.Equal(GetType().Assembly.FullName, reader.GetAttribute("assembly"));
                            break;

                        case "properties":
                            break;

                        case "data":
                            var name  = reader.GetAttribute("name");
                            var value = reader.GetAttribute("value");
                            Assert.Equal("nlogPropertyKey", name);
                            Assert.Equal("nlogPropertyValue", value);
                            break;

                        default:
                            throw new NotSupportedException("Unknown element: " + key);
                        }
                    }
                }
            }

            foreach (var required in requiredChilds)
            {
                Assert.True(foundsChilds.ContainsKey(required), $"{required} not found!");
            }
        }
示例#27
0
        public void NDLCTimingTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${ndlc}|${ndlctiming:CurrentScope=false:ScopeBeginTime=true:Format=yyyy-MM-dd HH\:mm\:ss}|${ndlctiming:CurrentScope=false:ScopeBeginTime=false:Format=fff}|${ndlctiming:CurrentScope=true:ScopeBeginTime=true:Format=HH\:mm\:ss.fff}|${ndlctiming:CurrentScope=true:ScopeBeginTime=false:Format=fffffff}|${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            NestedDiagnosticsLogicalContext.Clear();
            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", "|||||0");
            using (NestedDiagnosticsLogicalContext.Push("ala"))
            {
                LogManager.GetLogger("A").Debug("a");
                var measurements = GetDebugLastMessage("debug").Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                Assert.Equal(6, measurements.Length);
                Assert.Equal("ala", measurements[0]);
                Assert.InRange(int.Parse(measurements[2]), 0, 999);
                Assert.InRange(int.Parse(measurements[4]), 0, 9999999);
                Assert.Equal("a", measurements[measurements.Length - 1]);

                System.Threading.Thread.Sleep(10);

                LogManager.GetLogger("A").Debug("b");
                measurements = GetDebugLastMessage("debug").Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                Assert.Equal("ala", measurements[0]);
                Assert.InRange(int.Parse(measurements[2]), 10, 999);
                Assert.InRange(int.Parse(measurements[4]), 100000, 9999999);
                Assert.Equal("b", measurements[measurements.Length - 1]);

                using (NestedDiagnosticsLogicalContext.Push("ma"))
                {
                    LogManager.GetLogger("A").Debug("a");
                    measurements = GetDebugLastMessage("debug").Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                    Assert.Equal(6, measurements.Length);
                    Assert.Equal("ala ma", measurements[0]);
                    Assert.InRange(int.Parse(measurements[2]), 10, 999);
                    Assert.InRange(int.Parse(measurements[4]), 0, 9999999);
                    Assert.Equal("a", measurements[measurements.Length - 1]);

                    System.Threading.Thread.Sleep(10);

                    LogManager.GetLogger("A").Debug("b");
                    measurements = GetDebugLastMessage("debug").Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                    Assert.Equal(6, measurements.Length);
                    Assert.Equal("ala ma", measurements[0]);
                    Assert.InRange(int.Parse(measurements[2]), 20, 999);
                    Assert.InRange(int.Parse(measurements[4]), 100000, 9999999);
                    Assert.Equal("b", measurements[measurements.Length - 1]);
                }

                LogManager.GetLogger("A").Debug("c");
                measurements = GetDebugLastMessage("debug").Split(new[] { '|' }, System.StringSplitOptions.RemoveEmptyEntries);
                Assert.Equal("ala", measurements[0]);
                Assert.InRange(int.Parse(measurements[2]), 20, 999);
                Assert.InRange(int.Parse(measurements[4]), 200000, 9999999);
                Assert.Equal("c", measurements[measurements.Length - 1]);
            }

            LogManager.GetLogger("A").Debug("0");
            AssertDebugLastMessage("debug", "|||||0");
        }
        static Boolean InitLogsWithNLog(String folder)
        {
            String logConfigFileName = "NLogConfiguration.xml";

            String logFileName   = "MultiPlatformApplication"; // File name of the log file
            String suffixWebRtc  = "_WebRTC";
            String suffixArchive = "_{###}";
            String extension     = ".log";

            try
            {
                // Get content of the log file configuration
                String logConfigContent = Helper.GetContentOfEmbeddedResource(logConfigFileName, Encoding.UTF8);

                // Load XML in XMLDocument
                XmlDocument doc = new XmlDocument();
                doc.LoadXml(logConfigContent);

                XmlElement targetElement = doc["nlog"]["targets"];
                var        targetsList   = targetElement.ChildNodes;
                foreach (var target in targetsList)
                {
                    if (target is XmlElement xmlElement)
                    {
                        var name = xmlElement.GetAttribute("name");
                        if (name?.Contains("WEBRTC") == true)
                        {
                            var filename        = Path.Combine(folder, logFileName + suffixWebRtc + extension);
                            var archiveFilename = Path.Combine(folder, logFileName + suffixWebRtc + suffixArchive + extension);
                            xmlElement.SetAttribute("fileName", filename);
                            xmlElement.SetAttribute("archiveFileName", archiveFilename);
                        }
                        else
                        {
                            var filename        = Path.Combine(folder, logFileName + extension);
                            var archiveFilename = Path.Combine(folder, logFileName + suffixArchive + extension);
                            xmlElement.SetAttribute("fileName", filename);
                            xmlElement.SetAttribute("archiveFileName", archiveFilename);
                        }
                    }
                }

                // Create NLog configuration using XML file content
                XmlLoggingConfiguration config = XmlLoggingConfiguration.CreateFromXmlString(doc.OuterXml);
                if (config.InitializeSucceeded == true)
                {
                    // Set NLog configuration
                    NLog.LogManager.Configuration = config;

                    // Create Logger factory
                    var factory = new NLog.Extensions.Logging.NLogLoggerFactory();

                    // Set Logger factory to Rainbow SDK
                    Rainbow.LogFactory.Set(factory);

                    return(true);
                }
            }
            catch { }

            return(false);
        }
示例#29
0
        private void WebserviceTest_httppost_utf8(string bomAttr, bool includeBom)
        {
            var configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
                <nlog>
<targets>
    <target type='WebService'
            name='webservice'
            url='http://*****:*****@"
            encoding='UTF-8'
            methodName='Foo'>
        <parameter name='empty' type='System.String' layout=''/> <!-- work around so the guid is decoded properly -->
        <parameter name='guid' type='System.String' layout='${guid}'/>
        <parameter name='m' type='System.String' layout='${message}'/>
        <parameter name='date' type='System.String' layout='${longdate}'/>
        <parameter name='logger' type='System.String' layout='${logger}'/>
        <parameter name='level' type='System.String' layout='${level}'/>
    </target>
</targets>
                </nlog>");

            var target = configuration.FindTargetByName("webservice") as WebServiceTarget;

            Assert.NotNull(target);

            Assert.Equal(6, target.Parameters.Count);

            Assert.Equal("utf-8", target.Encoding.WebName);

            //async call with mockup stream
            WebRequest webRequest     = WebRequest.Create("http://www.test.com");
            var        httpWebRequest = (HttpWebRequest)webRequest;
            var        streamMock     = new StreamMock();

            //event for async testing
            var counterEvent = new ManualResetEvent(false);

            var parameterValues = new object[] { "", "336cec87129942eeabab3d8babceead7", "Debg", "2014-06-26 23:15:14.6348", "TestClient.Program", "Debug" };

            target.DoInvoke(parameterValues, c => counterEvent.Set(), httpWebRequest,
                            (request, callback) =>
            {
                var t = new Task(() => { });
                callback(t);
                return(t);
            },
                            (request, result) => streamMock);

            counterEvent.WaitOne(10000);

            var bytes = streamMock.bytes;
            var url   = streamMock.stringed;

            const string expectedUrl = "empty=&guid=336cec87129942eeabab3d8babceead7&m=Debg&date=2014-06-26+23%3a15%3a14.6348&logger=TestClient.Program&level=Debug";

            Assert.Equal(expectedUrl, url);

            Assert.True(bytes.Length > 3);

            //not bom
            var possbleBomBytes = bytes.Take(3).ToArray();

            if (includeBom)
            {
                Assert.Equal(possbleBomBytes, EncodingHelpers.Utf8BOM);
            }
            else
            {
                Assert.NotEqual(possbleBomBytes, EncodingHelpers.Utf8BOM);
            }

            Assert.Equal(bytes.Length, includeBom ? 126 : 123);
        }
示例#30
0
        public void IdentityTest1Async()
        {
            var oldPrincipal = Thread.CurrentPrincipal;


            try
            {
                ConfigurationItemFactory.Default.Targets
                .RegisterDefinition("CSharpEventTarget", typeof(CSharpEventTarget));


                LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"<?xml version='1.0' encoding='utf-8' ?>
<nlog xmlns='http://www.nlog-project.org/schemas/NLog.xsd'
      xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'
 
      internalLogLevel='Debug'
      throwExceptions='true' >

  <targets async='true'>
    <target name='target1' xsi:type='CSharpEventTarget' layout='${identity}' />
  </targets>

  <rules>
    <logger name='*' writeTo='target1' />
  </rules>
</nlog>
");

                try
                {
                    var          continuationHit = new ManualResetEvent(false);
                    string       rendered        = null;
                    var          threadId        = Thread.CurrentThread.ManagedThreadId;
                    var          asyncThreadId   = threadId;
                    LogEventInfo lastLogEvent    = null;

                    var asyncTarget = LogManager.Configuration.FindTargetByName <AsyncTargetWrapper>("target1");
                    Assert.NotNull(asyncTarget);
                    var target = asyncTarget.WrappedTarget as CSharpEventTarget;
                    Assert.NotNull(target);
                    target.BeforeWrite += (logevent, rendered1, asyncThreadId1) =>
                    {
                        //clear in current thread before write
                        Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("ANOTHER user", "type"), null);
                    };

                    target.EventWritten += (logevent, rendered1, asyncThreadId1) =>
                    {
                        rendered      = rendered1;
                        asyncThreadId = asyncThreadId1;
                        lastLogEvent  = logevent;
                        continuationHit.Set();
                    };


                    Thread.CurrentPrincipal = new GenericPrincipal(new GenericIdentity("SOMEDOMAIN\\SomeUser", "CustomAuth"), new[] { "Role1", "Role2" });

                    var logger = LogManager.GetCurrentClassLogger();
                    logger.Debug("test write");


                    Assert.True(continuationHit.WaitOne());
                    Assert.NotNull(lastLogEvent);
                    //should be written in another thread.
                    Assert.NotEqual(threadId, asyncThreadId);


                    Assert.Equal("auth:CustomAuth:SOMEDOMAIN\\SomeUser", rendered);
                }
                finally
                {
                    LogManager.Configuration.Close();
                }
            }
            finally
            {
                InternalLogger.Reset();
                Thread.CurrentPrincipal = oldPrincipal;
            }
        }
示例#31
0
        /// <summary>
        /// Initialize the logging environment for Azure; including
        /// automatically rewriting log file paths for compatibility with
        /// local storage and setting up private variables.
        /// </summary>
        public void InitializeForCloud()
        {
            // Attach the diagnostic monitor trace listener to the list of master
            // System.Diagnostics trace listeners
            Trace.Listeners.Clear();
            if (RoleEnvironment.IsAvailable)
                Trace.Listeners.Add(new DiagnosticMonitorTraceListener());
            else
                Trace.Listeners.Add(new DefaultTraceListener());
            Trace.WriteLine("Initializing NLog configuration for Azure");

            // Replace log file and role name settings in the configuration
            var currentCfg = LogManager.Configuration;

            if (currentCfg == null)
            {
                // Depending on the deployment environment (i.e. Azure emulator) the NLog library
                // may not properly auto-load the NLog.config file.
                var binDirectory = new Uri(
                    System.IO.Path.GetDirectoryName(
                    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath;
                var configFile = Path.Combine(binDirectory, "NLog.config");

                // Check for NLog.config in the local directory.
                if (File.Exists(configFile))
                {
                    var newConfig = new XmlLoggingConfiguration(configFile);
                    LogManager.Configuration = newConfig;
                    currentCfg = LogManager.Configuration;
                }
                else
                {
                    // Set basic configuration and log the error
                    var localPath = System.IO.Path.GetTempPath();
                    var logDirPath = Path.Combine(localPath, "logs");
                    global::NLog.Config.SimpleConfigurator.ConfigureForFileLogging(
                        Path.Combine(logDirPath, "ApplicationLog.log"));
                    System.Diagnostics.Trace.TraceWarning("Warning: no NLog configuration section found in web.config or NLog.config; falling back to basic configuration");
                    return;
                }
            }

            Trace.WriteLine("Resetting NLog configuration");
            UpdateConfigForCloud(currentCfg);
            LogManager.Configuration = currentCfg;
        }