Пример #1
0
        public void DoubleInitializeTest()
        {
            var target = new MyTarget();
            target.Initialize(CommonCfg);
            target.Initialize(CommonCfg);

            // initialize was called once
            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Пример #2
0
        public void AutoFlushTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var wrapper = new AutoFlushTargetWrapper
            {
                WrappedTarget = myTarget,
            };

            myTarget.Initialize(null);
            wrapper.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            bool continuationHit = false;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationHit = true;
                    };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.IsTrue(continuationHit);
            Assert.IsNull(lastException);
            Assert.AreEqual(1, myTarget.FlushCount);
            Assert.AreEqual(1, myTarget.WriteCount);

            continuationHit = false;
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            Assert.IsTrue(continuationHit);
            Assert.IsNull(lastException);
            Assert.AreEqual(2, myTarget.WriteCount);
            Assert.AreEqual(2, myTarget.FlushCount);
        }
Пример #3
0
        public void InitializeTest()
        {
            var target = new MyTarget();
            target.Initialize(null);

            // initialize was called once
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Пример #4
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();
            using (target.Initialize(CommonCfg))
            {
            }

            // initialize and close were called once each
            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.CloseCount);
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Пример #5
0
        public void DoubleCloseTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();
            target.Close();

            // initialize and close were called once each
            Assert.Equal(1, target.InitializeCount);
            Assert.Equal(1, target.CloseCount);
            Assert.Equal(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
        }
Пример #6
0
        public void FlushTest()
        {
            var target = new MyTarget();
            List<Exception> exceptions = new List<Exception>();
            target.Initialize(CommonCfg);
            target.Flush(exceptions.Add);

            // flush was called
            Assert.AreEqual(1, target.FlushCount);
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);
            Assert.AreEqual(1, exceptions.Count);
            exceptions.ForEach(Assert.IsNull);
        }
        public void PostFilteringTargetWrapperUsingDefaultFilterTest()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
                Rules =
                {
                    // if we had any warnings, log debug too
                    new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),

                    // when there is an error, emit everything
                    new FilteringRule
                    {
                        Exists = "level >= LogLevel.Error", 
                        Filter = "true",
                    },
                },

                // by default log info and above
                DefaultFilter = "level >= LogLevel.Info",
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();
            
            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all Info events went through
            Assert.Equal(3, target.Events.Count);
            Assert.Same(events[1].LogEvent, target.Events[0]);
            Assert.Same(events[2].LogEvent, target.Events[1]);
            Assert.Same(events[5].LogEvent, target.Events[2]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #8
0
        public void RoundRobinGroupTargetSyncTest1()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new RoundRobinGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.Equal(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(4, myTarget1.WriteCount);
            Assert.Equal(3, myTarget2.WriteCount);
            Assert.Equal(3, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }
Пример #9
0
        public void InitializeFailedTest()
        {
            var target = new MyTarget();
            target.ThrowOnInitialize = true;

            LogManager.ThrowExceptions = true;


            Assert.Throws<InvalidOperationException>(() => target.Initialize(null));

            // after exception in Initialize(), the target becomes non-functional and all Write() operations
            var exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.Equal(0, target.WriteCount);
            Assert.Equal(1, exceptions.Count);
            Assert.NotNull(exceptions[0]);
            Assert.Equal("Target " + target + " failed to initialize.", exceptions[0].Message);
            Assert.Equal("Init error.", exceptions[0].InnerException.Message);
        }
Пример #10
0
        public void RetryingTargetWrapperTest1()
        {
            var target  = new MyTarget();
            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget          = target,
                RetryCount             = 10,
                RetryDelayMilliseconds = 1,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List <Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.Equal(3, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);

            Assert.Equal(events.Length, exceptions.Count);

            // make sure there were no exception
            foreach (var ex in exceptions)
            {
                Assert.Null(ex);
            }
        }
Пример #11
0
        public void AsyncTargetWrapperSyncTest1()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper
            {
                WrappedTarget = myTarget,
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            var               logEvent           = new LogEventInfo();
            Exception         lastException      = null;
            ManualResetEvent  continuationHit    = new ManualResetEvent(false);
            Thread            continuationThread = null;
            AsyncContinuation continuation       =
                ex =>
            {
                lastException      = ex;
                continuationThread = Thread.CurrentThread;
                continuationHit.Set();
            };

            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            // continuation was not hit
            continuationHit.WaitOne();
            Assert.AreNotSame(continuationThread, Thread.CurrentThread);
            Assert.IsNull(lastException);
            Assert.AreEqual(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.AreNotSame(continuationThread, Thread.CurrentThread);
            Assert.IsNull(lastException);
            Assert.AreEqual(2, myTarget.WriteCount);
        }
Пример #12
0
        public void PostFilteringTargetWrapperNoFiltersDefined()
        {
            var target  = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List <Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.Equal(7, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);
            Assert.Same(events[3].LogEvent, target.Events[3]);
            Assert.Same(events[4].LogEvent, target.Events[4]);
            Assert.Same(events[5].LogEvent, target.Events[5]);
            Assert.Same(events[6].LogEvent, target.Events[6]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #13
0
        public void FilteringTargetWrapperSyncTest2()
        {
            var myMockCondition = new MyMockCondition(false);
            var myTarget        = new MyTarget();
            var wrapper         = new FilteringTargetWrapper
            {
                WrappedTarget = myTarget,
                Condition     = myMockCondition,
            };

            myTarget.Initialize(null);
            wrapper.Initialize(null);
            var               logEvent        = new LogEventInfo();
            Exception         lastException   = null;
            bool              continuationHit = false;
            AsyncContinuation continuation    =
                ex =>
            {
                lastException   = ex;
                continuationHit = true;
            };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.Equal(1, myMockCondition.CallCount);

            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(0, myTarget.WriteCount);
            Assert.Equal(1, myMockCondition.CallCount);

            continuationHit = false;
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(0, myTarget.WriteCount);
            Assert.Equal(2, myMockCondition.CallCount);
        }
Пример #14
0
        public void RetryingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 10,
                RetryDelayMilliseconds = 1,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.AreEqual(3, target.Events.Count);
            Assert.AreSame(events[0].LogEvent, target.Events[0]);
            Assert.AreSame(events[1].LogEvent, target.Events[1]);
            Assert.AreSame(events[2].LogEvent, target.Events[2]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");

            // make sure there were no exception
            foreach (var ex in exceptions)
            {
                Assert.IsNull(ex);
            }
        }
Пример #15
0
        public void BufferingAutoFlushWrapperTest()
        {
            var testTarget              = new MyTarget();
            var bufferingTargetWrapper  = new BufferingTargetWrapper(testTarget, 100);
            var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(bufferingTargetWrapper);

            autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info";
            testTarget.Initialize(null);
            bufferingTargetWrapper.Initialize(null);
            autoFlushOnLevelWrapper.Initialize(null);

            AsyncContinuation continuation = ex => { };

            autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
            Assert.Equal(0, testTarget.WriteCount);
            Assert.Equal(0, testTarget.FlushCount);
            autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation));
            Assert.Equal(2, testTarget.WriteCount);
            Assert.Equal(1, testTarget.FlushCount);
            autoFlushOnLevelWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation));
            Assert.Equal(2, testTarget.WriteCount);
            Assert.Equal(1, testTarget.FlushCount);
        }
Пример #16
0
        public void FilteringTargetWrapperSyncTest1()
        {
            var myMockCondition = new MyMockCondition(true);
            var myTarget = new MyTarget();
            var wrapper = new FilteringTargetWrapper
            {
                WrappedTarget = myTarget,
                Condition = myMockCondition,
            };

            myTarget.Initialize(null);
            wrapper.Initialize(null);
            var logEvent = new LogEventInfo();
            Exception lastException = null;
            bool continuationHit = false;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationHit = true;
                    };

            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            Assert.Equal(1, myMockCondition.CallCount);

            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit = false;
            wrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            Assert.True(continuationHit);
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
            Assert.Equal(2, myMockCondition.CallCount);
        }
