Ejemplo n.º 1
0
        private void EnqueuQueueBlock_OnClose_ReleasesWriters(bool forceLockingQueue)
        {
            // Arrange
            var slowTarget    = new MethodCallTarget("slowTarget", (logEvent, parms) => System.Threading.Thread.Sleep(300));
            var targetWrapper = new AsyncTargetWrapper("asynSlowTarget", slowTarget)
            {
                OverflowAction    = AsyncTargetWrapperOverflowAction.Block,
                QueueLimit        = 3,
                ForceLockingQueue = forceLockingQueue,
            };

            var logFactory    = new LogFactory();
            var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory);

            loggingConfig.AddRuleForAllLevels(targetWrapper);
            logFactory.Configuration = loggingConfig;
            var logger = logFactory.GetLogger("Test");

            // Act
            long allTasksCompleted = 0;

            AsyncHelpers.ForEachItemInParallel(System.Linq.Enumerable.Range(1, 6), (ex) => Interlocked.Exchange(ref allTasksCompleted, 1), (value, cont) => { for (int i = 0; i < 100; ++i)
                                                                                                                                                              {
                                                                                                                                                                  logger.Info("Hello {0}", value);
                                                                                                                                                              }
                                                                                                                                                              cont(null); });
            Thread.Sleep(150); // Let them get stuck
            Assert.Equal(0, Interlocked.Read(ref allTasksCompleted));

            targetWrapper.Close();  // Release those who are stuck, and discard the rest

            // Assert
            for (int i = 0; i < 100; i++)
            {
                if (Interlocked.Read(ref allTasksCompleted) == 1)
                {
                    break;
                }
                Thread.Sleep(10);
            }

            Assert.Equal(1, Interlocked.Read(ref allTasksCompleted));
        }
Ejemplo n.º 2
0
        public void EventQueueGrow_OnQueueGrow()
        {
            int queueLimit       = 2;
            int loggedEventCount = 10;

            int expectedGrowingNumber = 3;

            int eventsCounter = 0;
            var myTarget      = new MyTarget();

            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget             = myTarget,
                QueueLimit                = queueLimit,
                TimeToSleepBetweenBatches = 500,    // Make it slow
                OverflowAction            = AsyncTargetWrapperOverflowAction.Grow,
            };

            var logFactory    = new LogFactory();
            var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory);

            loggingConfig.AddRuleForAllLevels(targetWrapper);
            logFactory.Configuration = loggingConfig;
            var logger = logFactory.GetLogger("Test");

            try
            {
                targetWrapper.EventQueueGrow += (o, e) => { eventsCounter++; };

                for (int i = 0; i < loggedEventCount; i++)
                {
                    logger.Info("Hello");
                }

                Assert.Equal(expectedGrowingNumber, eventsCounter);
            }
            finally
            {
                logFactory.Configuration = null;
            }
        }
Ejemplo n.º 3
0
        public void LogEventNotDropped_IfOverflowActionGrow()
        {
            int queueLimit       = 2;
            int loggedEventCount = 5;
            int eventsCounter    = 0;
            var myTarget         = new MyTarget();

            var targetWrapper = new AsyncTargetWrapper()
            {
                WrappedTarget  = myTarget,
                QueueLimit     = queueLimit,
                OverflowAction = AsyncTargetWrapperOverflowAction.Grow
            };

            var logFactory    = new LogFactory();
            var loggingConfig = new NLog.Config.LoggingConfiguration(logFactory);

            loggingConfig.AddRuleForAllLevels(targetWrapper);
            logFactory.Configuration = loggingConfig;
            var logger = logFactory.GetLogger("Test");

            try
            {
                targetWrapper.LogEventDropped += (o, e) => { eventsCounter++; };

                for (int i = 0; i < loggedEventCount; i++)
                {
                    logger.Info("Hello");
                }

                Assert.Equal(0, eventsCounter);
            }
            finally
            {
                logFactory.Configuration = null;
            }
        }
Ejemplo n.º 4
0
 public void AddRule_all()
 {
     var config = new LoggingConfiguration();
     config.AddTarget(new FileTarget {Name = "File"});
     config.AddRuleForAllLevels("File", "*a");
     Assert.NotNull(config.LoggingRules);
     Assert.Equal(1, config.LoggingRules.Count);
     var rule1 = config.LoggingRules.FirstOrDefault();
     Assert.NotNull(rule1);
     Assert.Equal(false, rule1.Final);
     Assert.Equal("*a", rule1.LoggerNamePattern);
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Fatal));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Error));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Warn));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Info));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Debug));
     Assert.Equal(true, rule1.IsLoggingEnabledForLevel(LogLevel.Trace));
     Assert.Equal(false, rule1.IsLoggingEnabledForLevel(LogLevel.Off));
 }
