public void SimpleTest()
        {
            container.Register(Component.For(typeof(SimpleLoggingComponent)).Named("component1"));
            SimpleLoggingComponent test = container.Resolve <SimpleLoggingComponent>("component1");

            test.DoSomething();

            String         expectedLogOutput = String.Format("[INFO ] [{0}] - Hello world" + Environment.NewLine, typeof(SimpleLoggingComponent).FullName);
            MemoryAppender memoryAppender    = ((Hierarchy)LogManager.GetRepository()).Root.GetAppender("memory") as MemoryAppender;
            TextWriter     actualLogOutput   = new StringWriter();
            PatternLayout  patternLayout     = new PatternLayout("[%-5level] [%logger] - %message%newline");

            patternLayout.Format(actualLogOutput, memoryAppender.GetEvents()[0]);

            Assert.AreEqual(expectedLogOutput, actualLogOutput.ToString());

            container.Register(Component.For(typeof(SmtpServer)).Named("component2"));
            ISmtpServer smtpServer = container.Resolve <ISmtpServer>("component2");

            smtpServer.Start();
            smtpServer.InternalSend("*****@*****.**", "*****@*****.**", "We're looking for a few good porgrammars.");
            smtpServer.Stop();

            expectedLogOutput = String.Format("[DEBUG] [Castle.Facilities.Logging.Tests.Classes.SmtpServer] - Stopped" + Environment.NewLine, typeof(SimpleLoggingComponent).FullName);
            memoryAppender    = ((Hierarchy)LogManager.GetRepository()).Root.GetAppender("memory") as MemoryAppender;
            actualLogOutput   = new StringWriter();
            patternLayout     = new PatternLayout("[%-5level] [%logger] - %message%newline");

            Assert.AreEqual(memoryAppender.GetEvents().Length, 4);

            patternLayout.Format(actualLogOutput, memoryAppender.GetEvents()[3]);

            Assert.AreEqual(expectedLogOutput, actualLogOutput.ToString());
        }
Пример #2
0
        public void Can_Write_Fatal_With_Exception()
        {
            LogWriter.SetFactory(new Log4NetWriterFactory());

            LogWriter.GetLogger(this).Fatal("Testing Fatal with exception.", new Exception("Test Exception"));

            _memoryAppender.GetEvents().Any(le => le.Level == Level.Fatal).ShouldBeTrue();
        }
Пример #3
0
        public static void TestGetAll()
        {
            var _      = _client.SendAsync(new HttpRequestMessage(HttpMethod.Get, "http://example.org/test"), _cts.Token).Result;
            var events = _appender.GetEvents();

            events.ShouldNotBeEmpty();
            events.Select(x => x.RenderedMessage).ShouldContain(" GET http://example.org/test WebApiContrib.Tracing.Log4Net.Tests.Controllers.TestController Info loaded: 2");
        }