Пример #17
0
        public void RepeatingTargetWrapperTest1()
        {
            var target  = new MyTarget();
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount   = 3,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List <Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through and were replicated 3 times
            Assert.Equal(9, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[0].LogEvent, target.Events[1]);
            Assert.Same(events[0].LogEvent, target.Events[2]);
            Assert.Same(events[1].LogEvent, target.Events[3]);
            Assert.Same(events[1].LogEvent, target.Events[4]);
            Assert.Same(events[1].LogEvent, target.Events[5]);
            Assert.Same(events[2].LogEvent, target.Events[6]);
            Assert.Same(events[2].LogEvent, target.Events[7]);
            Assert.Same(events[2].LogEvent, target.Events[8]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #18
0
        public void AsyncTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper
            {
                WrappedTarget = myTarget,
            };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            var logEvent = new LogEventInfo();
            Exception lastException = null;
            ManualResetEvent continuationHit = new ManualResetEvent(false);
            Thread continuationThread = null;
            AsyncContinuation continuation =
                ex =>
                    {
                        lastException = ex;
                        continuationThread = Thread.CurrentThread;
                        continuationHit.Set();
                    };

            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));

            // continuation was not hit 
            Assert.True(continuationHit.WaitOne(2000));
            Assert.NotSame(continuationThread, Thread.CurrentThread);
            Assert.Null(lastException);
            Assert.Equal(1, myTarget.WriteCount);

            continuationHit.Reset();
            targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(continuation));
            continuationHit.WaitOne();
            Assert.NotSame(continuationThread, Thread.CurrentThread);
            Assert.Null(lastException);
            Assert.Equal(2, myTarget.WriteCount);
        }
        public void RepeatingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount = 3,
            };
            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through and were replicated 3 times
            Assert.Equal(9, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[0].LogEvent, target.Events[1]);
            Assert.Same(events[0].LogEvent, target.Events[2]);
            Assert.Same(events[1].LogEvent, target.Events[3]);
            Assert.Same(events[1].LogEvent, target.Events[4]);
            Assert.Same(events[1].LogEvent, target.Events[5]);
            Assert.Same(events[2].LogEvent, target.Events[6]);
            Assert.Same(events[2].LogEvent, target.Events[7]);
            Assert.Same(events[2].LogEvent, target.Events[8]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #20
0
        public void InitializeFailedTest()
        {
            var target = new MyTarget();

            target.ThrowOnInitialize = true;
            try
            {
                target.Initialize(null);
                Assert.Fail("Expected exception.");
            }
            catch (InvalidOperationException)
            {
            }

            // after exception in Initialize(), the target becomes non-functional and all Write() operations
            var exceptions = new List <Exception>();

            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.AreEqual(0, target.WriteCount);
            Assert.AreEqual(1, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);
            Assert.AreEqual("Target " + target + " failed to initialize.", exceptions[0].Message);
            Assert.AreEqual("Init error.", exceptions[0].InnerException.Message);
        }
Пример #21
0
        public void MultipleConditionalAutoFlushWrappersTest()
        {
            var testTarget = new MyTarget();
            var autoFlushOnLevelWrapper = new AutoFlushTargetWrapper(testTarget);
            autoFlushOnLevelWrapper.Condition = "level > LogLevel.Info";
            var autoFlushOnMessageWrapper = new AutoFlushTargetWrapper(autoFlushOnLevelWrapper);
            autoFlushOnMessageWrapper.Condition = "contains('${message}','FlushThis')";
            testTarget.Initialize(null);
            autoFlushOnLevelWrapper.Initialize(null);
            autoFlushOnMessageWrapper.Initialize(null);

            AsyncContinuation continuation = ex => { };
            autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
            Assert.Equal(1, testTarget.WriteCount);
            Assert.Equal(0, testTarget.FlushCount);
            autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Fatal, "*", "test").WithContinuation(continuation));
            Assert.Equal(2, testTarget.WriteCount);
            Assert.Equal(1, testTarget.FlushCount);
            autoFlushOnMessageWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "Please FlushThis").WithContinuation(continuation));
            Assert.Equal(3, testTarget.WriteCount);
            Assert.Equal(2, testTarget.FlushCount);
        }
