コード例 #1
0
        private static void LogMessage(string text, int sequence)
        {
            MappedDiagnosticsContext.Set("UnitTest", $"Sequence = {sequence}");

            var randomType = Random.Next(0, 6);

            switch (randomType)
            {
            case 0:
                Log.Error(text);
                break;

            case 1:
                Log.Fatal(text);
                break;

            case 2:
                Log.Info(text);
                break;

            case 3:
                Log.Warn(text);
                break;

            case 4:
                Log.Trace(text);
                break;

            default:
                Log.Debug(text);
                break;
            }

            MappedDiagnosticsContext.Remove("UnitTest");
        }
コード例 #2
0
ファイル: Provider.cs プロジェクト: daitkar/CFM
 protected override OpenMdc GetOpenMdcMethod()
 {
     return((key, value) =>
     {
         MappedDiagnosticsContext.Set(key, value);
         return new DisposableAction(() => MappedDiagnosticsContext.Remove(key));
     });
 }
コード例 #3
0
ファイル: LogBuilderTest.cs プロジェクト: niemyjski/NLog.Xml
        public void InfoContextWrite()
        {
            MappedDiagnosticsContext.Set("Global", "true");

            _logger.Info()
            .Message("This is a test Mapped Diagnostics Context fluent message.")
            .Property("Test", "InfoWrite")
            .Write();

            MappedDiagnosticsContext.Remove("Global");
        }
コード例 #4
0
        public void MDCTest1()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 500;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MappedDiagnosticsContext.Clear();
                        Assert.IsFalse(MappedDiagnosticsContext.Contains("foo"));
                        Assert.AreEqual(string.Empty, MappedDiagnosticsContext.Get("foo"));
                        Assert.IsFalse(MappedDiagnosticsContext.Contains("foo2"));
                        Assert.AreEqual(string.Empty, MappedDiagnosticsContext.Get("foo2"));

                        MappedDiagnosticsContext.Set("foo", "bar");
                        MappedDiagnosticsContext.Set("foo2", "bar2");

                        Assert.IsTrue(MappedDiagnosticsContext.Contains("foo"));
                        Assert.AreEqual("bar", MappedDiagnosticsContext.Get("foo"));

                        MappedDiagnosticsContext.Remove("foo");
                        Assert.IsFalse(MappedDiagnosticsContext.Contains("foo"));
                        Assert.AreEqual(string.Empty, MappedDiagnosticsContext.Get("foo"));

                        Assert.IsTrue(MappedDiagnosticsContext.Contains("foo2"));
                        Assert.AreEqual("bar2", MappedDiagnosticsContext.Get("foo2"));
                    }
                    catch (Exception exception)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(exception);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            Assert.AreEqual(0, exceptions.Count);
        }
コード例 #5
0
        static void Main(string[] args)
        {
            MappedDiagnosticsContext.Set("order-number", 1024.ToString());
            Logger.Info("Message before a trace.");

            using (var scope = Tracer.Instance.StartActive("NLog45Example - Main()"))
            {
                Logger.Info("Message during a trace.");
            }

            Logger.Info("Message after a trace.");
            MappedDiagnosticsContext.Remove("order-number");
        }
コード例 #6
0
        public static void Main(string[] args)
        {
            // Obtain the automatically registered OpenTracing.Util.GlobalTracer instance
            var tracer = GlobalTracer.Instance;

            MappedDiagnosticsContext.Set("order-number", 1024.ToString());
            Logger.Info("Message before a trace.");

            using (var scope = tracer.BuildSpan("NLog45Example - Main()").StartActive(finishSpanOnDispose: true))
            {
                Logger.Info("Message during a trace.");
            }

            Logger.Info("Message after a trace.");
            MappedDiagnosticsContext.Remove("order-number");
        }
