示例#1
0
 void DelLink_Clicked(RichTextBoxTarget sender, string linkText, LogEventInfo logEvent)
 {
     if (logEvent.Exception != null)
     {
         MessageBox.Show(logEvent.Exception.ToString(), "Exception details", MessageBoxButtons.OK);
     }
 }
示例#2
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            RichTextBoxTarget.ReInitializeAllTextboxes(this);

            this.tcMain.SelectedIndex = 1;

            if (SV.DeviceDictonary == null || SV.DeviceDictonary.Count == 0)
            {
                MessageBox.Show("首次运行,需要设置设备连接。");
                LoadSettingForm();
                tcMain.SelectedIndex = 0;
                return;
            }
            else
            {
            }

            LoadSettingForm();
            LoadEnterWarehouseForm();
            LoadWashingForm();
            LoadDryForm();
            LoadExWarehouseForm();

            ConnectDevice1();
            ConnectDevice2();
            ConnectDevice3();
            ConnectDevice4();
        }
示例#3
0
 private void Form1_LinkClicked(RichTextBoxTarget sender, string linkText, LogEventInfo logEvent)
 {
     //COM HRESULT E_FAIL happens when not used BeginInvoke and links are clicked while spinning
     BeginInvokeLambda(this,
                       () => { MessageBox.Show("Clicked link '" + linkText + "' for event\n" + logEvent, sender.Name); }
                       );
 }
示例#4
0
        public void ActiveFormNegativeTest1()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                FormName    = "MyForm1",
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = "${level} ${logger} ${message}",
                ToolWindow = false,
                Width      = 300,
                Height     = 200,
            };

            using (Form form = new Form())
            {
                form.Name        = "MyForm1";
                form.WindowState = FormWindowState.Minimized;

                //RichTextBox rtb = new RichTextBox();
                //rtb.Dock = DockStyle.Fill;
                //rtb.Name = "Control1";
                //form.Controls.Add(rtb);
                form.Show();
                try
                {
                    target.Initialize(null);
                    Assert.Fail("Expected exception.");
                }
                catch (NLogConfigurationException ex)
                {
                    Assert.AreEqual("Rich text box control 'Control1' cannot be found on form 'MyForm1'.", ex.Message);
                }
            }
        }
示例#5
0
        public void ActiveFormNegativeTest2()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                FormName = "MyForm1",
                UseDefaultRowColoringRules = true,
                Layout = "${level} ${logger} ${message}",
            };

            using (Form form = new Form())
            {
                form.Name        = "MyForm1";
                form.WindowState = FormWindowState.Minimized;
                form.Show();

                try
                {
                    target.Initialize(null);
                    Assert.Fail("Expected exception.");
                }
                catch (NLogConfigurationException ex)
                {
                    Assert.AreEqual("Rich text box control name must be specified for RichTextBoxTarget.", ex.Message);
                }
            }
        }
示例#6
0
        private static AsyncTargetWrapper GetFormTarget()
        {
            const string layout     = "${date:format=HH\\:mm\\:ss} ${logger} # ${message}";
            const int    maxLines   = 1000;
            const bool   autoScroll = true;
            Target       t;

            switch (_formConfig)
            {
            case NlogFormConfig.WinForms:
                t = new RichTextBoxTarget
                {
                    Layout      = layout,
                    AutoScroll  = autoScroll,
                    ControlName = "boxLog",
                    FormName    = "GUI",
                    MaxLines    = maxLines
                };
                break;

            case NlogFormConfig.WPF:
                t = new CustomEventTarget
                {
                    Layout = layout,
                };
                break;

            default:
                throw new ArgumentOutOfRangeException();
            }

            return(new AsyncTargetWrapper(t));
        }