Пример #22
0
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize    = 10,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit    = new bool[totalEvents];
            var lastException      = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount           = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                lastException[eventNumber]      = ex;
                continuationThread[eventNumber] = Thread.CurrentThread;
                continuationHit[eventNumber]    = true;
                Interlocked.Increment(ref hitCount);
            };

            // write 9 events - they will all be buffered and no final continuation will be reached
            int eventCounter = 0;

            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreSame(Thread.CurrentThread, continuationThread[i]);
                Assert.IsNull(lastException[i]);
            }

            // write 9 more events - they will all be buffered and no final continuation will be reached
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            // no change
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            targetWrapper.Flush(
                ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            Thread.Sleep(1000);

            flushHit.WaitOne();
            Assert.IsNull(flushException);

            // make sure remaining events were written
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(1, myTarget.FlushCount);

            // flushes happen on the same thread
            for (int i = 10; i < hitCount; ++i)
            {
                Assert.IsNotNull(continuationThread[i]);
                Assert.AreSame(Thread.CurrentThread, continuationThread[i], "Invalid thread #" + i);
                Assert.IsNull(lastException[i]);
            }

            // flush again - should just invoke Flush() on the wrapped target
            flushHit.Reset();
            targetWrapper.Flush(
                ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            flushHit.WaitOne();
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(2, myTarget.FlushCount);

            targetWrapper.Close();
            myTarget.Close();
        }
Пример #23
0
        public void FallbackGroupTargetSyncTest2()
        {
            // fail once
            var myTarget1 = new MyTarget() { FailCounter = 1 };
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new FallbackGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.AreEqual(10, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.IsNull(e);
            }

            Assert.AreEqual(1, myTarget1.WriteCount);
            Assert.AreEqual(10, myTarget2.WriteCount);
            Assert.AreEqual(0, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }
        }
Пример #24
0
        public void RetryingTargetWrapperTest2()
        {
            var target = new MyTarget()
            {
                ThrowExceptions = 6,
            };

            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 4,
                RetryDelayMilliseconds = 1,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            var internalLogOutput = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
            string expectedLogOutput = @"Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 1/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 2/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 3/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 4/4
Warn Too many retries. Aborting.
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 1/4
Warn Error while writing to 'MyTarget': System.InvalidOperationException: Some exception has ocurred.. Try 2/4
";
            Assert.AreEqual(expectedLogOutput, internalLogOutput);

            // first event does not get to wrapped target because of too many attempts.
            // second event gets there in 3rd retry
            // and third event gets there immediately
            Assert.AreEqual(2, target.Events.Count);
            Assert.AreSame(events[1].LogEvent, target.Events[0]);
            Assert.AreSame(events[2].LogEvent, target.Events[1]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");

            Assert.IsNotNull(exceptions[0]);
            Assert.AreEqual("Some exception has ocurred.", exceptions[0].Message);
            Assert.IsNull(exceptions[1]);
            Assert.IsNull(exceptions[2]);
        }
Пример #25
0
        private static void SplitGroupSyncTest1inner(bool allEventsAtOnce)
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new SplitGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            var inputEvents = new List<LogEventInfo>();
            for (int i = 0; i < 10; ++i)
            {
                inputEvents.Add(LogEventInfo.CreateNullEvent());
            }

            int remaining = inputEvents.Count;
            var allDone = new ManualResetEvent(false);

            // no exceptions

            AsyncContinuation asyncContinuation = ex =>
            {
                lock (exceptions)
                {
                    exceptions.Add(ex);
                    if (Interlocked.Decrement(ref remaining) == 0)
                    {
                        allDone.Set();
                    }
                }
                      ;
            };

            if (allEventsAtOnce)
            {
                wrapper.WriteAsyncLogEvents(inputEvents.Select(ev => ev.WithContinuation(asyncContinuation)).ToArray());
            }
            else
            {
                for (int i = 0; i < inputEvents.Count; ++i)
                {
                    wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(asyncContinuation));
                }
            }

            allDone.WaitOne();

            Assert.Equal(inputEvents.Count, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget3.WriteCount);

            for (int i = 0; i < inputEvents.Count; ++i)
            {
                Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
            }

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex =>
            {
                flushException = ex;
                flushHit.Set();
            });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }
