Ejemplo n.º 1
0
        public void LinkClickTest()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout       = "${rtb-link:inner=link}",
                ToolWindow   = false,
                Width        = 300,
                Height       = 200,
                SupportLinks = true
            };

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            logger.Info("Test");

            //   Application.DoEvents();

            Assert.Same(target, RichTextBoxTarget.GetTargetByControl(target.TargetRichTextBox));
            //  Assert.Contains("link", target.TargetRichTextBox.Text);

            bool         linkClickedFromHandler = false;
            string       linkTextFromHandler    = null;
            LogEventInfo logEventFromHandler    = null;

            RichTextBoxTarget.DelLinkClicked clickHandler = (RichTextBoxTarget sender, string linkText, LogEventInfo logEvent) =>
            {
                //actual checks moved to main code to make exceptions caught by the test runner.
                linkClickedFromHandler = true;
                linkTextFromHandler    = linkText;
                logEventFromHandler    = logEvent;
                target.TargetForm.Close();
            };

            RichTextBoxTarget.GetTargetByControl(target.TargetRichTextBox).LinkClicked += clickHandler;

            //simulate clicking on a link
            //Task.Run(() =>
            //{
            //    for (int i = 0; i < 3; ++i) //needs a number of clicks. Probably - to make application focused, form focused, and finally link clicked.
            //    {
            //        InvokeLambda(target.TargetRichTextBox, () =>
            //        {
            //            Point scrPoint = target.TargetRichTextBox.PointToScreen(new Point(5, 5));
            //            LeftMouseClick(scrPoint.X, scrPoint.Y);
            //        });
            //    }
            //});

            //in case link does not click, this would hang up infinitely;
            //    Application.Run(target.TargetForm);

            Assert.True(linkClickedFromHandler); //check that we have actually clicked on a link, not just missed anything
            Assert.True("link" == linkTextFromHandler);
            Assert.True("Test" == logEventFromHandler.Message);
        }
Ejemplo n.º 2
0
        public void Setup()
        {
            mLogs = new MemoryTarget {
                Layout = @"${date:format=HH\:mm\:ss} ${logger} ${message}"
            };
            SimpleConfigurator.ConfigureForTargetLogging(mLogs, LogLevel.Debug);

            mLogger = LogManager.GetLogger("Tests");
            Contracts.Dependencies.Injection.RegisterLogger(mLogger);
        }
Ejemplo n.º 3
0
        public void WrongMyTargetShouldNotThrowExceptionWhenThrowExceptionsIsFalse()
        {
            var target = new WrongMyTarget();

            LogManager.ThrowExceptions = false;
            SimpleConfigurator.ConfigureForTargetLogging(target);
            var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");

            logger.Info("Testing");
        }
Ejemplo n.º 4
0
        public void SimpleRichTextBoxTargetTest()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = "${level} ${logger} ${message}",
                ToolWindow = false,
                Width      = 300,
                Height     = 200,
            };

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            logger.Fatal("Test");
            logger.Error("Foo");
            logger.Warn("Bar");
            logger.Info("Test");
            logger.Debug("Foo");
            logger.Trace("Bar");

            Application.DoEvents();

            var form = target.TargetForm;

            Assert.IsTrue(target.CreatedForm);
            Assert.IsTrue(form.Name.StartsWith("NLog"));
            Assert.AreEqual(FormWindowState.Normal, form.WindowState);
            Assert.AreEqual("NLog", form.Text);
            Assert.AreEqual(300, form.Width);
            Assert.AreEqual(200, form.Height);

            MemoryStream ms = new MemoryStream();

            target.TargetRichTextBox.SaveFile(ms, RichTextBoxStreamType.RichText);
            string rtfText = Encoding.UTF8.GetString(ms.GetBuffer());

            Assert.IsTrue(target.CreatedForm);

            string expectedRtf = @"{\colortbl ;\red255\green255\blue255;\red255\green0\blue0;\red255\green165\blue0;\red0\green0\blue0;\red128\green128\blue128;\red169\green169\blue169;}
