コード例 #1
0
        public void VarInPropertyIsRendered()
        {
            var layout = new JsonWithPropertiesLayout();

            layout.Properties.Add(new StructuredLoggingProperty("key1", "${var:foo}"));

            var target = new MemoryTarget
            {
                Name   = Guid.NewGuid().ToString(),
                Layout = layout
            };

            var fooValue = Guid.NewGuid().ToString();

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            LogManager.Configuration.Variables.Add("foo", fooValue);

            TimeSource.Current = new FakeTimeSource();
            var logger = LogManager.GetCurrentClassLogger();

            var logEvent = new LogEventInfo(LogLevel.Trace, LoggerName, TestMessage);

            logger.Log(logEvent);

            Assert.That(target.Logs.Count, Is.EqualTo(1));

            var output = target.Logs[0];

            Assert.That(output, Does.Contain(fooValue));
            Assert.That(output, Does.Contain($"\"key1\":\"{fooValue}\""));

            Assert.That(output, Does.Not.Contain("var:"));
            Assert.That(output, Does.Not.Contain("${:"));
            Assert.That(output, Does.Not.Contain("foo"));
        }
コード例 #2
0
        private static void WriteEventLogEntry2(LogLevel logLevel, EventLogEntryType eventLogEntryType, Layout entryType = null)
        {
            var target = new EventLogTarget();

            //The Log to write to is intentionally lower case!!
            target.Log = "application";
            // set the source explicitly to prevent random AppDomain name being used as the source name
            target.Source = "NLog.UnitTests";
            if (entryType != null)
            {
                //set only when not default
                target.EntryType = entryType;
            }
            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            var logger = LogManager.GetLogger("WriteEventLogEntry");
            var el     = new EventLog(target.Log);

            var loggedNotBefore = DateTime.Now.AddMinutes(-1);

            var testValue = Guid.NewGuid().ToString();

            logger.Log(logLevel, testValue);

            var entries = GetEventRecords(el.Log).TakeWhile(e => e.TimeCreated > loggedNotBefore).ToList();

            //debug-> error
            EntryExists(entries, testValue, target.Source, eventLogEntryType);
        }
コード例 #3
0
ファイル: AsyncTaskTargetTest.cs プロジェクト: zsybupt/NLog
        public void AsyncTaskTarget_TestTimeout()
        {
            RetryingIntegrationTest(3, () =>
            {
                ILogger logger = LogManager.GetCurrentClassLogger();

                var asyncTarget = new AsyncTaskTestTarget
                {
                    Layout             = "${level}",
                    TaskTimeoutSeconds = 1
                };

                SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace);

                logger.Trace("TTT");
                logger.Debug("TIMEOUT");
                logger.Info("III");
                logger.Warn("WWW");
                logger.Error("EEE");
                logger.Fatal("FFF");
                Assert.True(asyncTarget.WaitForWriteEvent());
                Assert.NotEmpty(asyncTarget.Logs);
                LogManager.Flush();
                Assert.Equal(5, asyncTarget.Logs.Count);
                while (asyncTarget.Logs.TryDequeue(out var logEventMessage))
                {
                    Assert.Equal(-1, logEventMessage.IndexOf("Debug|"));
                }

                LogManager.Configuration = null;
            });
コード例 #4
0
ファイル: DmdExt.cs プロジェクト: BlameTheTank/dmd-extensions
        public DmdExt()
        {
            // setup logger
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            var assemblyPath  = Path.GetDirectoryName(new Uri(Assembly.GetExecutingAssembly().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
            _config       = new Configuration();
            _altcolorPath = GetColorPath();

            Logger.Info("Starting VPinMAME API through {0}.exe.", System.Diagnostics.Process.GetCurrentProcess().ProcessName);
        }
コード例 #5
0
        /// <summary>
        /// NLog Setup
        /// </summary>
        public static LoggingConfiguration Initialize()
        {
            // Create NLog configuration object
            var config = new LoggingConfiguration();

            // Create targets and add them to the configuration
            var fileTarget = GetFileTarget();

            config.AddTarget(fileTarget);

            // Define logging rules
            LoggingRule logRule = new LoggingRule("*", LogLevel.Trace, fileTarget);

            // Define filter to ignore logs from Microsoft DLLs
            var filterToIgnoreAllMicrosoftLogs = new ConditionBasedFilter
            {
                Condition = "starts-with(logger, 'Microsoft.')",
                Action    = FilterResult.Ignore
            };

            logRule.Filters.Add(filterToIgnoreAllMicrosoftLogs);

            config.LoggingRules.Add(logRule);

            // Define wrappers
            var asyncWrapper = GetAsyncTargetWrapper();

            asyncWrapper.WrappedTarget = fileTarget;
            SimpleConfigurator.ConfigureForTargetLogging(asyncWrapper, LogLevel.Trace);

            // Activate the configuration
            LogManager.Configuration = config;
            return(config);
        }
コード例 #6
0
        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
        }
コード例 #7
0
        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;
            }
        }