示例#7
0
        /// <summary>
        /// Form loading
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void MainForm_Load(object sender, EventArgs e)
        {
            // Setup form textbox as logging target
            // Solution from:
            // https://github.com/NLog/NLog/issues/133#issuecomment-136164391

            RichTextBoxTarget loggerTextBoxTarget = new RichTextBoxTarget
            {
                Name        = "LogBox",
                FormName    = Name,
                ControlName = logBox.Name,
                Layout      = "${date:format=HH\\:mm\\:ss.fff} [${logger}] ${message} ${exception:format=Message}",
                AutoScroll  = true
            };

            LoggingConfiguration logConfig = new LoggingConfiguration();

            logConfig.AddTarget(loggerTextBoxTarget.Name, loggerTextBoxTarget);
            logConfig.AddRule(LogLevel.Debug, LogLevel.Fatal, loggerTextBoxTarget);

            // Create MS logger
            using (ILoggerFactory loggerFactory = LoggerFactory.Create(builder => builder.AddNLog(logConfig)))
            {
                logger       = loggerFactory.CreateLogger("Demo");
                lidar.Logger = loggerFactory.CreateLogger("Lidar");
            }
        }
 private void ConfigLogger()
 {
     logWindow = new NLog.Windows.Forms.RichTextBoxTarget
     {
         Name        = "LogWindow",
         Layout      = "${date:format=yyyy.MM.dd HH.mm.ss} ${threadname:padding=-6} ${threadid:padding=-2} ${pad:padding=-7:inner=[${level:uppercase=True}]}: ${message}${onexception:inner=${literal:text=\\:} ${exception:innerformat=Message:maxInnerExceptionLevel=10:innerExceptionSeparator=-->:format=Message}}",
         ControlName = "logRichTextBox",
         FormName    = "Form1",
         AutoScroll  = true,
         MaxLines    = 500,
         UseDefaultRowColoringRules = true
     };
     maxLinesTextBox.Text = logWindow.MaxLines.ToString();
     guiWrapper           = new NLog.Targets.Wrappers.AsyncTargetWrapper()
     {
         Name                      = "GUI",
         OverflowAction            = NLog.Targets.Wrappers.AsyncTargetWrapperOverflowAction.Discard,
         BatchSize                 = 10,
         QueueLimit                = 500,
         FullBatchSizeWriteLimit   = 1,
         TimeToSleepBetweenBatches = 400,
         WrappedTarget             = logWindow
     };
     timeToSleepBetweenBatchesTextBox.Text = guiWrapper.TimeToSleepBetweenBatches.ToString();
     overflowActionComboBox.Items.AddRange(Enum.GetNames(typeof(AsyncTargetWrapperOverflowAction)));
     overflowActionComboBox.SelectedIndex = (int)guiWrapper.OverflowAction;
     queueLimitTextBox.Text = guiWrapper.QueueLimit.ToString();
     fullBatchSizeWriteLimitTextBox.Text = guiWrapper.FullBatchSizeWriteLimit.ToString();
     batchSizeTextBox.Text = guiWrapper.BatchSize.ToString();
     LogManager.Configuration.AddTarget(guiWrapper.Name, guiWrapper);
     LogManager.Configuration.LoggingRules.Add(new NLog.Config.LoggingRule("*", LogLevel.Trace, guiWrapper));
     LogManager.ReconfigExistingLoggers();
 }
示例#9
0
        public Form1()
        {
            InitializeComponent();

            NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
            Logger.Info("Init");

            RichTextBoxTarget.ReInitializeAllTextboxes(this);

            Logger.Log(LogLevel.Trace, "Log Trace");
            Logger.Log(LogLevel.Debug, "Log Debug");
            Logger.Log(LogLevel.Info, "Log Info");
            Logger.Log(LogLevel.Warn, "Log Warn");
            Logger.Log(LogLevel.Error, "Log Error");
            Logger.Log(LogLevel.Fatal, "Log Fatal");

            var thread = new Thread(() =>
            {
                Random rnd = new Random();
                for (int i = 0; i < 10; i++)
                {
                    LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", i + ": a line with some length\n a new line");
                    Logger.Log(theEvent);
                    Thread.Sleep(200);
                }
                Logger.Info("Done");
            });

            Logger.Info("start thread");
            thread.Start();
        }