\viewkind4\uc1\pard\cf1\highlight2\b\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par
\cf2\highlight1\i Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par
\cf3\ul\b0\i0 Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par
\cf4\ulnone Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par
\cf5 Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par
\cf6\i Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par
\cf0\highlight0\i0\f1\par
}";

            Assert.IsTrue(rtfText.Contains(expectedRtf), "Invalid RTF: " + rtfText);

            LogManager.Configuration = null;
            Assert.IsNull(target.TargetForm);
            Application.DoEvents();
            Assert.IsTrue(form.IsDisposed);
        }
Ejemplo n.º 5
0
        public void BufferedMultiFileWrite()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                var ft = new FileTarget
                {
                    FileName   = Path.Combine(tempPath, "${level}.txt"),
                    LineEnding = LineEndingMode.LF,
                    Layout     = "${message}"
                };

                SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 10), LogLevel.Debug);

                for (var i = 0; i < 250; ++i)
                {
                    logger.Trace("@@@");
                    logger.Debug("aaa");
                    logger.Info("bbb");
                    logger.Warn("ccc");
                    logger.Error("ddd");
                    logger.Fatal("eee");
                }

                LogManager.Configuration = null;

                Assert.False(File.Exists(Path.Combine(tempPath, "Trace.txt")));

                AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
                                   StringRepeat(250, "aaa\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Info.txt"),
                                   StringRepeat(250, "bbb\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
                                   StringRepeat(250, "ccc\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Error.txt"),
                                   StringRepeat(250, "ddd\n"), Encoding.UTF8);

                AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
                                   StringRepeat(250, "eee\n"), Encoding.UTF8);
            }
            finally
            {
                //if (File.Exists(tempFile))
                //    File.Delete(tempFile);
                LogManager.Configuration = null;
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
Ejemplo n.º 6
0
        public void MultiFileWrite()
        {
            // create the file in a not-existent
            // directory which forces creation
            string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());

            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName   = Path.Combine(tempPath, "${level}.txt");
                ft.LineEnding = FileTarget.LineEndingMode.LF;
                ft.Layout     = "${message}";

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                for (int i = 0; i < 250; ++i)
                {
                    logger.Trace("@@@");
                    logger.Debug("aaa");
                    logger.Info("bbb");
                    logger.Warn("ccc");
                    logger.Error("ddd");
                    logger.Fatal("eee");
                }

                LogManager.Configuration = null;

                Assert.IsFalse(File.Exists(Path.Combine(tempPath, "Trace.txt")));

                AssertFileContents(Path.Combine(tempPath, "Debug.txt"),
                                   StringRepeat(250, "aaa\n"), Encoding.ASCII);

                AssertFileContents(Path.Combine(tempPath, "Info.txt"),
                                   StringRepeat(250, "bbb\n"), Encoding.ASCII);

                AssertFileContents(Path.Combine(tempPath, "Warn.txt"),
                                   StringRepeat(250, "ccc\n"), Encoding.ASCII);

                AssertFileContents(Path.Combine(tempPath, "Error.txt"),
                                   StringRepeat(250, "ddd\n"), Encoding.ASCII);

                AssertFileContents(Path.Combine(tempPath, "Fatal.txt"),
                                   StringRepeat(250, "eee\n"), Encoding.ASCII);
            }
            finally
            {
                //if (File.Exists(tempFile))
                //    File.Delete(tempFile);
                LogManager.Configuration = null;
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
Ejemplo n.º 7
0
 public void WrongMyTargetShouldThrowException()
 {
     Assert.Throws <NLogRuntimeException>(() =>
     {
         var target = new WrongMyTarget();
         LogManager.ThrowExceptions = true;
         SimpleConfigurator.ConfigureForTargetLogging(target);
         var logger = LogManager.GetLogger("WrongMyTargetShouldThrowException");
         logger.Info("Testing");
     });
 }
Ejemplo n.º 8
0
        public NLogTracerWriterTests()
        {
            // setup writer under test
            _writer = new NLogTraceWriter();

            // setup debug logging target
            _debugTarget = new DebugTarget {
                Layout = "${message}"
            };
            SimpleConfigurator.ConfigureForTargetLogging(_debugTarget, LogLevel.Info);
        }
Ejemplo n.º 9
0
        public void WriteFormattedStringEvent_WithNullArgument()
        {
            var target = new MyTarget();

            SimpleConfigurator.ConfigureForTargetLogging(target);
            var    logger = LogManager.GetLogger("WriteFormattedStringEvent_EventWithNullArguments");
            string t      = null;

            logger.Info("Testing null:{0}", t);
            Assert.Equal(1, target.WriteCount);
        }
Ejemplo n.º 10
0
        // ReSharper disable DoNotCallOverridableMethodsInConstructor
        protected BehaviourTestBase()
        {
            ExceptionMode = ExceptionMode.Throw;
            LoggingTarget = ConfigureLoggingTarget();
            LogLevel      = ConfigureLogLevel();
            SimpleConfigurator.ConfigureForTargetLogging(LoggingTarget, LogLevel);
            Log = LogManager.GetCurrentClassLogger();

            Fixture = new Fixture();
            CustomizeAutoFixture(Fixture);
        }
Ejemplo n.º 11
0
        public void CustomWordRowColoringTest()
        {
            try
            {
                RichTextBoxTarget target = new RichTextBoxTarget()
                {
                    ControlName       = "Control1",
                    Layout            = "${level} ${logger} ${message}",
                    ShowMinimized     = true,
                    ToolWindow        = false,
                    WordColoringRules =
                    {
                        new RichTextBoxWordColoringRule("zzz", "Red",   "Empty"),
                        new RichTextBoxWordColoringRule("aaa", "Green", "Empty"),
                    }
                };

                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                logger.Fatal("Test zzz");
                logger.Error("Foo xxx");
                logger.Warn("Bar yyy");
                logger.Info("Test aaa");
                logger.Debug("Foo zzz");
                logger.Trace("Bar ccc");

                Application.DoEvents();

                var form = target.TargetForm;

                MemoryStream ms = new MemoryStream();
                target.TargetRichTextBox.SaveFile(ms, RichTextBoxStreamType.RichText);
                string rtfText = Encoding.UTF8.GetString(ms.GetBuffer());

                Assert.IsTrue(target.CreatedForm);

                // "zzz" string will be highlighted

                string expectedRtf = @"{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red255\green0\blue0;\red0\green128\blue0;}
\viewkind4\uc1\pard\cf1\highlight2\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf3\f1 zzz\cf1\f0\par
Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo xxx\par
Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar yyy\par
Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf4\f1 aaa\cf1\f0\par
Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo \cf3\f1 zzz\cf1\f0\par
Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar ccc\par
\cf0\highlight0\f1\par
}";
                Assert.IsTrue(rtfText.Contains(expectedRtf), "Invalid RTF: " + rtfText);
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
Ejemplo n.º 12
0
        public BaseTest()
        {
            ConsoleTarget target = new ConsoleTarget();

            target.Layout = "${time}|${level:uppercase=true}|${callsite:className=true:includeSourcePath=false:methodName=false}|${message}";

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

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

            logger.Debug("another log message");
        }
        public void ManualRegisterTestWithRetentionOnlyMissed()
        {
            var config = new LoggingConfiguration();
            var target = new RichTextBoxTarget()
            {
                FormName    = "MyForm1",
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout = "${message}",
                AllowAccessoryFormCreation = false,
                MaxLines         = 10,
                MessageRetention = RichTextBoxTargetMessageRetentionStrategy.OnlyMissed
            };

            LogManager.ThrowExceptions = true;
            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            logger.Trace("Accessory Form");
            Application.DoEvents();

            Assert.False(target.CreatedForm);
            Assert.Null(target.TargetForm);
            Assert.Null(target.TargetRichTextBox);

            using (Form form = new Form())
            {
                form.Name = "MyForm1";
                //with minimized forms textbox is created with width of 0, so texts get trimmed and result.Contains() fails
                //form.WindowState = FormWindowState.Minimized;
                form.Width = 600;
                RichTextBox rtb = new RichTextBox();
                rtb.Dock = DockStyle.Fill;
                rtb.Name = "Control1";
                form.Controls.Add(rtb);
                form.Show();
                form.Activate();

                RichTextBoxTarget.ReInitializeAllTextboxes(form);

                logger.Trace("Normal Form");

                Application.DoEvents();

                Assert.False(target.CreatedForm);
                Assert.Same(form, target.TargetForm);
                Assert.Same(rtb, target.TargetRichTextBox);

                string result = ExtractRtf(target.TargetRichTextBox);

                Assert.Contains(@"Accessory Form", result);
                Assert.Contains(@"Normal Form", result);
            }
        }
        private void InitializeLogger(LogLevel minLevel)
        {
            if (logger != null)
            {
                logger.Dispose();
            }

            logger = new MemoryTarget {
                Layout = "${message}"
            };
            SimpleConfigurator.ConfigureForTargetLogging(logger, minLevel);
        }
Ejemplo n.º 15
0
        public void Test1()
        {
            var logger = LogManager.GetLogger("Aaa");
            var target = new LogReceiverWebServiceTarget();

            target.EndpointAddress = "http://notimportant:9999/";
            target.Parameters.Add(new MethodCallParameter("message", "${message}"));
            target.Parameters.Add(new MethodCallParameter("date", "${longdate}"));

            SimpleConfigurator.ConfigureForTargetLogging(target);
            logger.Info("aa");
        }
Ejemplo n.º 16
0
        public void SimpleRichTextBoxTargetTest()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = "${level} ${logger} ${message}",
                ToolWindow = false,
                Width      = 300,
                Height     = 200,
            };

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            logger.Fatal("Test");
            logger.Error("Foo");
            logger.Warn("Bar");
            logger.Info("Test");
            logger.Debug("Foo");
            logger.Trace("Bar");

            Application.DoEvents();

            var form = target.TargetForm;

            Assert.True(target.CreatedForm);
            Assert.True(form.Name.StartsWith("NLog"));
            Assert.Equal(FormWindowState.Normal, form.WindowState);
            Assert.Equal("NLog", form.Text);
            Assert.Equal(300, form.Width);
            Assert.Equal(200, form.Height);

            string rtfText = ExtractRtf(target.TargetRichTextBox);

            Assert.True(target.CreatedForm);

            var result = rtfText;

            Assert.True(result.Contains(@"{\colortbl ;\red255\green255\blue255;\red255\green0\blue0;\red255\green165\blue0;\red0\green0\blue0;\red128\green128\blue128;\red169\green169\blue169;}"));
            Assert.True(result.Contains(@"\viewkind4\uc1\pard\cf1\highlight2\b\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par"));
            Assert.True(result.Contains(@"\cf2\highlight1\i Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par"));
            Assert.True(result.Contains(@"\cf3\ul\b0\i0 Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par"));
            Assert.True(result.Contains(@"\cf4\ulnone Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par"));
            Assert.True(result.Contains(@"\cf5 Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par"));
            Assert.True(result.Contains(@"\cf6\i Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par"));
            Assert.True(result.Contains(@"\cf0\highlight0\i0\f1\par"));
            Assert.True(result.Contains(@"}"));

            LogManager.Configuration = null;
            Assert.Null(target.TargetForm);
            Application.DoEvents();
            Assert.True(form.IsDisposed);
        }