コード例 #8
0
        public void AsyncTaskTarget_TestLogging()
        {
            ILogger logger = LogManager.GetCurrentClassLogger();

            var asyncTarget = new AsyncTaskTestTarget();

            asyncTarget.Layout = "${threadid}|${level}|${message}";

            SimpleConfigurator.ConfigureForTargetLogging(asyncTarget, LogLevel.Trace);
            Assert.True(asyncTarget.Logs.Count == 0);
            logger.Trace("TTT");
            logger.Debug("DDD");
            logger.Info("III");
            logger.Warn("WWW");
            logger.Error("EEE");
            logger.Fatal("FFF");
            System.Threading.Thread.Sleep(50);
            Assert.True(asyncTarget.Logs.Count != 0);
            LogManager.Flush();
            Assert.True(asyncTarget.Logs.Count == 6);
            while (asyncTarget.Logs.Count > 0)
            {
                string logEventMessage = asyncTarget.Logs.Dequeue();
                Assert.Equal(0, logEventMessage.IndexOf(System.Threading.Thread.CurrentThread.ManagedThreadId.ToString() + "|"));
            }

            LogManager.Configuration = null;
        }
コード例 #9
0
ファイル: FileTargetTests.cs プロジェクト: parshim/NLog
        public void FileTarget_InvalidFileNameCorrection()
        {
            var tempFile                  = Path.GetTempFileName();
            var invalidTempFile           = tempFile + Path.GetInvalidFileNameChars()[0];
            var expectedCorrectedTempFile = tempFile + "_";

            try
            {
                var ft = new FileTarget
                {
                    FileName             = SimpleLayout.Escape(invalidTempFile),
                    LineEnding           = LineEndingMode.LF,
                    Layout               = "${level} ${message}",
                    OpenFileCacheTimeout = 0
                };

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Fatal);

                logger.Fatal("aaa");
                LogManager.Configuration = null;
                AssertFileContents(expectedCorrectedTempFile, "Fatal aaa\n", Encoding.UTF8);
            }
            finally
            {
                if (File.Exists(invalidTempFile))
                {
                    File.Delete(invalidTempFile);
                }
                if (File.Exists(expectedCorrectedTempFile))
                {
                    File.Delete(expectedCorrectedTempFile);
                }
            }
        }
コード例 #10
0
        public void WriteEventLogEntry()
        {
            var target = new EventLogTarget();

            //The Log to write to is intentionally lower case!!
            target.Log = "application";

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Debug);
            var logger = LogManager.GetLogger("WriteEventLogEntry");
            var el     = new EventLog(target.Log);

            var latestEntryTime = el.Entries.Cast <EventLogEntry>().Max(n => n.TimeWritten);


            var testValue = Guid.NewGuid();

            logger.Debug(testValue.ToString());

            var entryExists = (from entry in el.Entries.Cast <EventLogEntry>()
                               where entry.TimeWritten >= latestEntryTime &&
                               entry.Message.Contains(testValue.ToString())
                               select entry).Any();

            Assert.True(entryExists);
        }