Пример #4
0
        public void EnabledLibLogSubscriberAddsTraceData()
        {
            // Assert that the Log4Net log provider is correctly being used
            Assert.IsType <Log4NetLogProvider>(LogProvider.CurrentLogProvider);

            // Instantiate a tracer for this test with default settings and set LogsInjectionEnabled to TRUE
            var tracer = LoggingProviderTestHelpers.InitializeTracer(enableLogsInjection: true);

            LoggingProviderTestHelpers.PerformParentChildScopeSequence(tracer, _logger, _logProvider.OpenMappedContext, out var parentScope, out var childScope);

            // Filter the logs
            List <LoggingEvent> filteredLogs = new List <LoggingEvent>(_memoryAppender.GetEvents());

            filteredLogs.RemoveAll(log => !log.MessageObject.ToString().Contains(LoggingProviderTestHelpers.LogPrefix));

            int          logIndex = 0;
            LoggingEvent logEvent;

            // Scope: Parent scope
            // Custom property: N/A
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(parentScope);
            Assert.DoesNotContain(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());

            // Scope: Parent scope
            // Custom property: SET
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(parentScope);
            Assert.Contains(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());
            Assert.Equal <int>(LoggingProviderTestHelpers.CustomPropertyValue, int.Parse(logEvent.Properties[LoggingProviderTestHelpers.CustomPropertyName].ToString()));

            // Scope: Child scope
            // Custom property: SET
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(childScope);
            Assert.Contains(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());
            Assert.Equal <int>(LoggingProviderTestHelpers.CustomPropertyValue, int.Parse(logEvent.Properties[LoggingProviderTestHelpers.CustomPropertyName].ToString()));

            // Scope: Parent scope
            // Custom property: SET
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(parentScope);
            Assert.Contains(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());
            Assert.Equal <int>(LoggingProviderTestHelpers.CustomPropertyValue, int.Parse(logEvent.Properties[LoggingProviderTestHelpers.CustomPropertyName].ToString()));

            // EXISTING: Verify the log event is decorated with the parent scope properties
            // Scope: Parent scope
            // Custom property: N/A
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(parentScope);
            Assert.DoesNotContain(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());

            // Scope: Default values of TraceId=0,SpanId=0
            // Custom property: N/A
            logEvent = filteredLogs[logIndex++];
            logEvent.Contains(traceId: 0, spanId: 0);
            Assert.DoesNotContain(LoggingProviderTestHelpers.CustomPropertyName, logEvent.Properties.GetKeys());
        }
Пример #5
0
        private string GetSingleMessage()
        {
            LoggingEvent loggingEvent = memoryAppender.GetEvents().Single();

            return(string.Format("{0}|{1}|{2}",
                                 loggingEvent.Level,
                                 loggingEvent.MessageObject,
                                 loggingEvent.ExceptionObject != null ? loggingEvent.ExceptionObject.Message : string.Empty));
        }
Пример #6
0
        public void Can_open_nested_diagnostics_context()
        {
            using (_logProvider.OpenNestedContext("context"))
            {
                _sut.Info("m");
                var loggingEvent = _memoryAppender.GetEvents().Single();

                loggingEvent.Properties.GetKeys().Should().Contain("NDC");
                loggingEvent.Properties["NDC"].Should().Be("context");
            }
        }
Пример #7
0
        /// <summary>
        /// Retrieves the SQL statement from the log events
        /// </summary>
        /// <remarks>
        /// The SQL statement log message is in the following format
        /// SQL: {sql statement}
        /// </remarks>
        protected string GetSQLStatement()
        {
            var loggingEvents = _loggedEvents.GetEvents();

            foreach (LoggingEvent logEvent in loggingEvents)
            {
                if (logEvent.LoggerName == "LinqToExcel.SQL")
                {
                    return(logEvent.RenderedMessage.Split(";".ToCharArray())[0]);
                }
            }
            return("");
        }
Пример #8
0
        private int Contains(String loggingStatement)
        {
            LoggingEvent[] eventList = appender.GetEvents();
            int            index     = 0;

            for (int i = 0; i < eventList.Length; i++)
            {
                if (EqualsMessageByTemplate(eventList[i].RenderedMessage, loggingStatement))
                {
                    index++;
                }
            }
            return(index);
        }