示例#10
0
        public Form1()
        {
            InitializeComponent();

            NLog.Logger Logger = NLog.LogManager.GetCurrentClassLogger();
            Logger.Info("Init");

            RichTextBoxTarget.ReInitializeAllTextboxes(this);

            var thread = new Thread(() =>
            {
                Random rnd = new Random();
                for (int i = 0; i < 10; i++)
                {
                    LogEventInfo theEvent = new LogEventInfo(LogLevel.Debug, "", i + ": a line with some length\n a new line");
                    if (rnd.NextDouble() > 0.1)
                    {
                        theEvent.Properties["ShowLink"] = "link via property";
                    }
                    if (rnd.NextDouble() > 0.5)
                    {
                        theEvent.Properties["ShowLink2"] = "Another link";
                    }
                    Logger.Log(theEvent);
                    Thread.Sleep(200);
                }
                Logger.Info("Done");
            });

            Logger.Info("start thread");
            thread.Start();
        }
示例#11
0
        private void MainForm_Load(object sender, EventArgs e)
        {
            RichTextBoxTarget.ReInitializeAllTextboxes(this);

            // read config
            try
            {
                var cfg = File.ReadAllText(cfg_file);
                if (!string.IsNullOrWhiteSpace(cfg))
                {
                    dynamic json = JsonConvert.DeserializeObject(cfg);
                    if (json?.pub != null)
                    {
                        tbPublic.Text = json?.pub.ToString();
                    }
                    if (json?.priv != null)
                    {
                        tbPrivate.Text = json?.priv.ToString();
                    }
                }
            }
            catch
            {
                // None
            }
        }
示例#12
0
        protected override void OnShown(EventArgs e)
        {
            SearchUpdates();
            if (_memoryLogger.Logs.Count > 0)
            {
                LogRichTextBox.Text =
                    _memoryLogger.Logs.Aggregate(new StringBuilder(), (x, y) => x.AppendLine(y)).ToString();
            }

            LogManager.Configuration.LoggingRules.Remove(_loggingRule);
            _memoryLogger.Dispose();

            _memoryLogger = null;
            _loggingRule  = null;

            var target = new RichTextBoxTarget
            {
                Layout      = Program.LogLayout,
                ControlName = "LogRichTextBox",
                FormName    = Name,
                AutoScroll  = true,
                CreatedForm = false,
                Name        = "textBox"
            };

            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "White"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "Black", "White"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "White"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed",
                                                                       FontStyle.Bold));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed",
                                                                       FontStyle.Bold));

            SimpleConfigurator.ConfigureForTargetLogging(target, Program.MinLogLevel);
        }
示例#13
0
        private void Form1_Load(object sender, EventArgs e)
        {
            RichTextBoxTarget target = new RichTextBoxTarget();

            target.Layout      = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            target.ControlName = richTextBox1.Name;
            target.FormName    = this.Name;
            target.UseDefaultRowColoringRules = true;
            target.AutoScroll = true;

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

            /*
             * Logger logger = LogManager.GetLogger("Example");
             * logger.Trace("trace log message");
             * logger.Debug("debug log message");
             * logger.Info("info log message");
             * logger.Warn("warn log message");
             * logger.Error("error log message");
             * logger.Fatal("fatal log message");
             *
             * RichTextBoxTarget.ReInitializeAllTextboxes(this); //more on this later
             * //RichTextBoxTarget.GetTargetByControl(richTextBox1).LinkClicked += LoggerContent_LinkClicked;
             */

            _logger = new LoggerContent(richTextBox1);
            AddContent("logger", _logger, DockState.DockBottom);
        }
示例#14
0
        public void InitializeLogger()
        {
            var config = new NLog.Config.LoggingConfiguration();

            LogManager.Configuration = config;
            const string layout =
                @"${date:format=yyyy-MM-dd HH\:mm\:ss,fff} ${level:upperCase=True} ${logger} ${message}${newline}${onexception:Process\: ${processname}${newline}Process time\: ${processtime}${newline}Process ID\: ${processid}${newline}Thread ID\: ${threadid}${newline}Details\:${newline}${exception:format=ToString}}";
            var boxTarget = new RichTextBoxTarget
            {
                Layout      = layout,
                ControlName = "syntaxRichTextBox1",
                FormName    = "MainDlg",
                UseDefaultRowColoringRules = false
            };

            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "Orange", "White",
                                                                          FontStyle.Regular));
            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "Red", "White",
                                                                          FontStyle.Regular));
            boxTarget.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "DarkViolet", "White",
                                                                          FontStyle.Regular));

            var traceTarget = new TraceTarget {
                Layout = layout
            };

            config.AddTarget("box", boxTarget);
            config.AddTarget("trace", traceTarget);
            var r1 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Warn, boxTarget);
            var r2 = new NLog.Config.LoggingRule("*", NLog.LogLevel.Trace, traceTarget);

            config.LoggingRules.Add(r1);
            config.LoggingRules.Add(r2);
            LogManager.Configuration = config;
        }