Ejemplo n.º 17
0
        private void ConfigureSharedFile(string mode, string fileName)
        {
            var modes = mode.Split('|');

            FileTarget ft = new FileTarget();

            ft.FileName                   = fileName;
            ft.Layout                     = "${message}";
            ft.KeepFileOpen               = true;
            ft.OpenFileCacheTimeout       = 10;
            ft.OpenFileCacheSize          = 1;
            ft.LineEnding                 = LineEndingMode.LF;
            ft.KeepFileOpen               = Array.IndexOf(modes, "retry") >= 0 ? false : true;
            ft.ForceMutexConcurrentWrites = Array.IndexOf(modes, "mutex") >= 0 ? true : false;
            ft.ArchiveAboveSize           = Array.IndexOf(modes, "archive") >= 0 ? 50 : -1;
            if (ft.ArchiveAboveSize > 0)
            {
                string archivePath = Path.Combine(Path.GetDirectoryName(fileName), "Archive");
                ft.ArchiveFileName = Path.Combine(archivePath, "{####}_" + Path.GetFileName(fileName));
                ft.MaxArchiveFiles = 10000;
            }

            var name = "ConfigureSharedFile_" + mode.Replace('|', '_') + "-wrapper";

            switch (modes[0])
            {
            case "async":
                SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow)
                {
                    Name = name, TimeToSleepBetweenBatches = 10
                }, LogLevel.Debug);
                break;

            case "buffered":
                SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100)
                {
                    Name = name
                }, LogLevel.Debug);
                break;

            case "buffered_timed_flush":
                SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10)
                {
                    Name = name
                }, LogLevel.Debug);
                break;

            default:
                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
                break;
            }
        }
        public WebApiTraceRendererTests()
        {
            EnsureLayoutRendersSetup.Please();

            // setup writer under test
            _writer = new NLogTraceWriter();

            // setup debug logging target
            _debugTarget = new DebugTarget {
                Layout = "${message}"
            };
            SimpleConfigurator.ConfigureForTargetLogging(_debugTarget, LogLevel.Info);
        }