コード例 #7
0
ファイル: CommandExecutor.cs プロジェクト: z00nx/Sonarr
        private void ExecuteCommand <TCommand>(Command command) where TCommand : Command
        {
            var handlerContract = typeof(IExecute <>).MakeGenericType(command.GetType());
            var handler         = (IExecute <TCommand>)_serviceFactory.Build(handlerContract);

            _logger.Trace("{0} -> {1}", command.GetType().Name, handler.GetType().Name);

            try
            {
                _trackCommands.Start(command);
                BroadcastCommandUpdate(command);

                if (!MappedDiagnosticsContext.Contains("CommandId") && command.SendUpdatesToClient)
                {
                    MappedDiagnosticsContext.Set("CommandId", command.Id.ToString());
                }

                handler.Execute((TCommand)command);

                if (command.State == CommandStatus.Running)
                {
                    _trackCommands.Completed(command);
                }
            }
            catch (Exception e)
            {
                _trackCommands.Failed(command, e);
                throw;
            }
            finally
            {
                BroadcastCommandUpdate(command);
                _eventAggregator.PublishEvent(new CommandExecutedEvent(command));

                if (MappedDiagnosticsContext.Get("CommandId") == command.Id.ToString())
                {
                    MappedDiagnosticsContext.Remove("CommandId");
                }
            }

            _logger.Trace("{0} <- {1} [{2}]", command.GetType().Name, handler.GetType().Name, command.Runtime.ToString(""));
        }
コード例 #8
0
        public void MDCTest()
        {
            LogManager.Configuration = XmlLoggingConfiguration.CreateFromXmlString(@"
            <nlog>
                <targets><target name='debug' type='Debug' layout='${mdc:item=myitem} ${message}' /></targets>
                <rules>
                    <logger name='*' minlevel='Debug' writeTo='debug' />
                </rules>
            </nlog>");

            MappedDiagnosticsContext.Clear();
            MappedDiagnosticsContext.Set("myitem", "myvalue");
            LogManager.GetLogger("A").Debug("a");
            AssertDebugLastMessage("debug", "myvalue a");

            MappedDiagnosticsContext.Set("myitem", "value2");
            LogManager.GetLogger("A").Debug("b");
            AssertDebugLastMessage("debug", "value2 b");

            MappedDiagnosticsContext.Remove("myitem");
            LogManager.GetLogger("A").Debug("c");
            AssertDebugLastMessage("debug", " c");
        }
コード例 #9
0
        public void MDCTest1()
        {
            List <Exception> exceptions = new List <Exception>();
            ManualResetEvent mre        = new ManualResetEvent(false);
            int counter   = 100;
            int remaining = counter;

            for (int i = 0; i < counter; ++i)
            {
                ThreadPool.QueueUserWorkItem(
                    s =>
                {
                    try
                    {
                        MappedDiagnosticsContext.Clear();
                        Assert.False(MappedDiagnosticsContext.Contains("foo"));
                        Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));
                        Assert.False(MappedDiagnosticsContext.Contains("foo2"));
                        Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo2"));
                        Assert.Equal(0, MappedDiagnosticsContext.GetNames().Count);

                        MappedDiagnosticsContext.Set("foo", "bar");
                        MappedDiagnosticsContext.Set("foo2", "bar2");

                        Assert.True(MappedDiagnosticsContext.Contains("foo"));
                        Assert.Equal("bar", MappedDiagnosticsContext.Get("foo"));
                        Assert.Equal(2, MappedDiagnosticsContext.GetNames().Count);

                        MappedDiagnosticsContext.Remove("foo");
                        Assert.False(MappedDiagnosticsContext.Contains("foo"));
                        Assert.Equal(string.Empty, MappedDiagnosticsContext.Get("foo"));

                        Assert.True(MappedDiagnosticsContext.Contains("foo2"));
                        Assert.Equal("bar2", MappedDiagnosticsContext.Get("foo2"));

                        Assert.Equal(1, MappedDiagnosticsContext.GetNames().Count);
                        Assert.True(MappedDiagnosticsContext.GetNames().Contains("foo2"));

                        Assert.Null(MappedDiagnosticsContext.GetObject("foo3"));
                        MappedDiagnosticsContext.Set("foo3", new { One = 1 });
                    }
                    catch (Exception exception)
                    {
                        lock (exceptions)
                        {
                            exceptions.Add(exception);
                        }
                    }
                    finally
                    {
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            mre.Set();
                        }
                    }
                });
            }

            mre.WaitOne();
            StringBuilder exceptionsMessage = new StringBuilder();

            foreach (var ex in exceptions)
            {
                if (exceptionsMessage.Length > 0)
                {
                    exceptionsMessage.Append("\r\n");
                }

                exceptionsMessage.Append(ex.ToString());
            }

            Assert.True(exceptions.Count == 0, exceptionsMessage.ToString());
        }
