Example #1
0
    static void Main(string[] args)
    {
        FileTarget wrappedTarget = new FileTarget();
        wrappedTarget.FileName = "${basedir}/file.txt";

        RetryingTargetWrapper target = new RetryingTargetWrapper();
        target.WrappedTarget = wrappedTarget;
        target.RetryCount = 3;
        target.RetryDelayMilliseconds = 1000;

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

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");
    }
        public void RetryingTargetWrapperTest1()
        {
            var target = new MyTarget();
            var wrapper = new RetryingTargetWrapper()
            {
                WrappedTarget = target,
                RetryCount = 10,
                RetryDelayMilliseconds = 1,
            };

            ((ISupportsInitialize)wrapper).Initialize();
            ((ISupportsInitialize)target).Initialize();

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

            var exceptions = new List<Exception>();

            var continuations = new AsyncContinuation[events.Length];
            for (int i = 0; i < continuations.Length; ++i)
            {
                continuations[i] = exceptions.Add;
            }

            wrapper.WriteLogEvents(events, continuations);

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

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

            // make sure there were no exception
            foreach (var ex in exceptions)
            {
                Assert.IsNull(ex);
            }
        }
        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);
            }
        }
        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]);
        }
        private Target ConfigureSecurityActionTarget()
        {
            // Create database target
            DatabaseTarget eventLogDatabaseTarget = ConfigureSecurityActionDatabaseTarget();

            RetryingTargetWrapper retryTarget = new RetryingTargetWrapper(eventLogDatabaseTarget, 5, 1000);

            LogManager.Configuration.AddTarget("FrameworkLoggingSecurityAction", retryTarget);

            return retryTarget;
        }
        private void ConfigureDefaultTarget()
        {
            const int RetryCount = 2;
            const int RetryIntervalMs = 500;

            // Create database target
            DatabaseTarget eventLogDatabaseTarget = ConfigureDatabaseTarget();

            RetryingTargetWrapper retryTarget = new RetryingTargetWrapper(eventLogDatabaseTarget, RetryCount, RetryIntervalMs);

            // Create file target
            FileTarget fileTarget = ConfigureFileTarget();

            // Create Event Log target
            EventLogTarget applicationEventLogTarget = ConfigureEventLogTarget(base._applicationName);

            // Create fallback group target - database target first, then Event Log target
            FallbackGroupTarget fallbackTarget = new FallbackGroupTarget(retryTarget, fileTarget, applicationEventLogTarget);

            // With ReturnToFirstOnSuccess true, when the primary target fails and the secondary
            // succeeds, NLog will switch back to the primary for the next write, which is what we
            // want. With the default of false, if the primary fails once, NLog stays on the secondary
            // for the life of the AppDomain -- i.e. only Event Log and no more database.
            fallbackTarget.ReturnToFirstOnSuccess = true;

            AsyncTargetWrapper asyncFallbackTarget = new AsyncTargetWrapper(fallbackTarget);
            asyncFallbackTarget.BatchSize = 200;
            asyncFallbackTarget.QueueLimit = 5000;

            LogManager.Configuration.AddTarget("FrameworkLoggingDefault", asyncFallbackTarget);
        }