Ejemplo n.º 5
0
        public void ReplaceFileContentsOnEachWrite_CreateDirs(bool createDirs)
        {

            LogManager.ThrowExceptions = false;

            var tempPath = Path.Combine(Path.GetTempPath(), "dir_" + Guid.NewGuid().ToString());
            var logfile = Path.Combine(tempPath, "log.log");

            try
            {
                var target = new FileTarget
                {
                    FileName = logfile,
                    ReplaceFileContentsOnEachWrite = true,
                    CreateDirs = createDirs
                };
                var config = new LoggingConfiguration();

                config.AddTarget("logfile", target);

                config.AddRuleForAllLevels(target);

                LogManager.Configuration = config;

                ILogger logger = LogManager.GetLogger("A");
                logger.Info("a");

                Assert.Equal(createDirs, Directory.Exists(tempPath));
            }
            finally
            {
                if (File.Exists(logfile))
                    File.Delete(logfile);
                if (Directory.Exists(tempPath))
                    Directory.Delete(tempPath, true);
            }
        }
Ejemplo n.º 6
0
        public void DontCrashWhenDateAndSequenceDoesntMatchFiles()
        {
            var tempDir = Path.Combine(Path.GetTempPath(), "DontCrashWhenDateAndSequenceDoesntMatchFiles-" + Guid.NewGuid());
            string logFile = Path.Combine(tempDir, "log.txt");
            try
            {
                // set log file access times the same way as when this issue comes up.
                Directory.CreateDirectory(tempDir);

                File.WriteAllText(logFile, "some content" + Environment.NewLine);
                var oldTime = DateTime.Now.AddDays(-2);
                File.SetCreationTime(logFile, oldTime);
                File.SetLastWriteTime(logFile, oldTime);
                File.SetLastAccessTime(logFile, oldTime);

                //write to archive directly
                var archiveDateFormat = "yyyyMMdd";
                var archiveFileNamePattern = Path.Combine(tempDir, "log-{#}.txt");
                var archiveFileName = archiveFileNamePattern.Replace("{#}", oldTime.ToString(archiveDateFormat));
                File.WriteAllText(archiveFileName, "some archive content");

                LogManager.ThrowExceptions = true;

                // configure nlog


                var fileTarget = new FileTarget("file")
                {
                    FileName = logFile,
                    ArchiveEvery = FileArchivePeriod.Day,
                    ArchiveFileName = "log-{#}.txt",
                    ArchiveNumbering = ArchiveNumberingMode.DateAndSequence,
                    ArchiveAboveSize = 50000,
                    MaxArchiveFiles = 7
                };


                var config = new LoggingConfiguration();
                config.AddRuleForAllLevels(fileTarget);
                LogManager.Configuration = config;

                // write
                var logger = LogManager.GetLogger("DontCrashWhenDateAndSequenceDoesntMatchFiles");
                logger.Info("Log message");

                LogManager.Flush();
            }
            finally
            {
                try
                {
                    if (File.Exists(logFile))
                        File.Delete(logFile);
                    Directory.Delete(tempDir, true);
                }
                catch (Exception)
                {
                }
            }
        }
Ejemplo n.º 7
0
        private void HandleArchiveFileAlreadyExistsTest(Encoding encoding, bool hasBom)
        {
            var tempDir = Path.Combine(Path.GetTempPath(), "HandleArchiveFileAlreadyExistsTest-" + Guid.NewGuid());
            string logFile = Path.Combine(tempDir, "log.txt");
            try
            {
                // set log file access times the same way as when this issue comes up.
                Directory.CreateDirectory(tempDir);


                File.WriteAllText(logFile, "some content" + Environment.NewLine, encoding);
                var oldTime = DateTime.Now.AddDays(-2);
                File.SetCreationTime(logFile, oldTime);
                File.SetLastWriteTime(logFile, oldTime);
                File.SetLastAccessTime(logFile, oldTime);

                //write to archive directly
                var archiveDateFormat = "yyyy-MM-dd";
                var archiveFileNamePattern = Path.Combine(tempDir, "log-{#}.txt");
                var archiveFileName = archiveFileNamePattern.Replace("{#}", oldTime.ToString(archiveDateFormat));
                File.WriteAllText(archiveFileName, "message already in archive" + Environment.NewLine, encoding);

                LogManager.ThrowExceptions = true;

                // configure nlog


                var fileTarget = new FileTarget("file")
                {
                    FileName = logFile,
                    ArchiveEvery = FileArchivePeriod.Day,
                    ArchiveFileName = archiveFileNamePattern,
                    ArchiveNumbering = ArchiveNumberingMode.Date,
                    ArchiveDateFormat = archiveDateFormat,
                    Encoding = encoding
                };


                var config = new LoggingConfiguration();
                config.AddTarget(fileTarget);
                config.AddRuleForAllLevels(fileTarget);

                LogManager.Configuration = config;

                var logger = LogManager.GetLogger("HandleArchiveFileAlreadyExistsTest");
                // write, this should append.
                logger.Info("log to force archiving");


                LogManager.Flush();
                AssertFileContents(archiveFileName, "message already in archive" + Environment.NewLine + "some content" + Environment.NewLine, encoding, hasBom);
            }
            finally
            {
                try
                {
                    if (File.Exists(logFile))
                        File.Delete(logFile);
                    Directory.Delete(tempDir, true);
                }
                catch (Exception)
                {
                }
            }
        }