コード例 #10
0
 public static void Clear()
 {
     MappedDiagnosticsContext.Remove(TagologContextParamName);
 }
コード例 #11
0
ファイル: Program.cs プロジェクト: KernelA/control-task
        private static void SolveFW(INamedMOProblem Problem, string PathToOutDir, int MaxRun)
        {
            MappedDiagnosticsContext.Set("thread_id", $"_{Thread.CurrentThread.ManagedThreadId}_");

            Logger logger = LogManager.GetLogger("Main");

            const int numParams = 6;

            object[][] parameters =
            {
                //new object[numParams] {250, 600, 10, 20, 30, 1.1},
                new object[numParams] {
                    300, 700, 20, 8, 15, 0.025
                },
                new object[numParams] {
                    300, 1000, 25, 8, 17, 0.05
                },
                new object[numParams] {
                    400, 900, 15, 8, 12, 0.1
                },
                new object[numParams] {
                    350, 750, 20, 10, 19, 0.15
                }
            };

            string pathToXml = Path.Combine(PathToOutDir, $"{Problem.Name}_res.xml");

            logger.Info($"Open a xml file. '{pathToXml}'");

            var normalGen = new NormalGen();
            var contGen   = new ContGen();

            MOFWOptimizer opt = new MOFWOptimizer(contGen, normalGen);

            using (XmlWriter writer = XmlWriter.Create(pathToXml))
            {
                writer.WriteStartDocument();
                writer.WriteStartElement("Problem");

                Dictionary <string, string> problemDesc = new Dictionary <string, string>
                {
                    ["Name"]   = Problem.Name,
                    ["DimDec"] = Problem.LowerBounds.Count.ToString(),
                    ["DimObj"] = Problem.CountObjs.ToString(),
                };

                foreach (var name in problemDesc)
                {
                    writer.WriteAttributeString(name.Key, name.Value);
                }

                writer.WriteStartElement("Bounds");

                foreach (var bound in Problem.LowerBounds.Zip(Problem.UpperBounds, (low, upp) => (Lower: low, Upper: upp)))
                {
                    writer.WriteStartElement("Bound");
                    writer.WriteAttributeString("LowerB", bound.Lower.ToString());
                    writer.WriteAttributeString("UpperB", bound.Upper.ToString());
                    writer.WriteEndElement();
                }

                writer.WriteEndElement();

                logger.Info("Start solving with MOFW.");

                foreach (var par in Enumerable.Range(0, parameters.Length).Zip(parameters, (num, par) => (Num: num, Parameters: par)))
                {
                    logger.Info($"Try to find solution with {par.Num}th configuration of {parameters.Length}");

                    writer.WriteStartElement("Experiment");
                    writer.WriteStartElement("OptParams");

                    FWParams pars = CreateParams <FWParams>(par.Parameters);

                    var paramsType = pars.GetType();

                    foreach (var prop in paramsType.GetProperties())
                    {
                        if (prop.PropertyType == typeof(bool))
                        {
                            continue;
                        }

                        writer.WriteStartElement("Param");
                        writer.WriteAttributeString(prop.Name, prop.GetValue(pars).ToString());
                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();

                    writer.WriteStartElement("Runs");

                    for (int i = 0; i < MaxRun; i++)
                    {
                        logger.Info($"Run {i} of {MaxRun}");

                        writer.WriteStartElement("Run");

                        try
                        {
                            opt.Minimize(pars, Problem);

                            writer.WriteStartElement("Decisions");

                            foreach (var agent in opt.ParetoFront)
                            {
                                writer.WriteStartElement("Point");

                                for (int coordIndex = 0; coordIndex < agent.Point.Count; coordIndex++)
                                {
                                    writer.WriteAttributeString($"x{coordIndex + 1}", agent.Point[coordIndex].ToString());
                                }

                                writer.WriteEndElement();
                            }

                            writer.WriteEndElement();

                            writer.WriteStartElement("Targets");

                            foreach (var agent in opt.ParetoFront)
                            {
                                writer.WriteStartElement("Target");

                                for (int coordIndex = 0; coordIndex < agent.Objs.Count; coordIndex++)
                                {
                                    writer.WriteAttributeString($"F{coordIndex + 1}", agent.Objs[coordIndex].ToString());
                                }

                                writer.WriteEndElement();
                            }

                            writer.WriteEndElement();
                        }
                        catch (Exception exc)
                        {
                            logger.Error(exc, "Error was in optimization process.");
                            logger.Info("Recreate optimization method.");
                            opt = new MOFWOptimizer();
                            logger.Info($"Skip run {i}.");
                        }

                        writer.WriteEndElement();
                    }

                    writer.WriteEndElement();
                    writer.WriteEndElement();
                }
            }
            logger.Info("Close a xml file.");

            MappedDiagnosticsContext.Remove("thread_id");
        }
コード例 #12
0
        public void LoggerIncludesPropertiesInLog()
        {
            var formatter   = LogSettingsHelper.GetFormatter();
            var sink        = new NLogHelper.TestSink();
            var target      = NLogHelper.CreateTarget(sink, DirectSubmissionLogLevel.Debug);
            var targetProxy = NLogCommon <LoggingConfiguration> .CreateNLogTargetProxy(target);

            var config = new LoggingConfiguration();

            NLogHelper.AddTargetToConfig(config, targetProxy);

            var logFactory = new LogFactory(config);
            var logger     = logFactory.GetLogger(nameof(LoggerIncludesPropertiesInLog));

            // We don't currently record NDC/NDLC
#if NLOG_45
            var messageTemplate = "This is a message with {Value}";
#else
            var messageTemplate = "This is a message with {0}";
#endif
            var mdcKey   = "some mdcKey";
            var mdcValue = "some mdcValue";
#if !NLOG_2
            var mdclKey   = "some mdclKey";
            var mdclValue = "some mdclValue";
#endif
            // var nestedScope = "some nested name";
            // var nestedDictionary = new Dictionary<string, object> { { "nlcKey", 657 } };
            // var dictValues = nestedDictionary.First();
            try
            {
                MappedDiagnosticsContext.Set(mdcKey, mdcValue);
#if !NLOG_2
                MappedDiagnosticsLogicalContext.Set(mdclKey, mdclValue);
#endif
                logger.Error(messageTemplate, 123);
            }
            finally
            {
                MappedDiagnosticsContext.Remove(mdcKey);
#if !NLOG_2
                MappedDiagnosticsLogicalContext.Remove(mdclKey);
#endif
            }

            var logEvent = sink.Events.Should().ContainSingle().Subject;

            // get the rendered log
            var sb = new StringBuilder();
            logEvent.Format(sb, formatter);
            var log = sb.ToString();

            log.Should()
            .Contain("This is a message with 123")
            .And.Contain(mdcKey)
            .And.Contain(mdcValue)
#if !NLOG_2
            .And.Contain(mdclKey)
            .And.Contain(mdclValue)
#endif
            // .And.Contain(nestedScope)
            // .And.Contain(dictValues.Key)
            // .And.Contain(dictValues.Value.ToString())
            .And.Contain(DirectSubmissionLogLevelExtensions.Error);
        }