Пример #26
0
        public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper() {
                WrappedTarget = myTarget,
                TimeToSleepBetweenBatches = 0,
                BatchSize = 4,
                QueueLimit = 2, // Will make it "sleep" between every second write
                OverflowAction = AsyncTargetWrapperOverflowAction.Block
            };
            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                List<KeyValuePair<LogEventInfo, AsyncContinuation>> itemPrepareList = new List<KeyValuePair<LogEventInfo, AsyncContinuation>>(2500);
                List<int> itemWrittenList = new List<int>(itemPrepareList.Capacity);
                for (int i = 0; i< itemPrepareList.Capacity; ++i)
                {
                    var logEvent = new LogEventInfo();
                    int sequenceID = logEvent.SequenceID;
                    itemPrepareList.Add(new KeyValuePair<LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
                }

                long startTicks = Environment.TickCount;
                for (int i = 0; i < itemPrepareList.Count; ++i)
                {
                    var logEvent = itemPrepareList[i].Key;
                    targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
                }

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                    System.Threading.Thread.Sleep(1);

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
                int prevSequenceID = 0;
                for (int i = 0; i < itemWrittenList.Count; ++i)
                {
                    Assert.True(prevSequenceID < itemWrittenList[i]);
                    prevSequenceID = itemWrittenList[i];
                }

#if MONO || NET3_5
                Assert.True(elapsedMilliseconds < 2500);    // Skip timing test when running within OpenCover.Console.exe
#endif

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                    System.Threading.Thread.Sleep(1);
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
        public void RepeatingTargetWrapperTest2()
        {
            var target = new MyTarget();
            target.ThrowExceptions = true;
            var wrapper = new RepeatingTargetWrapper()
            {
                WrappedTarget = target,
                RepeatCount = 3,
            };
            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through but were registered only once
            // since repeating target wrapper will not repeat in case of exception.
            Assert.Equal(3, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);

            Assert.Equal(events.Length, exceptions.Count);
            foreach (var exception in exceptions)
            {
                Assert.NotNull(exception);
                Assert.Equal("Some exception has occurred.", exception.Message);
            }
        }
Пример #28
0
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount = 0;

            CreateContinuationFunc createAsyncContinuation = 
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                    };

            // write 9 events - they will all be buffered and no final continuation will be reached
            int eventCounter = 0;
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreSame(Thread.CurrentThread, continuationThread[i]);
                Assert.IsNull(lastException[i]);
            }

            // write 9 more events - they will all be buffered and no final continuation will be reached
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            // no change
            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            Assert.AreEqual(10, myTarget.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);

            targetWrapper.Flush(
                ex =>
                    {
                        flushException = ex;
                        flushHit.Set();
                    });

            Thread.Sleep(1000);

            flushHit.WaitOne();
            Assert.IsNull(flushException);

            // make sure remaining events were written
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(1, myTarget.FlushCount);

            // flushes happen on the same thread
            for (int i = 10; i < hitCount; ++i)
            {
                Assert.IsNotNull(continuationThread[i]);
                Assert.AreSame(Thread.CurrentThread, continuationThread[i], "Invalid thread #" + i);
                Assert.IsNull(lastException[i]);
            }

            // flush again - should just invoke Flush() on the wrapped target
            flushHit.Reset();
            targetWrapper.Flush(
                ex =>
                {
                    flushException = ex;
                    flushHit.Set();
                });

            flushHit.WaitOne();
            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);
            Assert.AreEqual(2, myTarget.FlushCount);

            targetWrapper.Close();
            myTarget.Close();
        }
Пример #29
0
        public void BufferingTargetWrapperSyncWithTimedFlushSlidingTest()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
                FlushTimeout = 400,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                    };

            int eventCounter = 0;
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Thread.Sleep(300);

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Thread.Sleep(300);

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            Thread.Sleep(200);
            Assert.AreEqual(2, hitCount);
            Assert.AreEqual(2, myTarget.WriteCount);
        }
Пример #30
0
        public void PostFilteringTargetWrapperUsingDefaultNonFilterTest2()
        {
            // in this case both rules would match, but first one is picked
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
                Rules =
                {
                    // when there is an error, emit everything
                    new FilteringRule("level >= LogLevel.Error", "true"),

                    // if we had any warnings, log debug too
                    new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),
                },

                // by default log info and above
                DefaultFilter = "level >= LogLevel.Info",
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new []
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
            };

            var internalLogOutput = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
            string expectedLogOutput = @"Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events