Пример #9
0
        public void Check01LoggerAOk()
        {
            //SETUP

            //ATTEMPT
            _loggerA.Verbose("a message");

            //VERIFY
            var logs = _log4NetMemoryLog.GetEvents();

            logs.Length.ShouldEqual(1);
            logs[0].LoggerName.ShouldEqual("A");
            logs[0].RenderedMessage.ShouldEqual("a message");
        }
        public static List <TrinityObjectiveInfo> GetObjectiveInfo()
        {
            // Why you make things so difficult for me nesox?
            var objectives = new List <TrinityObjectiveInfo>();
            var logger     = (log4net.Repository.Hierarchy.Logger)log4net.LogManager.GetLogger(typeof(QuestObjectiveInfo))?.Logger;

            if (logger == null)
            {
                return(objectives);
            }
            var dbLogger = (log4net.Repository.Hierarchy.Logger)log4net.LogManager.GetLogger(typeof(Demonbuddy.MainWindow))?.Logger;

            if (dbLogger == null)
            {
                return(objectives);
            }
            var asyncAppender = dbLogger.Parent.Appenders.ToArray().OfType <Zeta.Common.Logger.AsyncAppender>().FirstOrDefault();
            var repository    = (Hierarchy)LogManager.GetRepository();

            repository.Root.RemoveAppender(asyncAppender);
            var appender = new MemoryAppender();

            logger.AddAppender(appender);
            QuestObjectiveInfo.DumpObjectives();
            objectives.AddRange(appender.GetEvents().Select(e => new TrinityObjectiveInfo(e.RenderedMessage)));
            logger.RemoveAppender(appender);
            repository.Root.AddAppender(asyncAppender);
            return(objectives);
        }
Пример #11
0
        public async Task TransportHost_LogsError_WhenStartFails()
        {
            // arrange
            LogManager.Manager.AddListener(Log4NetStandardLogListener.Instance);
            var appender = new MemoryAppender();

            log4net.Config.BasicConfigurator.Configure(appender);
            const string errorMessage = "error message";

            _mockNServiceBusServer.Setup(m => m.Start(It.IsAny <string>(), It.IsAny <bool>())).ReturnsAsync(errorMessage);

            // act
            await _transportHost.Start(false, () => true);

            // Give the logging time to finish
            Thread.Sleep(1000);
            var logEntries = appender.GetEvents();

            Log4NetStandardLogListener.Clear();
            LogManager.Manager.ClearListeners();

            // assert
            Assert.AreEqual(1, logEntries.Length);
            Assert.AreEqual(errorMessage, logEntries.Single().RenderedMessage);
            _mockNServiceBusServer.Verify(m => m.Start(It.IsAny <string>(), It.IsAny <bool>()), Times.Once);
        }
Пример #12
0
        static void Main(string[] args)
        {
            var logger = LogManager.GetLogger(typeof(Program));

            LogicalThreadContext.Stacks["activity"].Push("First Activity");
            LogicalThreadContext.Stacks["activity"].Push("Second Activity");
            logger.Info("File Appender with JSON formatter");

            //add a memory appender so we don't seem crazy.
            var hierarchy = (Hierarchy)LogManager.GetRepository();

            hierarchy.Root.RemoveAllAppenders();
            var layout = new JsonLayout();

            layout.ActivateOptions();
            var memoryAppender = new MemoryAppender {
                Layout = layout
            };

            memoryAppender.ActivateOptions();
            hierarchy.Root.AddAppender(memoryAppender);
            hierarchy.Configured = true;
            logger.Info("Memory Appender with JSON Formatter");

            //have to get it out of the memoryappendor to trigger the code.
            memoryAppender.Layout.Format(Console.Out, memoryAppender.GetEvents()[0]);
        }
Пример #13
0
        /// <summary>
        /// Handles when the <see cref="ScreenManager"/> updates.
        /// </summary>
        /// <param name="screenManager">The screen manager.</param>
        /// <param name="e">The <see cref="System.EventArgs"/> instance containing the event data.</param>
        void ScreenManager_Updated(IScreenManager screenManager, EventArgs e)
        {
            // The logger we use to grab log messages and output to the console will continue to queue messages
            // indefinitely until it is cleared. Because of this, we can't just flush the log by overriding
            // the screen's Update method. Instead, we have this event hook for when the ScreenManager
            // updates so we can clear out the log buffer every tick.

            // Get the latest events
            LoggingEvent[] events;
            try
            {
                events = _logger.GetEvents();
            }
            catch (ArgumentException)
            {
                // There is some bug in the _logger.GetEvents() that can throw this exception...
                return;
            }

            _logger.Clear();

            // Ensure there are events
            if (events != null && events.Length > 0)
            {
                foreach (var ev in events)
                {
                    var styledText = new StyledText(ev.RenderedMessage, ev.Level.GetColor());
                    _txtOutput.AppendLine(styledText);
                }
            }

            // Move to the last line in the log textbox
            _txtOutput.LineBufferOffset = Math.Max(0, _txtOutput.LineCount - _txtOutput.MaxVisibleLines);
        }
