Esempio n. 1
0
        public NLogLogger()
        {
            ConfigurationItemFactory.Default.RegisterItemsFromAssembly(Assembly.GetExecutingAssembly());

            var config = new LoggingConfiguration();

            //var consoleTarget = new ColoredConsoleTarget();
            //config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, consoleTarget));

            var elasticTarget = new BufferingTargetWrapper(new ElasticSearchTarget
            {
                Fields =
                {
                    new ElasticSearchField
                    {
                        Name = "application",
                        Layout = "LoggerAppNLog"
                    },
                    new ElasticSearchField
                    {
                        Name = "machinename",
                        Layout = "${machinename}"
                    },
                }
            }, 1000, 1000);
            config.LoggingRules.Add(new LoggingRule("*", LogLevel.Info, elasticTarget));

            LogManager.Configuration = config;
        }
Esempio n. 2
0
    static void Main(string[] args)
    {
        FileTarget wrappedTarget = new FileTarget();
        wrappedTarget.FileName = "${basedir}/file.txt";

        PostFilteringTargetWrapper postFilteringTarget = new PostFilteringTargetWrapper();
        postFilteringTarget.WrappedTarget = wrappedTarget;

        // set up default filter
        postFilteringTarget.DefaultFilter = "level >= LogLevel.Info";

        FilteringRule rule;

        // if there are any warnings in the buffer
        // dump the messages whose level is Debug or higher

        rule = new FilteringRule();
        rule.Exists = "level >= LogLevel.Warn";
        rule.Filter = "level >= LogLevel.Debug";

        postFilteringTarget.Rules.Add(rule);

        BufferingTargetWrapper target = new BufferingTargetWrapper();
        target.BufferSize = 100;
        target.WrappedTarget = postFilteringTarget;

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

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");
    }
Esempio n. 3
0
    static void Main(string[] args)
    {
        FileTarget wrappedTarget = new FileTarget();
        wrappedTarget.FileName = "${basedir}/file.txt";

        BufferingTargetWrapper target = new BufferingTargetWrapper();
        target.BufferSize = 100;
        target.WrappedTarget = wrappedTarget;

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

        Logger logger = LogManager.GetLogger("Example");
        logger.Debug("log message");
    }
Esempio n. 4
0
        private static Target BuildInfoFileTarget(string logPath, string filename)
        {
            var target = new FileTarget();

            target.FileName = string.Concat(logPath, filename);
            target.AutoFlush = false;
            target.Layout = BuildLayout();
            target.ArchiveFileName = string.Concat(logPath, @"archives\log.{#####}.", filename);
            target.ArchiveEvery = FileArchivePeriod.Month;
            target.ArchiveNumbering = ArchiveNumberingMode.Sequence;
            target.NetworkWrites = true;

            var wrapper = new BufferingTargetWrapper(target);

            return wrapper;
        }
Esempio n. 5
0
        public App()
        {
            this.Startup += this.Application_Startup;
            this.Exit += this.Application_Exit;
            this.UnhandledException += this.Application_UnhandledException;

            InitializeComponent();

            LogManager.ThrowExceptions = true;

            var target = new LogReceiverWebServiceTarget();
            target.EndpointAddress = new Uri(HtmlPage.Document.DocumentUri, "NLogReceiver.svc").ToString();
            target.Parameters.Add(new MethodCallParameter("message", "${message}"));
            target.Parameters.Add(new MethodCallParameter("date", "${longdate}"));

            var buffer = new BufferingTargetWrapper(target) { BufferSize = 10, FlushTimeout = 1000 };

            SimpleConfigurator.ConfigureForTargetLogging(buffer);
        }
Esempio n. 6
0
    static void Main(string[] args)
    {
        try
        {
            NLog.Internal.InternalLogger.LogToConsole = true;
            NLog.Internal.InternalLogger.LogLevel = LogLevel.Trace;
            Console.WriteLine("Setting up the target...");
            MailTarget target = new MailTarget();

            target.SmtpServer = "192.168.0.15";
            target.From = "*****@*****.**";
            target.To = "*****@*****.**";
            target.Subject = "sample subject";
            target.Body = "${message}${newline}";

            BufferingTargetWrapper buffer = new BufferingTargetWrapper(target, 5);

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

            Console.WriteLine("Sending...");
            Logger logger = LogManager.GetLogger("Example");
            logger.Debug("log message 1");
            logger.Debug("log message 2");
            logger.Debug("log message 3");
            logger.Debug("log message 4");
            logger.Debug("log message 5");
            logger.Debug("log message 6");
            logger.Debug("log message 7");
            logger.Debug("log message 8");

            // this should send 2 mails - one with messages 1..5, the other with messages 6..8
            Console.WriteLine("Sent.");
        }
        catch (Exception ex)
        {
            Console.WriteLine("EX: {0}", ex);
                
        }
    }