Trace Rule matched: (level >= Error)
Trace Filter to apply: True
Trace After filtering: 7 events.
Trace Sending to MyTarget
";

            Assert.AreEqual(expectedLogOutput, internalLogOutput);

            // make sure all events went through
            Assert.AreEqual(7, target.Events.Count);
            Assert.AreSame(events[0].LogEvent, target.Events[0]);
            Assert.AreSame(events[1].LogEvent, target.Events[1]);
            Assert.AreSame(events[2].LogEvent, target.Events[2]);
            Assert.AreSame(events[3].LogEvent, target.Events[3]);
            Assert.AreSame(events[4].LogEvent, target.Events[4]);
            Assert.AreSame(events[5].LogEvent, target.Events[5]);
            Assert.AreSame(events[6].LogEvent, target.Events[6]);

            Assert.AreEqual(events.Length, exceptions.Count, "Some continuations were not invoked.");
        }
Пример #31
0
        public void InitializeFailedTest()
        {
            var target = new MyTarget();
            target.ThrowOnInitialize = true;
            try
            {
                target.Initialize(CommonCfg);
                Assert.Fail("Expected exception.");
            }
            catch(NLogConfigurationException) //(InvalidOperationException)
            { // HACK: check out the new behavior to throw exceptions
            }

            // after exception in Initialize(), the target becomes non-functional and all Write() operations
            var exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            Assert.AreEqual(0, target.WriteCount);
            Assert.AreEqual(1, exceptions.Count);
            Assert.IsNotNull(exceptions[0]);
            Assert.AreEqual("Target " + target + " failed to initialize.", exceptions[0].Message);
            Assert.AreEqual("Init error.", exceptions[0].InnerException.Message);
        }
Пример #32
0
        public void PostFilteringTargetWrapperNoFiltersDefined()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Error, "Logger1", "Hello").WithContinuation(exceptions.Add),
            };

            wrapper.WriteAsyncLogEvents(events);

            // make sure all events went through
            Assert.Equal(7, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);
            Assert.Same(events[3].LogEvent, target.Events[3]);
            Assert.Same(events[4].LogEvent, target.Events[4]);
            Assert.Same(events[5].LogEvent, target.Events[5]);
            Assert.Same(events[6].LogEvent, target.Events[6]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #33
0
        public void FallbackGroupTargetSyncTest6()
        {
            // fail once
            var myTarget1 = new MyTarget()
            {
                FailCounter = 10
            };
            var myTarget2 = new MyTarget()
            {
                FailCounter = 3
            };
            var myTarget3 = new MyTarget()
            {
                FailCounter = 3
            };

            var wrapper = new FallbackGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
                ReturnToFirstOnSuccess = true,
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List <Exception> exceptions = new List <Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.AreEqual(10, exceptions.Count);
            for (int i = 0; i < 10; ++i)
            {
                if (i < 3)
                {
                    // for the first 3 rounds, no target is available
                    Assert.IsNotNull(exceptions[i]);
                    Assert.IsInstanceOfType(typeof(InvalidOperationException), exceptions[i]);
                    Assert.AreEqual("Some failure.", exceptions[i].Message);
                }
                else
                {
                    Assert.IsNull(exceptions[i], Convert.ToString(exceptions[i]));
                }
            }

            Assert.AreEqual(10, myTarget1.WriteCount);
            Assert.AreEqual(10, myTarget2.WriteCount);
            Assert.AreEqual(3, myTarget3.WriteCount);

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }

            Assert.AreEqual(1, myTarget1.FlushCount);
            Assert.AreEqual(1, myTarget2.FlushCount);
            Assert.AreEqual(1, myTarget3.FlushCount);
        }
Пример #34
0
        public void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero()
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
                BatchSize      = 4,
                QueueLimit     = 2, // Will make it "sleep" between every second write
                OverflowAction = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                List <KeyValuePair <LogEventInfo, AsyncContinuation> > itemPrepareList = new List <KeyValuePair <LogEventInfo, AsyncContinuation> >(500);
                List <int> itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var logEvent   = new LogEventInfo();
                    int sequenceID = logEvent.SequenceID;
                    itemPrepareList.Add(new KeyValuePair <LogEventInfo, AsyncContinuation>(logEvent, (ex) => itemWrittenList.Add(sequenceID)));
                }

                long startTicks = Environment.TickCount;
                for (int i = 0; i < itemPrepareList.Count; ++i)
                {
                    var logEvent = itemPrepareList[i].Key;
                    targetWrapper.WriteAsyncLogEvent(logEvent.WithContinuation(itemPrepareList[i].Value));
                }

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    System.Threading.Thread.Sleep(1);
                }

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);
                int prevSequenceID = 0;
                for (int i = 0; i < itemWrittenList.Count; ++i)
                {
                    Assert.True(prevSequenceID < itemWrittenList[i]);
                    prevSequenceID = itemWrittenList[i];
                }

                if (!IsAppVeyor())
                {
                    Assert.True(elapsedMilliseconds < 750);    // Skip timing test when running within OpenCover.Console.exe
                }
                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    System.Threading.Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