コード例 #11
0
ファイル: FileTargetTests.cs プロジェクト: tmpkus/openvss
        public void CreateDirsTest()
        {
            // create the file in a not-existent
            // directory which forces creation
            string tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            string tempFile = Path.Combine(tempPath, "file.txt");

            try
            {
                FileTarget ft = new FileTarget();
                ft.FileName   = tempFile;
                ft.LineEnding = FileTarget.LineEndingMode.LF;
                ft.Layout     = "${level} ${message}";

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");
                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.ASCII);
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
コード例 #12
0
        private void InitializeLogging()
        {
            var currentConfig = LogManager.Configuration;

            if (currentConfig == null)
            {
                var binDirectory =
                    new Uri(Path.GetDirectoryName(Assembly.GetExecutingAssembly().GetName().CodeBase)).LocalPath;
                var configFile = Path.Combine(binDirectory, "NLog.config");

                if (File.Exists(configFile))
                {
                    var newConfig = new XmlLoggingConfiguration(configFile);
                    LogManager.Configuration = newConfig;
                    currentConfig            = LogManager.Configuration;
                }
                else
                {
                    var localPath  = GetLocalPath();
                    var logDirPath = Path.Combine(localPath, "logs");

                    SimpleConfigurator.ConfigureForFileLogging(Path.Combine(logDirPath, "ApplicationLog.log"));
                }
            }

            UpdateConfig(currentConfig);

            LogManager.Configuration = currentConfig;
        }
コード例 #13
0
        // All shared initialization
        public static void Init()
        {
            SimpleConfigurator.ConfigureForConsoleLogging(LogLevel.Info); // Doesnt seem to work anymore?!
            SetupNlog.Initialize("Test Runner");
            CommonBase.AssemblyLoader = GetAssemblyLoader();
            // Use to Reset the various common instances
            // Normally the EA instance is created in the AppBootStrapper, and Dependency injected into ShellViewModel
            Common.App   = new Common.AppCommon();
            Common.Paths = new PathConfiguration();
            // Must set AppPath to curdir, otherwise we end up somewhere in test heaven
            // Also keep the test configuration and temp data separate from production
            Common.App.InitLocalWithCleanup("Test Runner");
            var ea = new EventAggregator();

            Cheat.SetServices(new CheatImpl(ea, new Mediator(null, null)));
            DomainEvilGlobal.Settings = new UserSettings();

            /*
             * Tools.RegisterServices(new ToolsServices(new ProcessManager(),
             *  new Lazy<IWCFClient>(() => new WCFClient()),
             *  new Lazy<IGeoIpService>(() => new GeoIpService()), new CompressionUtil()));
             */
            ReSetupTools();

            if (!SingleSetup)
            {
                new AssemblyHandler().Register();
                SingleSetup = true;
            }
        }
コード例 #14
0
        public void LogEntryWithStaticEventIdAndCategoryInTargetLayout()
        {
            var rnd      = new Random();
            int eventId  = rnd.Next(1, short.MaxValue);
            int category = rnd.Next(1, short.MaxValue);
            var target   = CreateEventLogTarget(null, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000);

            target.EventId  = new SimpleLayout(eventId.ToString());
            target.Category = new SimpleLayout(category.ToString());
            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            var logger = LogManager.GetLogger("WriteEventLogEntry");

            logger.Log(LogLevel.Error, "Simple Test Message");
            var eventLog             = new EventLog(target.Log);
            var entries              = GetEventRecords(eventLog.Log).ToList();
            var expectedProviderName = target.GetFixedSource();
            var filtered             = entries.Where(entry =>
                                                     entry.ProviderName == expectedProviderName &&
                                                     HasEntryType(entry, EventLogEntryType.Error)
                                                     );

            Assert.Equal(1, filtered.Count());
            var record = filtered.First();

            Assert.Equal(eventId, record.Id);
            Assert.Equal(category, record.Task);
        }
コード例 #15
0
ファイル: EventLogTargetTests.cs プロジェクト: shadowca/NLog
        private static IEnumerable <EventRecord> Write(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType, string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate)
        {
            var target = CreateEventLogTarget(entryType, "NLog.UnitTests" + Guid.NewGuid().ToString("N"), overflowAction);

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            var logger = LogManager.GetLogger("WriteEventLogEntry");

            logger.Log(logLevel, logMessage);

            var eventLog = new EventLog(target.Log);

            var entries = GetEventRecords(eventLog.Log).ToList();

            var expectedSource = target.GetFixedSource();

            var filteredEntries = entries.Where(entry =>
                                                entry.ProviderName == expectedSource &&
                                                HasEntryType(entry, expectedEventLogEntryType)
                                                );

            if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > MaxMessageSize)
            {
                Assert.False(filteredEntries.Any(), string.Format("No message is expected. But {0} message(s) found entry of type '{1}' from source '{2}'.", filteredEntries.Count(), expectedEventLogEntryType, expectedSource));
            }
            else
            {
                Assert.True(filteredEntries.Any(), string.Format("Failed to find entry of type '{0}' from source '{1}'", expectedEventLogEntryType, expectedSource));
            }

            return(filteredEntries);
        }
