[InlineData(null, EventLogMock.EventLogDefaultMaxKilobytes, EventLogMock.EventLogDefaultMaxKilobytes)] // Should not change MaxKilobytes when the value is null
        public void ShouldSetMaxKilobytes_WhenNeeded(long?newValue, long initialValue, long expectedValue)
        {
            string targetLog    = "application"; // The Log to write to is intentionally lower case!!
            var    eventLogMock = new EventLogMock(
                deleteEventSourceFunction: (source, machineName) => { },
                sourceExistsFunction: (source, machineName) => false,
                logNameFromSourceNameFunction: (source, machineName) => targetLog,
                createEventSourceFunction: (sourceData) => { })
            {
                MaximumKilobytes = initialValue
            };
            var target = new EventLogTarget(eventLogMock, null)
            {
                Log              = targetLog,
                Source           = "NLog.UnitTests" + Guid.NewGuid().ToString("N"), // set the source explicitly to prevent random AppDomain name being used as the source name
                Layout           = new SimpleLayout("${message}"),                  // Be able to check message length and content, the Layout is intentionally only ${message}.
                OnOverflow       = EventLogTargetOverflowAction.Truncate,
                MaxMessageLength = MaxMessageLength,
                MaxKilobytes     = newValue,
            };

            eventLogMock.AssociateNewEventLog(target.Log, target.MachineName, target.GetFixedSource());

            target.Install(new InstallationContext());

            Assert.Equal(expectedValue, eventLogMock.MaximumKilobytes);
        }
Exemple #2
0
        public void WriteEventLogEntry_WillComplain_WhenWrongLogName()
        {
            // Arrange
            string sourceName        = "NLog.UnitTests" + Guid.NewGuid().ToString("N");
            string deletedSourceName = string.Empty;
            string createdLogName    = string.Empty;
            var    eventLogMock      = new EventLogMock(
                deleteEventSourceFunction: (source, machineName) => deletedSourceName = source,
                sourceExistsFunction: (source, machineName) => true,
                logNameFromSourceNameFunction: (source, machineName) => "FaultyLog",
                createEventSourceFunction: (sourceData) => createdLogName = sourceData.LogName);
            var target = new EventLogTarget(eventLogMock, null);

            target.Log    = "CorrectLog";
            target.Source = "${event-properties:item=DynamicSource}";
            target.Layout = "${message}";

            var logFactory = new LogFactory();
            var logConfig  = new LoggingConfiguration(logFactory);

            logConfig.AddRuleForAllLevels(target);
            logFactory.Configuration = logConfig;

            // Act
            var logger = logFactory.GetLogger("EventLogCorrectLog");

            logger.Info("Hello {DynamicSource:l}", sourceName);

            // Assert
            Assert.Equal(string.Empty, deletedSourceName);
            Assert.Equal(string.Empty, createdLogName);
            Assert.Equal(target.Log, eventLogMock.WrittenEntries[0].Log);
            Assert.Equal(sourceName, eventLogMock.WrittenEntries[0].Source);
            Assert.Equal($"Hello {sourceName}", eventLogMock.WrittenEntries[0].Message);
        }
Exemple #3
0
        public void WriteEventLogEntry_WithoutSource_WillBeDiscarded()
        {
            // Arrange
            var eventLogMock = new EventLogMock(
                deleteEventSourceFunction: (source, machineName) => { },
                sourceExistsFunction: (source, machineName) => true,
                logNameFromSourceNameFunction: (source, machineName) => string.Empty,
                createEventSourceFunction: (sourceData) => { });
            var target = new EventLogTarget(eventLogMock, null);

            target.Source = "${event-properties:item=DynamicSource}";

            var logFactory = new LogFactory();
            var logConfig  = new LoggingConfiguration(logFactory);

            logConfig.AddRuleForAllLevels(target);
            logFactory.Configuration = logConfig;

            // Act
            var logger = logFactory.GetLogger("EventLogCorrectLog");

            logger.Info("Hello");

            // Assert
            Assert.Empty(eventLogMock.WrittenEntries);
        }
Exemple #4
0
        private static IEnumerable <EventLogMock.EventRecord> WriteWithMock(LogLevel logLevel, EventLogEntryType expectedEventLogEntryType,
                                                                            string logMessage, Layout entryType = null, EventLogTargetOverflowAction overflowAction = EventLogTargetOverflowAction.Truncate, int maxMessageLength = MaxMessageLength)
        {
            var sourceName = "NLog.UnitTests" + Guid.NewGuid().ToString("N");

            var eventLogMock = new EventLogMock(
                deleteEventSourceFunction: (source, machineName) => { },
                sourceExistsFunction: (source, machineName) => false,
                logNameFromSourceNameFunction: (source, machineName) => string.Empty,
                createEventSourceFunction: (sourceData) => { });
            var target = new EventLogTarget(eventLogMock, null);

            InitializeEventLogTarget(target, sourceName, overflowAction, maxMessageLength, entryType);

            SimpleConfigurator.ConfigureForTargetLogging(target, LogLevel.Trace);

            var logger = LogManager.GetLogger("WriteEventLogEntry");

            logger.Log(logLevel, logMessage);

            var entries = eventLogMock.WrittenEntries;

            var expectedSource = target.GetFixedSource();

            var filteredEntries = entries.Where(entry =>
                                                entry.Source == expectedSource &&
                                                entry.EntryType == expectedEventLogEntryType
                                                );

            if (overflowAction == EventLogTargetOverflowAction.Discard && logMessage.Length > maxMessageLength)
            {
                Assert.False(filteredEntries.Any(),
                             $"No message is expected. But {filteredEntries.Count()} message(s) found entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'.");
            }
            else
            {
                Assert.True(filteredEntries.Any(),
                            $"Failed to find entry of type '{expectedEventLogEntryType}' from source '{expectedSource}'");
            }

            return(filteredEntries);
        }