Esempio n. 7
0
        public void BufferingTargetWrapperAsyncTest1()
        {
            var myTarget = new MyAsyncTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
            };

            ((ISupportsInitialize)myTarget).Initialize();
            ((ISupportsInitialize)targetWrapper).Initialize();

            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.WriteLogEvent(new LogEventInfo(), createAsyncContinuation(eventCounter++));
            }

            Assert.AreEqual(0, hitCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteLogEvent(new LogEventInfo(), createAsyncContinuation(eventCounter++));

            while (hitCount < 10)
            {
                Thread.Sleep(10);
            }

            Assert.AreEqual(10, hitCount);
            Assert.AreEqual(1, myTarget.BufferedWriteCount);
            Assert.AreEqual(10, myTarget.BufferedTotalEvents);
            for (int i = 0; i < hitCount; ++i)
            {
                Assert.AreNotSame(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.WriteLogEvent(new LogEventInfo(), createAsyncContinuation(eventCounter++));
            }

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

            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);

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

            // flush again - should not do anything
            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);

            ((ISupportsInitialize)targetWrapper).Close();
            ((ISupportsInitialize)myTarget).Close();
        }
Esempio n. 8
0
        public void BufferingTargetWrapperSyncWithTimedFlushTest()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
                FlushTimeout = 1000,
            };

            ((ISupportsInitialize)myTarget).Initialize();
            ((ISupportsInitialize)targetWrapper).Initialize();

            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.WriteLogEvent(new LogEventInfo(), 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.WriteLogEvent(new LogEventInfo(), 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);
        }
        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);
        }
Esempio n. 10
0
        public void WhenWrappedTargetThrowsExceptionThisIsHandled()
        {
            var myTarget = new MyTarget { ThrowException = true };
            var bufferingTargetWrapper = new BufferingTargetWrapper
                                             {
                                                 WrappedTarget = myTarget,
                                                 FlushTimeout = -1
                                             };

            InitializeTargets(myTarget, bufferingTargetWrapper);

            bufferingTargetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(_ => { }));

            var flushHit = new ManualResetEvent(false);
            bufferingTargetWrapper.Flush(ex => flushHit.Set());
            flushHit.WaitOne();

            Assert.Equal(1, myTarget.FlushCount);
        }
Esempio n. 11
0
        public void BufferingTargetWrapperSyncTest1()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
            };

            InitializeTargets(myTarget, targetWrapper);

            const int totalEvents = 100;

            var continuationHit = new bool[totalEvents];
            var lastException = new Exception[totalEvents];
            var continuationThread = new Thread[totalEvents];
            var 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
            var eventCounter = 0;
            for (var i = 0; i < 9; ++i)
            {
                targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            }

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

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

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

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

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

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

            Thread.Sleep(1000);

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

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

            // flushes happen on the same thread
            for (var i = 10; i < hitCount; ++i)
            {
                Assert.NotNull(continuationThread[i]);
                Assert.Same(Thread.CurrentThread, continuationThread[i]);
                Assert.Null(lastException[i]);
            }

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

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

            targetWrapper.Close();
            myTarget.Close();
        }
Esempio n. 12
0
        public void BufferingTargetWrapperSyncWithTimedFlushNonSlidingTest()
        {
            var myTarget = new MyTarget();
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = myTarget,
                BufferSize = 10,
                FlushTimeout = 400,
                SlidingTimeout = false,
            };

            InitializeTargets(myTarget, targetWrapper);

            const int totalEvents = 100;

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

            var resetEvent = new ManualResetEvent(false);
            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                        Interlocked.Increment(ref hitCount);
                        if (eventNumber > 0)
                        {
                            resetEvent.Set();
                        }
                    };

            var eventCounter = 0;
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));

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

            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.True(resetEvent.WaitOne(5000));

            Assert.Equal(2, hitCount);
            Assert.Equal(2, myTarget.WriteCount);
        }
Esempio n. 13
0
        public void BufferingTargetWithFallbackGroupAndFirstTargetFails_Write_SecondTargetWritesEvents()
        {
            var myTarget = new MyTarget { FailCounter = 1 };
            var myTarget2 = new MyTarget();
            var fallbackGroup = new FallbackGroupTarget(myTarget, myTarget2);
            var targetWrapper = new BufferingTargetWrapper
            {
                WrappedTarget = fallbackGroup,
                BufferSize = 10,
            };

            InitializeTargets(myTarget, targetWrapper, myTarget2, fallbackGroup);

            const int totalEvents = 100;

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

            CreateContinuationFunc createAsyncContinuation =
                eventNumber =>
                    ex =>
                    {
                        lastException[eventNumber] = ex;
                        continuationThread[eventNumber] = Thread.CurrentThread;
                        continuationHit[eventNumber] = true;
                    };

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

            Assert.Equal(0, myTarget.WriteCount);

            // write one more event - everything will be flushed
            targetWrapper.WriteAsyncLogEvent(new LogEventInfo().WithContinuation(createAsyncContinuation(eventCounter++)));
            Assert.Equal(1, myTarget.WriteCount);
            Assert.Equal(10, myTarget2.WriteCount);

            targetWrapper.Close();
            myTarget.Close();
        }