コード例 #16
0
ファイル: MemoryTargetTests.cs プロジェクト: w04301706/NLog
        public void MemoryTarget_EmptyMessageTest()
        {
            ILogger logger = LogManager.GetCurrentClassLogger();

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

            SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);

            logger.Trace("TTT");
            logger.Debug(String.Empty);
            logger.Info("III");
            logger.Warn("");
            logger.Error("EEE");

            LogManager.Configuration = null;

            Assert.True(memoryTarget.Logs.Count() == 5);
            Assert.True(memoryTarget.Logs[0] == "Trace TTT");
            Assert.True(memoryTarget.Logs[1] == "Debug ");
            Assert.True(memoryTarget.Logs[2] == "Info III");
            Assert.True(memoryTarget.Logs[3] == "Warn ");
            Assert.True(memoryTarget.Logs[4] == "Error EEE");
        }
コード例 #17
0
        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
        }
コード例 #18
0
ファイル: Helpers.cs プロジェクト: pinchuque/DoubleJ
        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);
        }
コード例 #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.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;
            }
        }
コード例 #20
0
        public void LogEntryWithDynamicEventIdAndCategory()
        {
            var rnd      = new Random();
            int eventId  = rnd.Next(1, short.MaxValue);
            int category = rnd.Next(1, short.MaxValue);
            var target   = CreateEventLogTarget <EventLogTarget>("NLog.UnitTests" + Guid.NewGuid().ToString("N"), EventLogTargetOverflowAction.Truncate, 5000);

            target.EventId  = new SimpleLayout("${event-properties:EventId}");
            target.Category = new SimpleLayout("${event-properties:Category}");
            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);
            var          logger   = LogManager.GetLogger("WriteEventLogEntry");
            LogEventInfo theEvent = new LogEventInfo(LogLevel.Error, "TestLoggerName", "Simple Message");

            theEvent.Properties["EventId"]  = eventId;
            theEvent.Properties["Category"] = category;
            logger.Log(theEvent);
            var eventLog             = new EventLog(target.Log);
            var entries              = GetEventRecords(eventLog.Log).ToList();
            var expectedProviderName = target.GetFixedSource();
            var filtered             = entries.Where(entry =>
                                                     entry.ProviderName == expectedProviderName &&
                                                     HasEntryType(entry, EventLogEntryType.Error)
                                                     );

            Assert.Single(filtered);
            var record = filtered.First();

            Assert.Equal(eventId, record.Id);
            Assert.Equal(category, record.Task);
        }
コード例 #21
0
        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;
            }
        }
コード例 #22
0
        private static IEnumerable <EventRecord> WriteWithMock(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType,
                                                               string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = MaxMessageLength)
        {
            var target = CreateEventLogTarget <EventLogTargetMock>("NLog.UnitTests" + Guid.NewGuid().ToString("N"), overflowAction, maxMessageLength, entryType);

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            var logger = LogManager.GetLogger("WriteEventLogEntry");

            logger.Log(logLevel, logMessage);

            var entries = target.CapturedEvents;

            var expectedSource = target.GetFixedSource();

            var filteredEntries = entries.Where(entry =>
                                                entry.ProviderName == expectedSource &&
                                                HasEntryType(entry, expectedEventLogEntryType)
                                                );

            if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength)
            {
                Assert.False(filteredEntries.Any(),
                             $"No message is expected. But {filteredEntries.Count()} message(s) found entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'.");
            }
            else
            {
                Assert.True(filteredEntries.Any(),
                            $"Failed to find entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'");
            }

            return(filteredEntries);
        }
コード例 #23
0
        private void ConfigureSharedFile(string mode)
        {
            FileTarget ft = new FileTarget();

            ft.FileName             = "${basedir}/file.txt";
            ft.Layout               = "${threadname} ${message}";
            ft.KeepFileOpen         = true;
            ft.OpenFileCacheTimeout = 10;
            ft.OpenFileCacheSize    = 1;
            ft.LineEnding           = LineEndingMode.LF;

            switch (mode)
            {
            case "async":
                SimpleConfigurator.ConfigureForTargetLogging(new AsyncTargetWrapper(ft, 100, AsyncTargetWrapperOverflowAction.Grow), LogLevel.Debug);
                break;

            case "buffered":
                SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100), LogLevel.Debug);
                break;

            case "buffered_timed_flush":
                SimpleConfigurator.ConfigureForTargetLogging(new BufferingTargetWrapper(ft, 100, 10), LogLevel.Debug);
                break;

            default:
                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);
                break;
            }
        }
        public void ExceptionTest()
        {
            var target = new MemoryTarget {
                Layout = @"${exception:format=tostring}"
            };

            SimpleConfigurator.ConfigureForTargetLogging(target);
            var logger = LogManager.GetCurrentClassLogger();

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

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

                Assert.Equal(2, target.Logs.Count);
                Assert.NotNull(target.Logs[0]);
                Assert.NotNull(target.Logs[1]);
                Assert.Equal(target.Logs[0], target.Logs[1]);
            }
        }