Пример #35
0
        public void SplitGroupSyncTest1()
        {
            var myTarget1 = new MyTarget();
            var myTarget2 = new MyTarget();
            var myTarget3 = new MyTarget();

            var wrapper = new SplitGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List <Exception> exceptions = new List <Exception>();

            var inputEvents = new List <LogEventInfo>();

            for (int i = 0; i < 10; ++i)
            {
                inputEvents.Add(LogEventInfo.CreateNullEvent());
            }

            int remaining = inputEvents.Count;
            var allDone   = new ManualResetEvent(false);

            // no exceptions
            for (int i = 0; i < inputEvents.Count; ++i)
            {
                wrapper.WriteAsyncLogEvent(inputEvents[i].WithContinuation(ex =>
                {
                    lock (exceptions)
                    {
                        exceptions.Add(ex);
                        if (Interlocked.Decrement(ref remaining) == 0)
                        {
                            allDone.Set();
                        }
                    };
                }));
            }

            allDone.WaitOne();

            Assert.Equal(inputEvents.Count, exceptions.Count);
            foreach (var e in exceptions)
            {
                Assert.Null(e);
            }

            Assert.Equal(inputEvents.Count, myTarget1.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget2.WriteCount);
            Assert.Equal(inputEvents.Count, myTarget3.WriteCount);

            for (int i = 0; i < inputEvents.Count; ++i)
            {
                Assert.Same(inputEvents[i], myTarget1.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget2.WrittenEvents[i]);
                Assert.Same(inputEvents[i], myTarget3.WrittenEvents[i]);
            }

            Exception flushException = null;
            var       flushHit       = new ManualResetEvent(false);

            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.True(false, flushException.ToString());
            }

            Assert.Equal(1, myTarget1.FlushCount);
            Assert.Equal(1, myTarget2.FlushCount);
            Assert.Equal(1, myTarget3.FlushCount);
        }
Пример #36
0
        public void WriteOnClosedTargetTest()
        {
            var target = new MyTarget();
            target.Initialize(null);
            target.Close();

            var exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));

            Assert.AreEqual(1, target.InitializeCount);
            Assert.AreEqual(1, target.CloseCount);

            // write was not called
            Assert.AreEqual(2, target.InitializeCount + target.FlushCount + target.CloseCount + target.WriteCount + target.WriteCount2 + target.WriteCount3);

            // but all callbacks were invoked with null values
            Assert.AreEqual(4, exceptions.Count);
            exceptions.ForEach(Assert.IsNull);
        }
Пример #37
0
        public void LockingTest()
        {
            var target = new MyTarget();
            target.Initialize(null);

            var mre = new ManualResetEvent(false);

            Exception backgroundThreadException = null;

            Thread t = new Thread(() =>
            {
                try
                {
                    target.BlockingOperation(1000);
                }
                catch (Exception ex)
                {
                    backgroundThreadException = ex;
                }
                finally
                {
                    mre.Set();
                }
            });


            target.Initialize(null);
            t.Start();
            Thread.Sleep(50);
            List<Exception> exceptions = new List<Exception>();
            target.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            target.WriteAsyncLogEvents(new[] 
            {
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
                LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add),
            });
            target.Flush(exceptions.Add);
            target.Close();

            exceptions.ForEach(Assert.IsNull);

            mre.WaitOne();
            if (backgroundThreadException != null)
            {
                Assert.Fail(backgroundThreadException.ToString());
            }
        }
Пример #38
0
 public void AutoFlushOnConditionTest()
 {
     var testTarget = new MyTarget();
     var autoFlushWrapper = new AutoFlushTargetWrapper(testTarget);
     autoFlushWrapper.Condition = "level > LogLevel.Info";
     testTarget.Initialize(null);
     autoFlushWrapper.Initialize(null);
     AsyncContinuation continuation = ex => { };
     autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Info, "*", "test").WithContinuation(continuation));
     autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Trace, "*", "test").WithContinuation(continuation));
     Assert.Equal(2, testTarget.WriteCount);
     Assert.Equal(0, testTarget.FlushCount);
     autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Warn, "*", "test").WithContinuation(continuation));
     autoFlushWrapper.WriteAsyncLogEvent(LogEventInfo.Create(LogLevel.Error, "*", "test").WithContinuation(continuation));
     Assert.Equal(4, testTarget.WriteCount);
     Assert.Equal(2, testTarget.FlushCount);
 }
Пример #39
0
        public void BufferingTargetWrapperSyncWithTimedFlushTest()
        {
            var myTarget      = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize    = 10,
                FlushTimeout  = 1000,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit    = new bool[totalEvents];
            var lastException      = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount           = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                ex =>
            {
                lastException[eventNumber]      = ex;
                continuationThread[eventNumber] = Thread.CurrentThread;
                continuationHit[eventNumber]    = true;
                Interlocked.Increment(ref hitCount);
            };

            // write 9 events - they will all be buffered and no final continuation will be reached
            int eventCounter = 0;

            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            // sleep 2 seconds, this will trigger the timer and flush all events
            Thread.Sleep(4000);
            Assert.AreEqual(9, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(9, myTarget.BufferedTotalEvents);
            Assert.AreEqual(9, myTarget.WriteCount);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreNotSame(Thread.CurrentThread, continuationThread[i]);
                Assert.IsNull(lastException[i]);
            }

            // write 11 more events, 10 will be hit immediately because the buffer will fill up
            // 1 will be pending
            for (int i = 0; i < 11; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);

            // sleep 2 seonds and the last remaining one will be flushed
            Thread.Sleep(2000);
            Assert.AreEqual(20, hitCount);
            Assert.AreEqual(3, myTarget.BufferedWriteCount);
            Assert.AreEqual(20, myTarget.BufferedTotalEvents);
            Assert.AreEqual(20, myTarget.WriteCount);
        }