示例#15
0
文件: Form1.cs 项目: WS-QA/Nlog
        private void Form1_Load(object sender, EventArgs e)
        {
            RichTextBoxTarget target = new RichTextBoxTarget();

            target.Layout      = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
            target.ControlName = "richTextBox1";
            target.FormName    = "Form1";
            target.UseDefaultRowColoringRules = false;
            target.WordColoringRules.Add(
                new RichTextBoxWordColoringRule(
                    "log",     // word
                    "White",   // font color
                    "Red",     // background color
                    FontStyle.Bold | FontStyle.Italic
                    )
                );

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

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

            logger.Trace("trace log message");
            logger.Debug("debug log message");
            logger.Info("info log message");
            logger.Warn("warn log message");
            logger.Error("error log message");
            logger.Fatal("fatal log message");
            logger.Fatal("fatal log message, rather serious");
        }
示例#16
0
        public static void InstantiateRLogger()
        {
            var target = new RichTextBoxTarget
            {
                Name        = "RichTextBox",
                Layout      = "${longdate:useUTC=true} | ${level:uppercase=true} | ${logger} :: ${message}",
                ControlName = "textbox1",
                FormName    = "Form1",
                AutoScroll  = true,
                Height      = 480,
                Width       = 640,
                MaxLines    = 10000,
                UseDefaultRowColoringRules = false
            };

            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Trace", "DarkGray", "Control"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Debug", "Gray", "Control"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Info", "ControlText", "Control"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Warn", "DarkRed", "Control"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Error", "White", "DarkRed"));
            target.RowColoringRules.Add(new RichTextBoxRowColoringRule("level == LogLevel.Fatal", "Yellow", "DarkRed"));

            var asyncWrapper = new AsyncTargetWrapper {
                Name = "AsyncRichTextBox", WrappedTarget = target
            };

            SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);
        }