コード例 #25
0
        public DmdDevice()
        {
            _currentFrameFormat    = new BehaviorSubject <FrameFormat>(FrameFormat.Rgb24);
            _vpmGray2Source        = new VpmGray2Source(_currentFrameFormat);
            _vpmGray4Source        = new VpmGray4Source(_currentFrameFormat);
            _vpmRgb24Source        = new VpmRgb24Source(_currentFrameFormat);
            _vpmAlphaNumericSource = new VpmAlphaNumericSource(_currentFrameFormat);

            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;
                if (string.IsNullOrEmpty(_sha))
                {
                    _fullVersion = _version;
                }
                else
                {
                    _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);
        }
コード例 #26
0
ファイル: FileTargetTests.cs プロジェクト: mattyway/NLog
        public void CreateDirsTest()
        {
            var tempPath = Path.Combine(Path.GetTempPath(), Guid.NewGuid().ToString());
            var tempFile = Path.Combine(tempPath, "file.txt");

            try
            {
                var ft = new FileTarget
                {
                    FileName   = tempFile,
                    LineEnding = LineEndingMode.LF,
                    Layout     = "${level} ${message}"
                };

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");
                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
            }
            finally
            {
                LogManager.Configuration = null;
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
                if (Directory.Exists(tempPath))
                {
                    Directory.Delete(tempPath, true);
                }
            }
        }
コード例 #27
0
 /// <summary>
 /// Initializes a new instance of the <see cref="NLogTests"/> class.
 /// </summary>
 static NLogTests()
 {
     testTarget = new TestTarget {
         Layout = "${callsite}"
     };
     SimpleConfigurator.ConfigureForTargetLogging(testTarget, LogLevel.Trace);
 }
コード例 #28
0
ファイル: FileTargetTests.cs プロジェクト: mattyway/NLog
        public void SimpleFileTest1()
        {
            var tempFile = Path.GetTempFileName();

            try
            {
                var ft = new FileTarget
                {
                    FileName             = SimpleLayout.Escape(tempFile),
                    LineEnding           = LineEndingMode.LF,
                    Layout               = "${level} ${message}",
                    OpenFileCacheTimeout = 0
                };

                SimpleConfigurator.ConfigureForTargetLogging(ft, LogLevel.Debug);

                logger.Debug("aaa");
                logger.Info("bbb");
                logger.Warn("ccc");
                LogManager.Configuration = null;
                AssertFileContents(tempFile, "Debug aaa\nInfo bbb\nWarn ccc\n", Encoding.UTF8);
            }
            finally
            {
                if (File.Exists(tempFile))
                {
                    File.Delete(tempFile);
                }
            }
        }
コード例 #29
0
ファイル: MemoryTargetTests.cs プロジェクト: zy850580380/NLog
        public void MemoryTarget_ClearLogsTest()
        {
            ILogger logger = LogManager.GetCurrentClassLogger();

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

            SimpleConfigurator.ConfigureForTargetLogging(memoryTarget, LogLevel.Trace);

            logger.Warn("WWW");
            logger.Error("EEE");
            logger.Fatal("FFF");

            memoryTarget.Logs.Clear();
            logger.Trace("TTT");
            logger.Debug("DDD");
            logger.Info("III");

            LogManager.Configuration = null;

            Assert.True(memoryTarget.Logs.Count() == 3);
            Assert.True(memoryTarget.Logs[0] == "Trace TTT");
            Assert.True(memoryTarget.Logs[1] == "Debug DDD");
            Assert.True(memoryTarget.Logs[2] == "Info III");
        }
コード例 #30
0
        public void MachineNameInPropertyIsRendered()
        {
            var layout = new JsonWithPropertiesLayout();

            layout.Properties.Add(new StructuredLoggingProperty("machinename", "${machinename}"));

            var target = new MemoryTarget
            {
                Name   = Guid.NewGuid().ToString(),
                Layout = layout
            };

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            TimeSource.Current = new FakeTimeSource();
            var logger = LogManager.GetCurrentClassLogger();

            var logEvent = new LogEventInfo(LogLevel.Trace, LoggerName, TestMessage);

            logger.Log(logEvent);

            Assert.That(target.Logs.Count, Is.EqualTo(1));

            var output = target.Logs[0];

            Assert.That(output, Does.Contain("\"machinename\":\""));
            Assert.That(output, Does.Not.Contain("${machinename}"));
        }