Пример #40
0
        public void PostFilteringTargetWrapperUsingDefaultNonFilterTest()
        {
            var target = new MyTarget();
            var wrapper = new PostFilteringTargetWrapper()
            {
                WrappedTarget = target,
                Rules =
                {
                    // if we had any warnings, log debug too
                    new FilteringRule("level >= LogLevel.Warn", "level >= LogLevel.Debug"),

                    // when there is an error, emit everything
                    new FilteringRule("level >= LogLevel.Error", "true"),
                },

                // by default log info and above
                DefaultFilter = "level >= LogLevel.Info",
            };

            wrapper.Initialize(null);
            target.Initialize(null);

            var exceptions = new List<Exception>();

            var events = new[]
            {
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger2", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Debug, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Trace, "Logger1", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Info, "Logger3", "Hello").WithContinuation(exceptions.Add),
                new LogEventInfo(LogLevel.Warn, "Logger1", "Hello").WithContinuation(exceptions.Add),
            };

            string result = RunAndCaptureInternalLog(() => wrapper.WriteAsyncLogEvents(events), LogLevel.Trace);
            Assert.True(result.IndexOf("Trace Running PostFilteringWrapper Target[(unnamed)](MyTarget) on 7 events") != -1);
            Assert.True(result.IndexOf("Trace Rule matched: (level >= Warn)") != -1);
            Assert.True(result.IndexOf("Trace Filter to apply: (level >= Debug)") != -1);
            Assert.True(result.IndexOf("Trace After filtering: 6 events.") != -1);
            Assert.True(result.IndexOf("Trace Sending to MyTarget") != -1);

            // make sure all Debug,Info,Warn events went through
            Assert.Equal(6, target.Events.Count);
            Assert.Same(events[0].LogEvent, target.Events[0]);
            Assert.Same(events[1].LogEvent, target.Events[1]);
            Assert.Same(events[2].LogEvent, target.Events[2]);
            Assert.Same(events[3].LogEvent, target.Events[3]);
            Assert.Same(events[5].LogEvent, target.Events[4]);
            Assert.Same(events[6].LogEvent, target.Events[5]);

            Assert.Equal(events.Length, exceptions.Count);
        }
Пример #41
0
        public void FallbackGroupTargetSyncTest6()
        {
            // fail once
            var myTarget1 = new MyTarget() { FailCounter = 10 };
            var myTarget2 = new MyTarget() { FailCounter = 3 };
            var myTarget3 = new MyTarget() { FailCounter = 3 };

            var wrapper = new FallbackGroupTarget()
            {
                Targets = { myTarget1, myTarget2, myTarget3 },
                ReturnToFirstOnSuccess = true,
            };

            myTarget1.Initialize(null);
            myTarget2.Initialize(null);
            myTarget3.Initialize(null);
            wrapper.Initialize(null);

            List<Exception> exceptions = new List<Exception>();

            // no exceptions
            for (int i = 0; i < 10; ++i)
            {
                wrapper.WriteAsyncLogEvent(LogEventInfo.CreateNullEvent().WithContinuation(exceptions.Add));
            }

            Assert.AreEqual(10, exceptions.Count);
            for (int i = 0; i < 10; ++i)
            {
                if (i < 3)
                {
                    // for the first 3 rounds, no target is available
                    Assert.IsNotNull(exceptions[i]);
                    Assert.IsInstanceOfType(exceptions[i], typeof(InvalidOperationException));
                    Assert.AreEqual("Some failure.", exceptions[i].Message);
                }
                else
                {
                    Assert.IsNull(exceptions[i], Convert.ToString(exceptions[i]));
                }
            }

            Assert.AreEqual(10, myTarget1.WriteCount);
            Assert.AreEqual(10, myTarget2.WriteCount);
            Assert.AreEqual(3, myTarget3.WriteCount);

            Exception flushException = null;
            var flushHit = new ManualResetEvent(false);
            wrapper.Flush(ex => { flushException = ex; flushHit.Set(); });

            flushHit.WaitOne();
            if (flushException != null)
            {
                Assert.Fail(flushException.ToString());
            }

            Assert.AreEqual(1, myTarget1.FlushCount);
            Assert.AreEqual(1, myTarget2.FlushCount);
            Assert.AreEqual(1, myTarget3.FlushCount);
        }