示例#17
0
 public frmLog()
 {
     InitializeComponent();
     _log = _log ?? LogManager.GetCurrentClassLogger();
     RichTextBoxTarget.ReInitializeAllTextboxes(this);
     RichTextBoxTarget.GetTargetByControl(rtbLog).LinkClicked += DelLink_Clicked;
 }
        public void ActiveFormNegativeTest2()
        {
            var config = new LoggingConfiguration();
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                FormName = "MyForm1",
                UseDefaultRowColoringRules = true,
                Layout = "${level} ${logger} ${message}",
            };

            config.AddTarget("target", target);
            config.LoggingRules.Add(new LoggingRule("*", target));
            LogManager.ThrowExceptions = true;

            using (Form form = new Form())
            {
                form.Name        = "MyForm1";
                form.WindowState = FormWindowState.Minimized;
                form.Show();

                try
                {
                    new LogFactory(config);
                    Assert.True(false, "Expected exception.");
                }
                catch (NLogConfigurationException ex)
                {
                    Assert.Equal("Rich text box control name must be specified for RichTextBoxTarget.", ex.Message);
                }
            }
        }
        public void ActiveFormTest()
        {
            var config = new LoggingConfiguration();
            var target = new RichTextBoxTarget()
            {
                FormName    = "MyForm1",
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = "${level} ${logger} ${message}",
                ToolWindow = false,
                Width      = 300,
                Height     = 200,
            };

            config.AddTarget("target", target);
            config.LoggingRules.Add(new LoggingRule("*", target));
            LogManager.ThrowExceptions = true;

            using (Form form = new Form())
            {
                form.Name        = "MyForm1";
                form.WindowState = FormWindowState.Minimized;
                RichTextBox rtb = new RichTextBox();
                rtb.Dock = DockStyle.Fill;
                rtb.Name = "Control1";
                form.Controls.Add(rtb);
                form.Show();
                form.Activate();

                new LogFactory(config);
                Assert.Same(form, target.TargetForm);
                Assert.Same(rtb, target.TargetRichTextBox);
            }
        }
        public void ActiveFormNegativeTest1()
        {
            var config = new LoggingConfiguration();
            var target = new RichTextBoxTarget()
            {
                FormName    = "MyForm1",
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout     = "${level} ${logger} ${message}",
                ToolWindow = false,
                Width      = 300,
                Height     = 200,
            };

            config.AddTarget("target", target);
            config.LoggingRules.Add(new LoggingRule("*", target));
            LogManager.ThrowExceptions = true;

            using (var form = new Form())
            {
                form.Name        = "MyForm1";
                form.WindowState = FormWindowState.Minimized;

                form.Show();
                try
                {
                    new LogFactory(config);
                    Assert.True(false, "Expected exception.");
                }
                catch (NLogConfigurationException ex)
                {
                    Assert.Equal("Rich text box control 'Control1' cannot be found on form 'MyForm1'.", ex.Message);
                }
            }
        }
        public void AutoScrollTest()
        {
            try
            {
                RichTextBoxTarget target = new RichTextBoxTarget()
                {
                    ControlName   = "Control1",
                    Layout        = "${level} ${logger} ${message}",
                    ShowMinimized = true,
                    ToolWindow    = false,
                    AutoScroll    = true,
                };

                var form = target.TargetForm;
                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                for (int i = 0; i < 100; ++i)
                {
                    logger.Info("Test");
                    Application.DoEvents();
                    Assert.Equal(target.TargetRichTextBox.SelectionStart, target.TargetRichTextBox.TextLength);
                    Assert.Equal(0, target.TargetRichTextBox.SelectionLength);
                }
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
        public void MaxLinesTest()
        {
            try
            {
                RichTextBoxTarget target = new RichTextBoxTarget()
                {
                    ControlName   = "Control1",
                    Layout        = "${message}",
                    ShowMinimized = true,
                    ToolWindow    = false,
                    AutoScroll    = true,
                };

                Assert.Equal(0, target.MaxLines);
                target.MaxLines = 7;

                var form = target.TargetForm;
                SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
                for (int i = 0; i < 100; ++i)
                {
                    logger.Info("Test {0}", i);
                }

                Application.DoEvents();
                string expectedText = "Test 93\nTest 94\nTest 95\nTest 96\nTest 97\nTest 98\nTest 99\n";

                Assert.Equal(expectedText, target.TargetRichTextBox.Text);
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
        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.Contains(@"{\colortbl ;\red0\green0\blue0;\red255\green255\blue255;\red255\green0\blue0;\red0\green128\blue0;}", result);

                if (IsAppVeyor())
                {
                    Assert.Contains(@"\viewkind4\uc1\pard\cf1\highlight2\f0\fs17 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf3\f1 zzz\cf1\f0\par", result);
                }
                else
                {
                    Assert.Contains(@"\viewkind4\uc1\pard\cf1\highlight2\f0\fs15 Fatal NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf3\f1 zzz\cf1\f0\par", result);
                }

                Assert.Contains(@"Error NLog.UnitTests.Targets.RichTextBoxTargetTests Foo xxx\par", result);
                Assert.Contains(@"Warn NLog.UnitTests.Targets.RichTextBoxTargetTests Bar yyy\par", result);
                Assert.Contains(@"Info NLog.UnitTests.Targets.RichTextBoxTargetTests Test \cf4\f1 aaa\cf1\f0\par", result);
                Assert.Contains(@"Debug NLog.UnitTests.Targets.RichTextBoxTargetTests Foo \cf3\f1 zzz\cf1\f0\par", result);
                Assert.Contains(@"Trace NLog.UnitTests.Targets.RichTextBoxTargetTests Bar ccc\par", result);
                Assert.Contains(@"\cf0\highlight0\f1\par", result);
                Assert.Contains(@"}", result);
            }
            finally
            {
                LogManager.Configuration = null;
            }
        }
        public void LinkTestExcessLinksRemoved()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout       = "${level} ${logger} ${message} ${rtb-link:inner=${event-properties:item=LinkIndex}}",
                ToolWindow   = false,
                Width        = 300,
                Height       = 200,
                SupportLinks = true,
                MaxLines     = 5
            };

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            Assert.Same(target, RichTextBoxTarget.GetTargetByControl(target.TargetRichTextBox));

            for (int i = 0; i < 100; ++i)
            {
                LogEventInfo info = new LogEventInfo(LogLevel.Info, "", "Test");
                info.Properties["LinkIndex"] = i;
                logger.Log(info);
            }
            Application.DoEvents();

            string resultText = target.TargetRichTextBox.Text;
            string resultRtf  = ExtractRtf(target.TargetRichTextBox);

            Assert.Contains("#link", resultText);                     //some links exist
            Assert.Contains(@"\v #link", resultRtf);                  //some links exist

            Assert.True(target.LinkedEventsCount == target.MaxLines); //storing 5, not 100 events
        }
        public void LinkTest()
        {
            RichTextBoxTarget target = new RichTextBoxTarget()
            {
                ControlName = "Control1",
                UseDefaultRowColoringRules = true,
                Layout       = "${level} ${logger} ${message} ${rtb-link:inner=descr}",
                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));

            string resultRtf  = ExtractRtf(target.TargetRichTextBox);
            string resultText = target.TargetRichTextBox.Text;

            Assert.DoesNotMatch(@"(\([a-z0-9]{8}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{4}-[a-z0-9]{12}\))", resultRtf); //the placeholder GUID was replaced
            Assert.Contains("descr#link", resultText);                                                             //text contains visible and invisible parts
            Assert.Contains(@"descr\v #link", resultRtf);                                                          //RTF contains everything
        }