Ejemplo n.º 19
0
        public void CustomWordRowColoringTest()
        {
            try
            {
                RichTextBoxTarget target = new RichTextBoxTarget()
                {
                    ControlName       = "Control1",
                    Layout            = "${level} ${logger} ${message}",
                    ShowMinimized     = true,
                    ToolWindow        = false,
                    WordColoringRules =
                    {
                        new RichTextBoxWordColoringRule("zzz", "Red",   "Empty"),
                        new RichTextBoxWordColoringRule("aaa", "Green", "Empty"),
                    }
                };

                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                logger.Fatal("Test zzz");
                logger.Error("Foo xxx");
                logger.Warn("Bar yyy");
                logger.Info("Test aaa");
                logger.Debug("Foo zzz");
                logger.Trace("Bar ccc");

                Application.DoEvents();

                var form = target.TargetForm;

                string rtfText = ExtractRtf(target.TargetRichTextBox);

                Assert.True(target.CreatedForm);

                // "zzz" string will be highlighted

                var result = rtfText;
                Assert.True(result.Contains(@"{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red255\green0\blue0;\red0\green128\blue0;}"));
                Assert.True(result.Contains(@"\viewkind4\uc1\pard\cf1\highlight2\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf3\f1 zzz\cf1\f0\par"));
                Assert.True(result.Contains(@"Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo xxx\par"));
                Assert.True(result.Contains(@"Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar yyy\par"));
                Assert.True(result.Contains(@"Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf4\f1 aaa\cf1\f0\par"));
                Assert.True(result.Contains(@"Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo \cf3\f1 zzz\cf1\f0\par"));
                Assert.True(result.Contains(@"Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar ccc\par"));
                Assert.True(result.Contains(@"\cf0\highlight0\f1\par"));
                Assert.True(result.Contains(@"}"));
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
Ejemplo n.º 20
0
        public void RepeatingHeaderTest()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tempFile = Path.Combine(tempPath, "file.txt");

            try
            {
                const string header = "Headerline";

                var ft = new FileTarget
                {
                    FileName         = tempFile,
                    ArchiveFileName  = Path.Combine(tempPath, "archive/{####}.txt"),
                    ArchiveAboveSize = 51,
                    LineEnding       = LineEndingMode.LF,
                    ArchiveNumbering = ArchiveNumberingMode.Sequence,
                    Layout           = "${message}",
                    Header           = header,
                    MaxArchiveFiles  = 2,
                };

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                for (var i = 0; i < 16; ++i)
                {
                    logger.Debug("123456789");
                }

                LogManager.Configuration = null;

                AssertFileContentsStartsWith(tempFile, header, Encoding.UTF8);

                AssertFileContentsStartsWith(Path.Combine(tempPath, "archive/0002.txt"), header, Encoding.UTF8);

                AssertFileContentsStartsWith(Path.Combine(tempPath, "archive/0001.txt"), header, Encoding.UTF8);

                Assert.True(!File.Exists(Path.Combine(tempPath, "archive/0000.txt")));
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
Ejemplo n.º 21
0
        public void CustomRowColoringTest()
        {
            try
            {
                RichTextBoxTarget target = new RichTextBoxTarget()
                {
                    ControlName      = "Control1",
                    Layout           = "${level} ${logger} ${message}",
                    ShowMinimized    = true,
                    ToolWindow       = false,
                    RowColoringRules =
                    {
                        new RichTextBoxRowColoringRule("starts-with(message, 'B')", "Maroon", "Empty"),
                    }
                };

                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                logger.Fatal("Test");
                logger.Error("Foo");
                logger.Warn("Bar");
                logger.Info("Test");
                logger.Debug("Foo");
                logger.Trace("Bar");

                Application.DoEvents();

                var form = target.TargetForm;

                MemoryStream ms = new MemoryStream();
                target.TargetRichTextBox.SaveFile(ms, RichTextBoxStreamType.RichText);
                string rtfText = Encoding.UTF8.GetString(ms.GetBuffer());

                Assert.True(target.CreatedForm);

                var result = rtfText;
                Assert.True(result.Contains(@"{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red128\green0\blue0;}"));
                Assert.True(result.Contains(@"\viewkind4\uc1\pard\cf1\highlight2\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par"));
                Assert.True(result.Contains(@"Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par"));
                Assert.True(result.Contains(@"\cf3 Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par"));
                Assert.True(result.Contains(@"\cf1 Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test\par"));
                Assert.True(result.Contains(@"Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo\par"));
                Assert.True(result.Contains(@"\cf3 Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar\par"));
                Assert.True(result.Contains(@"\cf0\highlight0\f1\par"));
                Assert.True(result.Contains(@"}"));
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
Ejemplo n.º 22
0
        public void ErrorMessageWithStringFormatWillLogNullParameters()
        {
            SimpleConfigurator.ConfigureForTargetLogging(_target, LogLevel.Error);
            Logger logger = LogManager.GetLogger("Example");

            logger.Error("log message {0} and with a {1}", _parameter1, _parameter2);

            JToken log       = JObject.Parse(_target.Logs[0]);
            string message   = (string)log.SelectToken("Message");
            string parameter = (string)log.SelectToken("Parameters");

            Assert.That(message, Is.EqualTo("log message With Extra String!! and with a "));
            Assert.That(parameter, Is.EqualTo("With Extra String!!,null"));
        }
Ejemplo n.º 23
0
        JObject AssertValidJson(Action <ILogger> act, IEnumerable <SeqPropertyItem> properties = null, int?maxRecursionLimit = null)
        {
            var logger = LogManager.GetCurrentClassLogger();
            var target = new CollectingTarget();

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            act(logger);

            var formatted = new StringWriter();

            ToCompactJson(target.Events.Single(), formatted, properties?.ToList() ?? new List <SeqPropertyItem>(), maxRecursionLimit);

            return(Assertions.AssertValidJson(formatted.ToString()));
        }
Ejemplo n.º 24
0
        JObject AssertValidJson(Action <ILogger> act)
        {
            var logger = LogManager.GetCurrentClassLogger();
            var target = new CollectingTarget();

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            act(logger);

            var formatted = new StringWriter();

            ToCompactJson(target.Events.Single(), formatted, new List <SeqPropertyItem>());

            return(Assertions.AssertValidJson(formatted.ToString()));
        }
Ejemplo n.º 25
0
        public void Test1()
        {
            EventLogTarget elt = new EventLogTarget();

            elt.Log      = "NLog.UnitTests";
            elt.Source   = "NLog.UnitTests";
            elt.EventID  = "10";
            elt.Category = "123";
            SimpleConfigurator.ConfigureForTargetLogging(elt);

            LogManager.Configuration = null;

            Logger l = LogManager.GetCurrentClassLogger();

            l.Info("aaa");
        }
Ejemplo n.º 26
0
        public static void SetLoggerToNormal()
        {
            FileTarget target = new FileTarget();

            target.FileName                = "${basedir}/nlog/autoFlushLogger.txt";
            target.KeepFileOpen            = true;
            target.Encoding                = Encoding.UTF8;
            target.ArchiveOldFileOnStartup = true;

            AutoFlushTargetWrapper wrapper = new AutoFlushTargetWrapper();

            wrapper.WrappedTarget       = target;
            wrapper.OptimizeBufferReuse = true;

            SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug);
        }
Ejemplo n.º 27
0
        public static void SetLoggerBuffer()
        {
            FileTarget target = new FileTarget();

            target.FileName     = "${basedir}/nlog/BufferLogger.txt";
            target.KeepFileOpen = true;
            target.Encoding     = Encoding.UTF8;

            BufferingTargetWrapper wrapper = new BufferingTargetWrapper();

            wrapper.WrappedTarget       = target;
            wrapper.OptimizeBufferReuse = true;
            wrapper.FlushTimeout        = 100;

            SimpleConfigurator.ConfigureForTargetLogging(wrapper, LogLevel.Debug);
        }
Ejemplo n.º 28
0
        public DmdDevice()
        {
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;

            // setup logger
            var assembly      = Assembly.GetCallingAssembly();
            var assemblyPath  = Path.GetDirectoryName(new Uri(assembly.CodeBase).LocalPath);
            var logConfigPath = Path.Combine(assemblyPath, "DmdDevice.log.config");

            if (File.Exists(logConfigPath))
            {
                LogManager.Configuration = new XmlLoggingConfiguration(logConfigPath, true);
#if !DEBUG
                LogManager.Configuration.AddTarget("memory", MemLogger);
                LogManager.Configuration.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, MemLogger));
                LogManager.ReconfigExistingLoggers();
#endif
            }
#if !DEBUG
            else
            {
                SimpleConfigurator.ConfigureForTargetLogging(MemLogger, LogLevel.Debug);
            }
#endif
            CultureUtil.NormalizeUICulture();
            _config       = new Configuration();
            _altcolorPath = GetColorPath();

            // read versions from assembly
            var attr = assembly.GetCustomAttributes(typeof(AssemblyConfigurationAttribute), false);
            var fvi  = FileVersionInfo.GetVersionInfo(assembly.Location);
            _version = fvi.ProductVersion;
            if (attr.Length > 0)
            {
                var aca = (AssemblyConfigurationAttribute)attr[0];
                _sha         = aca.Configuration;
                _fullVersion = $"{_version} ({_sha})";
            }
            else
            {
                _fullVersion = fvi.ProductVersion;
                _sha         = "";
            }

            Logger.Info("Starting VPinMAME API {0} through {1}.exe.", _fullVersion, Process.GetCurrentProcess().ProcessName);
            Logger.Info("Assembly located at {0}", assembly.Location);
        }
Ejemplo n.º 29
0
        public void CsvHeaderTest()
        {
            // test for the following changes
            // https://github.com/NLog/NLog/commit/e1ed0d4857dddc95d5db09ee95e9a0c85afc7810
            // codeplex ticket 6370

            string tempFile = Path.GetTempFileName();

            try
            {
                for (int i = 0; i < 2; i++)
                {
                    var layout = new CsvLayout
                    {
                        Delimiter  = CsvColumnDelimiterMode.Semicolon,
                        WithHeader = true,
                        Columns    =
                        {
                            new CsvColumn("name",    "${logger}"),
                            new CsvColumn("level",   "${level}"),
                            new CsvColumn("message", "${message}"),
                        }
                    };

                    FileTarget ft = new FileTarget
                    {
                        FileName                       = SimpleLayout.Escape(tempFile),
                        LineEnding                     = LineEndingMode.LF,
                        Layout                         = layout,
                        OpenFileCacheTimeout           = 0,
                        ReplaceFileContentsOnEachWrite = false
                    };
                    SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                    logger.Debug("aaa");
                    LogManager.Configuration = null;
                }
                AssertFileContents(tempFile, "name;level;message\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\nNLog.UnitTests.Targets.FileTargetTests;Debug;aaa\n", Encoding.UTF8);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
        public void Shutdown_DisposesSdk()
        {
            _fixture.Options.InitializeSdk = false;
            var target = _fixture.GetTarget();

            SimpleConfigurator.ConfigureForTargetLogging(target);

            var sut = LogManager.GetCurrentClassLogger();

            sut.Error(DefaultMessage);

            _fixture.SdkDisposeHandle.DidNotReceive().Dispose();

            LogManager.Shutdown();

            _fixture.SdkDisposeHandle.Received(1).Dispose();
        }