Пример #42
0
        /// <summary>
        /// Test Fix for https://github.com/NLog/NLog/issues/1069
        /// </summary>
        private void AsyncTargetWrapperSyncTest_WhenTimeToSleepBetweenBatchesIsEqualToZero(bool forceLockingQueue)
        {
            LogManager.ThrowConfigExceptions = true;

            var myTarget      = new MyTarget();
            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                TimeToSleepBetweenBatches = 0,
#if NET4_5
                ForceLockingQueue   = forceLockingQueue,
                OptimizeBufferReuse = !forceLockingQueue,
#endif
                BatchSize  = 3,
                QueueLimit = 5, // Will make it "sleep" between every second write
                FullBatchSizeWriteLimit = 1,
                OverflowAction          = AsyncTargetWrapperOverflowAction.Block
            };

            targetWrapper.Initialize(null);
            myTarget.Initialize(null);

            try
            {
                int flushCounter = 0;
                AsyncContinuation flushHandler = (ex) => { ++flushCounter; };

                var itemPrepareList = new List <AsyncLogEventInfo>(500);
                var itemWrittenList = new List <int>(itemPrepareList.Capacity);
                for (int i = 0; i < itemPrepareList.Capacity; ++i)
                {
                    var  logEvent      = new LogEventInfo();
                    int  sequenceID    = logEvent.SequenceID;
                    bool blockConsumer = (itemPrepareList.Capacity / 2) == i;  // Force producers to get into blocking-mode
                    itemPrepareList.Add(logEvent.WithContinuation((ex) => { if (blockConsumer)
                                                                            {
                                                                                Thread.Sleep(125);
                                                                            }
                                                                            itemWrittenList.Add(sequenceID); }));
                }

                var eventProducer0 = new ManualResetEvent(false);
                var eventProducer1 = new ManualResetEvent(false);
                ParameterizedThreadStart producerMethod = (s) =>
                {
                    var eventProducer = (ManualResetEvent)s;
                    if (eventProducer != null)
                    {
                        eventProducer.Set();    // Signal we are ready
                    }
                    int partitionNo = ReferenceEquals(eventProducer, eventProducer1) ? 1 : 0;
                    for (int i = 0; i < itemPrepareList.Count; ++i)
                    {
                        if (i % 2 == partitionNo)
                        {
                            targetWrapper.WriteAsyncLogEvent(itemPrepareList[i]);
                        }
                    }
                };

                Thread producer0 = new Thread(producerMethod);
                producer0.IsBackground = true;
                Thread producer1 = new Thread(producerMethod);
                producer1.IsBackground = true;
                producer1.Start(eventProducer0);
                producer0.Start(eventProducer1);
                Assert.True(eventProducer0.WaitOne(5000), "Producer0 Start Timeout");
                Assert.True(eventProducer1.WaitOne(5000), "Producer1 Start Timeout");

                long startTicks = Environment.TickCount;

                Assert.True(producer0.Join(5000), "Producer0 Complete Timeout");  // Wait for producer0 to complete
                Assert.True(producer1.Join(5000), "Producer1 Complete Timeout");  // Wait for producer1 to complete

                long elapsedMilliseconds = Environment.TickCount - startTicks;

                targetWrapper.Flush(flushHandler);

                for (int i = 0; i < itemPrepareList.Count * 2 && itemWrittenList.Count != itemPrepareList.Count; ++i)
                {
                    Thread.Sleep(1);
                }

                Assert.Equal(itemPrepareList.Count, itemWrittenList.Count);

                int producer0sequenceID = 0;
                int producer1sequenceID = 0;
                for (int i = 1; i < itemWrittenList.Count; ++i)
                {
                    if (itemWrittenList[i] % 2 == 0)
                    {
                        Assert.True(producer0sequenceID < itemWrittenList[i], "Producer0 invalid sequence");
                        producer0sequenceID = itemWrittenList[i];
                    }
                    else
                    {
                        Assert.True(producer1sequenceID < itemWrittenList[i], "Producer1 invalid sequence");
                        producer1sequenceID = itemWrittenList[i];
                    }
                }

#if NET4_5
                if (!IsAppVeyor())  // Skip timing test when running within OpenCover.Console.exe
#endif
                Assert.InRange(elapsedMilliseconds, 0, 950);

                targetWrapper.Flush(flushHandler);
                for (int i = 0; i < 2000 && flushCounter != 2; ++i)
                {
                    Thread.Sleep(1);
                }
                Assert.Equal(2, flushCounter);
            }
            finally
            {
                myTarget.Close();
                targetWrapper.Close();
            }
        }
Пример #43
0
        public void BufferingTargetWrapperSyncWithTimedFlushTest()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
                FlushTimeout = 1000,
            };

            myTarget.Initialize(null);
            targetWrapper.Initialize(null);

            int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            int hitCount = 0;

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                    };

            // write 9 events - they will all be buffered and no final continuation will be reached
            int eventCounter = 0;
            for (int i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(0, hitCount);
            Assert.AreEqual(0, myTarget.WriteCount);

            // sleep 2 seconds, this will trigger the timer and flush all events
            Thread.Sleep(2000);
            Assert.AreEqual(9, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(9, myTarget.BufferedTotalEvents);
            Assert.AreEqual(9, myTarget.WriteCount);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreNotSame(Thread.CurrentThread, continuationThread[i]);
                Assert.IsNull(lastException[i]);
            }

            // write 11 more events, 10 will be hit immediately because the buffer will fill up
            // 1 will be pending
            for (int i = 0; i < 11; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

            Assert.AreEqual(19, hitCount);
            Assert.AreEqual(2, myTarget.BufferedWriteCount);
            Assert.AreEqual(19, myTarget.BufferedTotalEvents);
            Assert.AreEqual(19, myTarget.WriteCount);

            // sleep 2 seonds and the last remaining one will be flushed
            Thread.Sleep(2000);
            Assert.AreEqual(20, hitCount);
            Assert.AreEqual(3, myTarget.BufferedWriteCount);
            Assert.AreEqual(20, myTarget.BufferedTotalEvents);
            Assert.AreEqual(20, myTarget.WriteCount);
        }