示例#26
0
        private void InitializeLog()
        {
            var config = new LoggingConfiguration();
            var target = new RichTextBoxTarget
            {
                UseDefaultRowColoringRules = true,
                Layout      = @"${date:format=dd/MM/yyyy HH\:mm\:ss} - ${message}",
                FormName    = Name,
                ControlName = rtbLog.Name,
                AutoScroll  = true
            };

            config.AddTarget("RichTextBox", target);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, target));

            var infoTarget = new FileTarget
            {
                FileName = "${basedir:dir=Logs:file=ACBrSat.log}",
                Layout   = "${processid}|${longdate}|${level:uppercase=true}|" +
                           "${event-context:item=Context}|${logger}|${message}",
                CreateDirs        = true,
                Encoding          = Encoding.UTF8,
                MaxArchiveFiles   = 93,
                ArchiveEvery      = FileArchivePeriod.Day,
                ArchiveNumbering  = ArchiveNumberingMode.Date,
                ArchiveFileName   = "${basedir}/Logs/Archive/${date:format=yyyy}/${date:format=MM}/ACBrSat_{{#}}.log",
                ArchiveDateFormat = "dd.MM.yyyy"
            };

            config.AddTarget("infoFile", infoTarget);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Debug, infoTarget));
            LogManager.Configuration = config;
            logger = LogManager.GetLogger("ACBrSAT");
        }
示例#27
0
 public RedistClient()
 {
     InitializeComponent();
     Hub.StateChangeEvent += Hub_StateChangeEvent;
     Hub.UpdateStart      += Hub_UpdateStart;
     Hub.UpdateComplete   += Hub_UpdateComplete;
     RichTextBoxTarget.ReInitializeAllTextboxes(this);
 }
示例#28
0
        public FrmMain()
        {
            InitializeComponent();
            RichTextBoxTarget.ReInitializeAllTextboxes(this);

            this.label5.Text = @"数据格式:" + Environment.NewLine +
                               @"<STX>Index___Code1_Code2 ....<ETX>" + Environment.NewLine +
                               @"<STX>Index___NoRead<ETX>";
        }
        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);
        }
        public void RichTextBoxTargetDefaultsTest()
        {
            var target = new RichTextBoxTarget();

            Assert.False(target.UseDefaultRowColoringRules);
            Assert.Equal(0, target.WordColoringRules.Count);
            Assert.Equal(0, target.RowColoringRules.Count);
            Assert.Null(target.FormName);
            Assert.Null(target.ControlName);
        }