Пример #14
0
        public void Test()
        {
            // Get the default hierarchy
            var h = LogManager.GetLoggerRepository() as Hierarchy;
            var m = new MemoryAppender();

            h.Root.AddAppender(m);
            log.Debug("test");
            var l1a = new L1("a");
            var l1b = new L1("b");

            l1a.L1CallL2();
            l1b.L1CallL2();
            var events = m.GetEvents();

            CheckEvent(0, events, typeof(ContextLoggerTests), "Test", "test");
            CheckEvent(1, events, typeof(L1), ".ctor", "[a] L1 logger created");
            CheckEvent(2, events, typeof(L1), ".ctor", "[b] L1 logger created");
            CheckEvent(3, events, typeof(L1), "L1CallL2", "[a] L1 calling L2");
            CheckEvent(4, events, typeof(L2), ".ctor", "[a] L2 logger created");
            CheckEvent(5, events, typeof(L2), "L2Call", "[a] L2 call");
            CheckEvent(6, events, typeof(L1), "L1CallL2", "[b] L1 calling L2");
            CheckEvent(7, events, typeof(L2), ".ctor", "[b] L2 logger created");
            CheckEvent(8, events, typeof(L2), "L2Call", "[b] L2 call");
            h.Root.RemoveAppender(m);
        }
        private void CheckErrors(CertificateTask task, MemoryAppender memoryAppender, TestCertificateSourceHandler handler, uint errorCount, bool idEquals = false)
        {
            var firstEvents = memoryAppender.GetEvents();

            var firstErrors = firstEvents.Where(item => item.Level >= Level.Warn);

            Assert.That(firstErrors.Count(), Is.EqualTo(errorCount), firstErrors.Implode(e => e.MessageObject));

            //кол-во ошибок должно быть равно 1
            Assert.That(handler.Errors.Count, Is.EqualTo(1));

            var info = handler.Errors[task.GetErrorId()];

            Assert.That(info.ErrorCount, Is.EqualTo(errorCount));
            Assert.That(info.Exception.Message, Is.StringStarting("Возникла ошибка при обработке задачи: "));
            if (idEquals)
            {
                Assert.That(info.Task.Id, Is.EqualTo(task.Id));
            }
            Assert.That(info.Task.CertificateSource.Id, Is.EqualTo(task.CertificateSource.Id));
            Assert.That(info.Task.CatalogProduct.Id, Is.EqualTo(task.CatalogProduct.Id));
            Assert.That(info.Task.SerialNumber, Is.EqualTo(task.SerialNumber));

            //Задача должна быть удалена из базы данных
            var deletedTask = CertificateTask.Queryable.FirstOrDefault(t => t.Id == task.Id);

            Assert.That(deletedTask, Is.Null);
        }
        private void SendErrorToProvider(DocSourceHandlerForTesting handler, MiniMailException exception, Mime sourceLetter)
        {
            try {
                var memoryAppender = new MemoryAppender();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                handler.SendErrorLetterToSupplier(exception, sourceLetter);

                var events = memoryAppender.GetEvents();
                Assert.That(
                    events.Length,
                    Is.EqualTo(0),
                    "Ошибки при обработки задач сертификатов:\r\n{0}",
                    events.Select(item => {
                    if (string.IsNullOrEmpty(item.GetExceptionString()))
                    {
                        return(item.RenderedMessage);
                    }
                    else
                    {
                        return(item.RenderedMessage + Environment.NewLine + item.GetExceptionString());
                    }
                }).Implode("\r\n"));
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }
Пример #17
0
        private static LoggingEvent[] LogInstanceMethodHelper(ILog loggingInstance, string debugMessage, Exception exceptionMessage = null)
        {
            //if (!LogManager.GetRepository().Configured)
            //    BasicConfigurator.Configure();  //If you need to know how to configure a repository

            //Use hierarchy to to get Repository and then get Root to access IAppenderAttachable
            var hierarchy = (Hierarchy)LogManager.GetRepository();
            //Remove all appenders and setup a memory appender so that we don't write to the database
            var attachable = hierarchy.Root as IAppenderAttachable;

            //if (attachable == null) return ("IappenderAttachable is null");
            attachable.RemoveAllAppenders();
            var appender = new MemoryAppender();

            attachable.AddAppender(appender);
            if (exceptionMessage == null)
            {
                EntLogger.LogDebug(loggingInstance, debugMessage);
            }
            else
            {
                EntLogger.LogException(loggingInstance, debugMessage, exceptionMessage);
            }

            var loggingEvents = appender.GetEvents();

            //Cleanup
            attachable.RemoveAppender(appender);
            return(loggingEvents);
        }
Пример #18
0
    protected void Page_Load(object sender, EventArgs e)
    {
        // gather log4net output with small hack to get results...
        ILoggerRepository repository = LogManager.GetRepository();

        IAppender[]    appenders = repository.GetAppenders();
        MemoryAppender appender  = null;

        foreach (IAppender a in appenders)
        {
            if (a is MemoryAppender)
            {
                // we found our appender to look results from
                appender = a as MemoryAppender;
                break;
            }
        }

        if (appender != null)
        {
            appender.Clear();
            fulfillmentService.ProcessCustomer(customerEditController.CurrentCustomer.Id);
            LoggingEvent[] events       = appender.GetEvents();
            StringWriter   stringWriter = new StringWriter();
            PatternLayout  layout       = new PatternLayout("%date{HH:mm:ss} %-5level %logger{1}: %message<br />");
            foreach (LoggingEvent loggingEvent in events)
            {
                layout.Format(stringWriter, loggingEvent);
            }

            results.Text = stringWriter.ToString();
        }
    }
Пример #19
0
        public void FilterDefWithoutReference()
        {
            const string filterDef = @"<hibernate-mapping xmlns='urn:nhibernate-mapping-2.2' >

	<filter-def name='LiveFilter'>
		<filter-param name='LiveParam' type='boolean'/>
	</filter-def>

</hibernate-mapping>";

            var cfg = GetConfiguration();

            cfg.AddXmlString(filterDef);
            var memoryAppender = new MemoryAppender();

            BasicConfigurator.Configure(memoryAppender);
            try
            {
                cfg.BuildSessionFactory();

                var wholeLog = String.Join("\r\n", memoryAppender.GetEvents().Select(x => x.RenderedMessage).ToArray());
                Assert.That(wholeLog, Does.Contain("filter-def for filter named"));
                Assert.That(wholeLog, Does.Contain("was never used to filter classes nor collections."));
            }
            finally
            {
                LogManager.Shutdown();
            }
        }
Пример #20
0
        public void LoggingExceptionTest()
        {
            const string TITLE_MSG     = "Exception Message";
            const string EXCEPTION_MSG = "ImageGen Service Logging Exception-test";

            var appender = new MemoryAppender();

            log4net.Config.BasicConfigurator.Configure(appender);

            var exc = new Exception(EXCEPTION_MSG);

            Log.Fatal(exc);
            Log.Fatal(TITLE_MSG, exc);

            Thread.Sleep(1000);

            var logEntries = appender.GetEvents();

            // Remove Listeners
            Log4NetStandardLogListener.Clear();
            LogManager.Manager.ClearListeners();

            // Check for Exception message
            Assert.IsTrue(logEntries[0].RenderedMessage.Contains(EXCEPTION_MSG));

            // Check for text message
            Assert.IsTrue(logEntries[1].RenderedMessage.Contains(TITLE_MSG));
        }
        public IEnumerable <LoggingEvent> GetLoggingEvents(LoggingVerbosity verbosity)
        {
            Level logginglevel;

            #region Convert LoggingVerbosity to Level
            switch (verbosity)
            {
            case LoggingVerbosity.Error:
                logginglevel = Level.Error;
                break;

            case LoggingVerbosity.Warning:
                logginglevel = Level.Warn;
                break;

            case LoggingVerbosity.Info:
                logginglevel = Level.Info;
                break;

            default:
                logginglevel = Level.All;
                break;
            }
            #endregion

            return(_memoryAppender.GetEvents()
                   .Where(x => x.Level >= logginglevel));
        }
Пример #22
0
        public SamplesForm()
        {
            InitializeComponent();
            _buttonStorageScuVerify.Text = STR_Verify;

            if (String.IsNullOrEmpty(Properties.Settings.Default.ScpStorageFolder))
            {
                Properties.Settings.Default.ScpStorageFolder = Path.Combine(Path.GetTempPath(), "DicomImages");
            }

            _destinationSyntaxCombo.Items.Clear();
            _destinationSyntaxCombo.Items.Add(TransferSyntax.ExplicitVrLittleEndian);
            foreach (TransferSyntax syntax in DicomCodecRegistry.GetCodecTransferSyntaxes())
            {
                _destinationSyntaxCombo.Items.Add(syntax);
            }

            ComboBoxQueryScuQueryTypeSelectedIndexChanged(null, null);
            ComboBoxMoveScuQueryTypeSelectedIndexChanged(null, null);

            // Logging stuff
            Closing += SamplesFormClosing;
            BasicConfigurator.Configure(_appender);
            _timer = new Timer(delegate
            {
                try
                {
                    LoggingEvent[] events = _appender.GetEvents();
                    if (events != null && events.Length > 0)
                    {
                        // if there are events, we clear them from the logger,
                        // since we're done with them
                        _appender.Clear();
                        foreach (LoggingEvent ev in events)
                        {
                            // the line we want to log
                            string line = String.Format("({0}) {1} {2} [{3}]: {4}\r\n",
                                                        ev.ThreadName,
                                                        ev.TimeStamp.ToShortDateString(),
                                                        ev.TimeStamp.ToLongTimeString(), ev.Level,
                                                        ev.RenderedMessage);

                            AppendText(line);

                            if (ev.ExceptionObject != null)
                            {
                                AppendText(string.Format("{0}: {1}\r\n", ev.ExceptionObject, ev.ExceptionObject.Message));
                                AppendText("Stack Trace:\r\n" + ev.ExceptionObject.StackTrace + "\r\n");
                            }
                        }
                    }
                }
                catch (Exception x)
                {
                    Platform.Log(LogLevel.Error, x, "Unexpected exception with logging event");
                }
            }, null, 500);
            _timer.Start();
        }
Пример #23
0
        public void Database()
        {
            MemoryAppender memoryAppender = new MemoryAppender();

            BasicConfigurator.Configure(LogManager.GetLogger(typeof(SchemaExport)).Logger.Repository, memoryAppender);
            ActiveRecordStarter.CreateSchema();
            PropertyBag["events"] = memoryAppender.GetEvents();
        }
Пример #24
0
        public async Task HomeController_Index_LogInfoMessages()
        {
            // Arrange
            var mockRepo = new Mock <IBrainstormSessionRepository>();

            mockRepo.Setup(repo => repo.ListAsync())
            .ReturnsAsync(GetTestSessions());
            var controller = new HomeController(mockRepo.Object);

            // Act
            var result = await controller.Index();

            // Assert
            var logEntries = _appender.GetEvents();

            Assert.True(logEntries.Any(l => l.Level == Level.Info), "Expected Info messages in the logs");
        }
 public void CharacterizationTest(ProviderData receivedData, ProviderData existedData)
 {
     using (ApprovalResults.ForScenario(TestContext.CurrentContext.Test.Name))
     {
         var res = processor.ProcessProviderData(receivedData, existedData);
         var s   = res + "\n" + string.Join("\n", memoryAppender.GetEvents().Select(e => e.RenderedMessage));
         Approvals.Verify(s);
     }
 }
Пример #26
0
        public void Detail_Level_can_log()
        {
            Log.Detail("Entered Detail_Level_can_log");
            var loggingEvent = Appender.GetEvents().ToList().Last();

            Assert.AreEqual("DETAIL", loggingEvent.Level.Name);
            Assert.AreEqual(typeof(Tests).FullName, loggingEvent.LoggerName);
            Assert.AreEqual("Entered Detail_Level_can_log", loggingEvent.RenderedMessage);
        }
Пример #27
0
 /// <summary>
 /// Fills the text writer.
 /// </summary>
 /// <param name="sw">
 /// The sw.
 /// </param>
 /// <remarks>
 /// </remarks>
 private void FillTextWriter(TextWriter sw)
 {
     if (ma != null)
     {
         var events  = ma.GetEvents();
         var iLayout = (PatternLayout)ma.Layout;
         iLayout.Format(sw, events[events.GetUpperBound(0)]);
         ma.Clear();
     }
 }
Пример #28
0
        public string RenderedMessages()
        {
            var wholeMessage = new StringBuilder();

            foreach (var loggingEvent in _appender.GetEvents())
            {
                wholeMessage.AppendLine(loggingEvent.RenderedMessage);
            }
            return(wholeMessage.ToString());
        }
Пример #29
0
        public void GetAccess_WithAccessControlExcptionFromAccessControlListFinder()
        {
            AccessControlException expectedException = new AccessControlException();

            using (_clientTransaction.EnterNonDiscardingScope())
            {
                Expect.Call(_mockAclFinder.Find(_context)).Throw(expectedException);
            }
            _mocks.ReplayAll();

            AccessType[] accessTypes = _service.GetAccess(_context, _principalStub);

            _mocks.VerifyAll();
            Assert.That(accessTypes.Length, Is.EqualTo(0));
            LoggingEvent[] events = _memoryAppender.GetEvents();
            Assert.That(events.Length, Is.EqualTo(1));
            Assert.That(events[0].ExceptionObject, Is.SameAs(expectedException));
            Assert.That(events[0].Level, Is.EqualTo(Level.Error));
        }
        private void ProcessCertificatesWithLog(Action action)
        {
            if (session.Transaction.IsActive)
            {
                session.Transaction.Commit();
            }

            try {
                var memoryAppender = new MemoryAppender();
                memoryAppender.AddFilter(new LoggerMatchFilter {
                    AcceptOnMatch = true, LoggerToMatch = "PriceProcessor", Next = new DenyAllFilter()
                });
                BasicConfigurator.Configure(memoryAppender);

                try {
                    action();
                }
                catch {
                    var logEvents = memoryAppender.GetEvents();
                    Console.WriteLine(
                        "Ошибки при обработки задач сертификатов:\r\n{0}",
                        logEvents.Select(item => {
                        if (string.IsNullOrEmpty(item.GetExceptionString()))
                        {
                            return(item.RenderedMessage);
                        }
                        else
                        {
                            return(item.RenderedMessage + Environment.NewLine + item.GetExceptionString());
                        }
                    }).Implode("\r\n"));
                    throw;
                }

                var events = memoryAppender.GetEvents();
                var errors = events.Where(item => item.Level >= Level.Warn);
                Assert.That(errors.Count(), Is.EqualTo(0), "При обработки задач сертификатов возникли ошибки:\r\n{0}", errors.Select(item => item.RenderedMessage).Implode("\r\n"));
            }
            finally {
                LogManager.ResetConfiguration();
            }
        }