public static LoggingConfiguration BuildProgrammaticConfig(bool isAsync = false)
        {
            var formatter = new TextFormatter();

            var flatFileTraceListener = new FlatFileTraceListener(@"FlatFile.log",
                                                                  "----------------------------------------",
                                                                  "----------------------------------------",
                                                                  formatter);

            //   var eventLog = new EventLog("Application", ".", "LoggingApplication");
            //   var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog, formatter);

            // Build Configuration
            var config = new LoggingConfiguration();

            if (isAsync == false)
            {
                config.AddLogSource("General", SourceLevels.All, true)
                // .AddTraceListener(eventLogTraceListener);
                .AddTraceListener(flatFileTraceListener);
            }
            else
            {
                config.AddLogSource("General", SourceLevels.All, true)
                // .AddTraceListener(eventLogTraceListener);
                .AddAsynchronousTraceListener(flatFileTraceListener);
            }


            config.IsTracingEnabled = true;
            return(config);
        }
        public void SharedTraceListener()
        {
            var sharedTraceListener = new DefaultTraceListener();

            var config = new LoggingConfiguration();

            config.AddLogSource("General").AddTraceListener(sharedTraceListener);
            config.AddLogSource("Special", SourceLevels.Critical, true, sharedTraceListener);

            Assert.AreEqual <int>(2, config.LogSources.Count);
            Assert.AreEqual <string>("General", config.LogSources.First().Name);
            Assert.AreEqual <string>("Special", config.LogSources.Last().Name);
        }
        public void AddLogSourcesIsSetAsDefault()
        {
            var config = new LoggingConfiguration();

            Assert.IsNull(config.DefaultSource);

            config.AddLogSource("Default");

            Assert.AreEqual <string>("Default", config.DefaultSource);

            config.AddLogSource("Second");

            Assert.AreEqual <string>("Default", config.DefaultSource);
        }
Exemplo n.º 4
0
        static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatters
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");

            // Category Filters
            ICollection <string> categories = new List <string>();

            categories.Add("BlockedByFilter");

            // Log Filters
            var priorityFilter   = new PriorityFilter("Priority Filter", 2, 99);
            var logEnabledFilter = new LogEnabledFilter("LogEnabled Filter", true);
            var categoryFilter   = new CategoryFilter("Category Filter", categories, CategoryFilterMode.AllowAllExceptDenied);

            // Trace Listeners
            var flatFileTraceListener = new FlatFileTraceListener(@"C:\Temp\ConfigSampleFlatFile.log", "----------------------------------------", "----------------------------------------", formatter);

            // Build Configuration
            var config = new LoggingConfiguration();

            config.Filters.Add(priorityFilter);
            config.Filters.Add(logEnabledFilter);
            config.Filters.Add(categoryFilter);

            config.AddLogSource("General", SourceLevels.All, true, flatFileTraceListener);

            return(config);
        }
        private void UpdateConfigForRollingFlatFileRollExistsIncrement(LoggingConfiguration loggingConfiguration)
        {
            var rollingFlatFileTraceListener = new RollingFlatFileTraceListener(Path.Combine(strPath, "RollingFlatFile.log"), "----------------------------------------", "----------------------------------------", extendedFormatter, 1, "yyyy", RollFileExistsBehavior.Increment, RollInterval.None, 3);

            loggingConfiguration.AddLogSource("RollFFIncrement", SourceLevels.All, true, rollingFlatFileTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(rollingFlatFileTraceListener);
        }
Exemplo n.º 6
0
        /// <summary>
        /// Initializes a new instance of the <see cref="EnterpriseLibraryLoggerAdapter"/> class.
        /// </summary>
        static EnterpriseLibraryLoggerAdapter()
        {
            TextFormatter _extendedFormatter = new TextFormatter("Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}Severity: {severity}{newline}Title: {title}{newline}Activity ID: {property(ActivityId)}{newline}Machine: {localMachine}{newline}App Domain: {localAppDomain}{newline}ProcessId: {localProcessId}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}Win32 ThreadId:{win32ThreadId}{newline}Extended Properties: {dictionary({key} - {value}{newline})}");
            TextFormatter _briefFormatter    = new TextFormatter("{timestamp(local)};{message};{category};{priority};{eventid};{severity};{title}");

            // Category Filters
            ICollection <string> _categories = new List <string>();

            _categories.Add("BlockedByFilter");

            // Log Filters
            PriorityFilter   _priorityFilter   = new PriorityFilter("Priority Filter", -1, 99);
            LogEnabledFilter _logEnabledFilter = new LogEnabledFilter("LogEnabled Filter", true);
            CategoryFilter   _categoryFilter   = new CategoryFilter("Category Filter", _categories, CategoryFilterMode.AllowAllExceptDenied);

            FlatFileTraceListener _flatFileTraceListener = new FlatFileTraceListener($"{nameof(ConfigurationEditorBase)}.log", string.Empty, string.Empty, _briefFormatter);
            LoggingConfiguration  _configuration         = new LoggingConfiguration();

            _configuration.Filters.Add(_priorityFilter);
            _configuration.Filters.Add(_logEnabledFilter);
            _configuration.Filters.Add(_categoryFilter);
            _configuration.AddLogSource("Debug", System.Diagnostics.SourceLevels.All, true, _flatFileTraceListener);
            FlatFileTraceListener unprocessedFlatFileTraceListener = new FlatFileTraceListener(@"Unprocessed.log", "----------------------------------------", "----------------------------------------", _extendedFormatter);

            _configuration.SpecialSources.Unprocessed.AddTraceListener(unprocessedFlatFileTraceListener);
            FlatFileTraceListener _LoggingErrorsAndWarningsTraceListener = new FlatFileTraceListener(@"LoggingErrorsAndWarnings.log", "----------------------------------------", "----------------------------------------", _extendedFormatter);

            _configuration.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(_LoggingErrorsAndWarningsTraceListener);
            Logger.SetLogWriter(new LogWriter(_configuration));
        }
        public void MessageIsSetWhenUsingJsonFormatter()
        {
            LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace();

            JsonLogFormatter jsonformatter = new JsonLogFormatter(JsonFormatting.Indented);

            EmailTraceListener emailListener = new EmailTraceListener(this.toaddress,
                                                                      this.fromaddress,
                                                                      "StartOfSubject",
                                                                      "EndOfSubject", this.smtpserver, jsonformatter);

            emailListener.Filter = new EventTypeFilter(SourceLevels.All);
            loggingConfiguration.AddLogSource("Email", SourceLevels.All, true, emailListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(emailListener);

            string message = "Test JSON";

            this.writer = new LogWriter(loggingConfiguration);
            this.writer.Write(message, "General");
            this.writer.Dispose();

            LogEntry logEntry = LogFileReader.GetLogEntryFromEmail();

            Assert.IsTrue(logEntry.Message == message);
        }
        public void JsonFormatterHeadersAreSetWhenSendingEmail()
        {
            DateTime messageTimestamp = DateTime.UtcNow;

            LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace();

            JsonLogFormatter jsonformatter = new JsonLogFormatter(JsonFormatting.Indented);

            EmailTraceListener emailListener = new EmailTraceListener(this.toaddress,
                                                                      this.fromaddress,
                                                                      "StartOfSubject",
                                                                      "EndOfSubject", this.smtpserver, jsonformatter);

            emailListener.Filter = new EventTypeFilter(SourceLevels.All);
            loggingConfiguration.AddLogSource("Email", SourceLevels.All, true, emailListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(emailListener);

            string message = "Test JSON";

            this.writer = new LogWriter(loggingConfiguration);
            this.writer.Write(message, "General");
            this.writer.Dispose();

            string emailText   = LogFileReader.GetEmail();
            string endOfHeader = "\r\n\r\n";
            int    index       = emailText.IndexOf(endOfHeader);
            string header      = emailText.Substring(0, index);

            Dictionary <string, string> emailDictionary = Regex.Split(header, "\r\n").Select(e => e.Split(':')).ToDictionary(line => line[0], line => line[1].Trim());

            Assert.AreEqual("StartOfSubject Information EndOfSubject", emailDictionary["Subject"]);
            Assert.AreEqual(this.fromaddress, emailDictionary["From"]);
            Assert.AreEqual(this.toaddress, emailDictionary["To"]);
        }
Exemplo n.º 9
0
        public void AllEntriesAreWrittenWhenUsingAsynchForFormattedDatabase()
        {
            this.ClearLogs();
            string      unique          = Guid.NewGuid().ToString();
            SqlDatabase dbConnection    = new SqlDatabase(connectionString);
            int         messageContents = 0;

            var configuration = new LoggingConfiguration();

            configuration.AddLogSource("TestAsynchLogging In FormattedDatabase")
            .AddTraceListener(new AsynchronousTraceListenerWrapper(
                                  new FormattedDatabaseTraceListener(dbConnection, "WriteLog", "AddCategory", null),
                                  ownsWrappedTraceListener: true,
                                  bufferSize: 10000));

            using (var writer = new LogWriter(configuration))
            {
                Parallel.Invoke(Enumerable.Range(0, 10000).Select(i =>
                                                                  new Action(() =>
                {
                    writer.Write(unique + " Test Asynch Message: " + i);
                })).ToArray());
            }

            using (var connection = new SqlConnection(connectionString))
            {
                connection.Open();
                SqlCommand command = new SqlCommand("select COUNT(1) from Log where Message like '" + unique + " Test Asynch Message:%'", connection);
                messageContents = (Int32)command.ExecuteScalar();
                connection.Close();
            }

            Assert.AreEqual(10000, messageContents);
        }
        public void CreatesLoggingExceptionHandlerWithProgrammaticConfiguration()
        {
            var loggingConfiguration  = new LoggingConfiguration();
            var eventLog              = new EventLog("Application", ".", "ExceptionHandling.Bvt.Tests - Programmatic");
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog, new TextFormatter("{message}"));

            loggingConfiguration.AddLogSource("Sample Category", SourceLevels.All, true).AddTraceListener(eventLogTraceListener);
            var logWriter = new LogWriter(loggingConfiguration);

            var excepionPolicies      = new List <ExceptionPolicyDefinition>();
            var excepionPolicyEntries = new List <ExceptionPolicyEntry>();
            var exceptionHandler      = new LoggingExceptionHandler("Sample Category", 100, TraceEventType.Transfer, "Sample Title", 4, typeof(TextExceptionFormatter), logWriter);
            var exceptionPolicy       = new ExceptionPolicyEntry(typeof(DivideByZeroException), PostHandlingAction.None, new IExceptionHandler[] { exceptionHandler });

            excepionPolicyEntries.Add(exceptionPolicy);
            excepionPolicies.Add(new ExceptionPolicyDefinition("Logging Policy", excepionPolicyEntries));

            var exceptionManager = new ExceptionManager(excepionPolicies);
            var exceptionTothrow = new DivideByZeroException("error message");

            exceptionManager.HandleException(exceptionTothrow, "Logging Policy");
            var entry = EventLogEntries.Last;

            Assert.IsTrue(entry.Message.Contains("Type : " + exceptionTothrow.GetType().FullName));
            Assert.IsTrue(entry.Message.Contains("Message : error message"));
        }
Exemplo n.º 11
0
        /// <summary>
        /// Builds Programmatic Configuration for Logging
        /// </summary>
        /// <returns>LoggingConfiguration</returns>
        public static LoggingConfiguration BuildProgrammaticConfig()
        {
            ResourceManager resxManager = new ResourceManager(ConfigurationManager.AppSettings["FmoMessages_ResourceFileName"], Assembly.GetExecutingAssembly());

            // Formatters
            TextFormatter formatter = new TextFormatter(ErrorConstants.Logging_TextFormat);

            // Listeners
            // var flatFileTraceListener = new FlatFileTraceListener(string.Concat(ConfigurationManager.AppSettings["LogFilePath"], ConfigurationManager.AppSettings["ErrorLogFileName"]), "----------------------------------------", "----------------------------------------", formatter);
            var rollingFlatFileTraceListener = new RollingFlatFileTraceListener(string.Concat(ConfigurationManager.AppSettings["LogFilePath"], ConfigurationManager.AppSettings["ErrorLogFileName"]), "----------------------------------------", "----------------------------------------", formatter, 20, "yyyy-MM-dd", RollFileExistsBehavior.Increment, RollInterval.None, 3);

            var eventLog = new EventLog(ErrorConstants.Logging_LogName, ".", ErrorConstants.Logging_LogSource);
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog);

            // Build Configuration
            var config = new LoggingConfiguration();

            config.AddLogSource(ErrorConstants.LogSource_LogSourceName, SourceLevels.All, true).AddTraceListener(eventLogTraceListener);

            // config.LogSources["General"].AddTraceListener(flatFileTraceListener);
            config.LogSources[ErrorConstants.LogSource_LogSourceName].AddTraceListener(rollingFlatFileTraceListener);

            // Special Sources Configuration
            config.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(eventLogTraceListener);

            return(config);
        }
        private void UpdateConfigForRollingFlatFileRollExistsOverwrite(LoggingConfiguration loggingConfiguration)
        {
            var rollingFlatFileTraceListener = new RollingFlatFileTraceListener(Path.Combine(strPath, "RollingFlatFile.log"), "----------------------------------------", "----------------------------------------", extendedFormatter, 0, String.Empty, RollFileExistsBehavior.Overwrite, RollInterval.None, 3);

            loggingConfiguration.AddLogSource("RollFFOverwrite", SourceLevels.All, true, rollingFlatFileTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(rollingFlatFileTraceListener);
        }
Exemplo n.º 13
0
        public void MultipleFilesAreWrittenWhenUsingAsynchForRollingFlatFile()
        {
            const string Folder = "AsyncFolder";
            const string FileNameWithoutExtension = "AsynchTestingForRollingFlatFile";
            const string Extension = ".log";
            const string FileName  = FileNameWithoutExtension + Extension;

            LogFileReader.CreateDirectory(Folder);

            var configuration = new LoggingConfiguration();

            configuration.AddLogSource("TestAsynchLogging In RollingFlatFile").AddTraceListener(new AsynchronousTraceListenerWrapper(
                                                                                                    new RollingFlatFileTraceListener(Path.Combine(Folder, FileName), "----", "----", new TextFormatter(), 8, "yyyy",
                                                                                                                                     RollFileExistsBehavior.Increment, RollInterval.Minute, 10), ownsWrappedTraceListener: true, bufferSize: 100));

            using (var writer = new LogWriter(configuration))
            {
                Parallel.Invoke(Enumerable.Range(0, 100).Select(i =>
                                                                new Action(() =>
                {
                    writer.Write("Test Asynch Message: " + i);
                })).ToArray());
            }

            Assert.IsTrue(File.Exists(Path.Combine(Folder, FileName)));
            Assert.IsTrue(File.Exists(Path.Combine(Folder, FileNameWithoutExtension + "." + DateTime.Now.Year + ".1" + Extension)));
            Assert.IsTrue(File.Exists(Path.Combine(Folder, FileNameWithoutExtension + "." + DateTime.Now.Year + ".5" + Extension)));
        }
        public void AddsLogSourceToCollection()
        {
            var config = new LoggingConfiguration();
            config.AddLogSource("mock", new MockTraceListener());

            Assert.AreEqual<int>(1, config.LogSources["mock"].Listeners.Count);
        }
Exemplo n.º 15
0
        public void DisposingWriterDisposesAllTraceListenersOnce()
        {
            var traceListener = new MockDisposableTraceListener();

            var config = new LoggingConfiguration();

            config.AddLogSource("cat1", traceListener);
            config.AddLogSource("cat2", traceListener);
            config.SpecialSources.AllEvents.Listeners.Add(traceListener);

            var logWriter = new LogWriter(config);

            logWriter.Dispose();

            Assert.AreEqual(1, traceListener.DisposedCalls);
        }
        /// <summary>Builds the configuration used to log entries to the file system.</summary>
        /// <returns>A <see cref="LoggingConfiguration"/> with default settings.</returns>
        private LoggingConfiguration BuildLoggingConfiguration()
        {
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");

            ICollection <string> categories = new List <string> {
                "BlockedByFilter"
            };

            PriorityFilter   priorityFilter   = new PriorityFilter("PriorityFilter", -1);
            LogEnabledFilter logEnabledFilter = new LogEnabledFilter("LogEnabled Filter", true);
            CategoryFilter   categoryFilter   = new CategoryFilter("CategoryFilter", categories, CategoryFilterMode.AllowAllExceptDenied);

            RollingFlatFileTraceListener rollingFileListener = new RollingFlatFileTraceListener(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"SCH\Logs\Everything.log"),
                "----------------------------------------",
                "----------------------------------------",
                formatter,
                200,
                "yyyy-MM-dd",
                RollFileExistsBehavior.Increment,
                RollInterval.None,
                5);

            RollingFlatFileTraceListener errorFileListener = new RollingFlatFileTraceListener(
                Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData), @"SCH\Logs\Errors.log"),
                "----------------------------------------",
                "----------------------------------------",
                formatter,
                200,
                "yyyy-MM-dd",
                RollFileExistsBehavior.Increment,
                RollInterval.None,
                2);

            // Build Configuration
            LoggingConfiguration config = new LoggingConfiguration();

            config.Filters.Add(priorityFilter);
            config.Filters.Add(logEnabledFilter);
            config.Filters.Add(categoryFilter);

            config.AddLogSource(LoggingConstants.CategoryGeneralConst, SourceLevels.All, true, rollingFileListener);
            config.AddLogSource(LoggingConstants.CategoryCompilerConst, SourceLevels.All, true, rollingFileListener);
            config.AddLogSource(LoggingConstants.CategoryErrorConst, SourceLevels.Warning, true, errorFileListener);

            return(config);
        }
        public void ThrowsArgumentNullIfAddLogSourceIsNull()
        {
            MockDisposableTraceListener listener = null;

            var config = new LoggingConfiguration();

            AssertEx.Throws <ArgumentNullException>(() => config.AddLogSource("test", listener));
        }
        public void AddsLogSourceToCollection()
        {
            var config = new LoggingConfiguration();

            config.AddLogSource("mock", new MockTraceListener());

            Assert.AreEqual <int>(1, config.LogSources["mock"].Listeners.Count);
        }
        public void ShouldNotAutoflushByDefault()
        {
            var config = new LoggingConfiguration();

            config.AddLogSource("Default");

            Assert.AreEqual <bool>(false, config.LogSources["Default"].AutoFlush);
        }
        private void UpdateConfigForEventlogSourceLogMachineFormatter(LoggingConfiguration loggingConfiguration)
        {
            var eventLogTraceListener = new FormattedEventLogTraceListener("Enterprise Library Logging", "Application", ".", briefFormatter);

            loggingConfiguration.AddLogSource("General", SourceLevels.All, true, eventLogTraceListener);
            loggingConfiguration.SpecialSources.LoggingErrorsAndWarnings.Listeners.Add(eventLogTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(eventLogTraceListener);
        }
        public void ShouldHaveDefaultSourceLevel()
        {
            var config = new LoggingConfiguration();

            config.AddLogSource("Default");

            Assert.AreEqual <SourceLevels>(SourceLevels.All, config.LogSources["Default"].Level);
        }
Exemplo n.º 22
0
        private void UpdateConfigForDatabaseTL(LoggingConfiguration loggingConfiguration)
        {
            SqlDatabase dbConnection = new SqlDatabase(connectionString);

            var databaseTraceListener = new FormattedDatabaseTraceListener(dbConnection, "WriteLog", "AddCategory", briefFormatter);

            loggingConfiguration.AddLogSource("Database", SourceLevels.All, true, databaseTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(databaseTraceListener);
        }
Exemplo n.º 23
0
        public void UpdateConfigForXMLTL(LoggingConfiguration loggingConfiguration)
        {
            var xmlTraceListener = new XmlTraceListener(Path.Combine(strPath, "XmlLogFile.xml"));

            xmlTraceListener.Filter = new EventTypeFilter(SourceLevels.All);
            loggingConfiguration.IsTracingEnabled = false;
            loggingConfiguration.AddLogSource("XML", SourceLevels.All, true, xmlTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(xmlTraceListener);
        }
Exemplo n.º 24
0
        private static void ConfigureLogger()
        {
            var configuration = new LoggingConfiguration();

            configuration.AddLogSource("default", new ConsoleTraceListener());
            configuration.DefaultSource = "default";
            var logWriter = new LogWriter(configuration);

            Logger.SetLogWriter(logWriter, false);
        }
Exemplo n.º 25
0
        private static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatter
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");

            // Trace Listeners
            var eventLog = new EventLog("Application", ".", "EnoughPI");
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog, formatter);
            var flatFileTraceListener = new FlatFileTraceListener(@"C:\Temp\trace.log", "----------------------------------------", "----------------------------------------", formatter);

            // Build Configuration
            var config = new LoggingConfiguration();

            config.AddLogSource(Category.General, SourceLevels.All, true).AddTraceListener(eventLogTraceListener);
            config.AddLogSource(Category.Trace, SourceLevels.ActivityTracing, true).AddTraceListener(flatFileTraceListener);
            config.IsTracingEnabled = true;

            return(config);
        }
Exemplo n.º 26
0
        /// <summary>
        /// Create a LogWrite that writes to the MemoryStream.
        /// </summary>
        /// <param name="memStream">Log will be written here.</param>
        /// <returns>A new LogWriter</returns>
        private static LogWriter CreateLogWriter(MemoryStream memStream)
        {
            var config = new LoggingConfiguration();
            var source = config.AddLogSource(
                "All", System.Diagnostics.SourceLevels.All, true);

            source.AddAsynchronousTraceListener(new FormattedTextWriterTraceListener(
                                                    memStream, new TextFormatter("{message}\n")));
            return(new LogWriter(config));
        }
        private static LogWriter CreateStandardOutputLogWriter()
        {
            var traceListener = new FormattedTextWriterTraceListener(
                Console.OpenStandardOutput(), new TextFormatter("{timestamp}:\t{message}\n"));
            var config = new LoggingConfiguration();

            config.AddLogSource("StandardOutput", System.Diagnostics.SourceLevels.All, true)
            .AddAsynchronousTraceListener(traceListener);
            return(new LogWriter(config));
        }
Exemplo n.º 28
0
        private static void ConfigureXmlLogging(LoggingConfiguration config)
        {
            //  Create a listener that formats events as XML
            XmlTraceListener xmllog
                = new XmlTraceListener(@"C:\temp\application log.xml");

            //  Set it to only listen to Error AND ABOVE
            xmllog.Filter = new EventTypeFilter(SourceLevels.Error);

            //  Tell the config to use this (Category = xml)
            config.AddLogSource("xml", SourceLevels.All, true).AddTraceListener(xmllog);
        }
Exemplo n.º 29
0
        public LoggingViewModel()
        {
            var logFormatter = new TextFormatter();

            var flatFileTraceListener = new FlatFileTraceListener("log.hblog", "-------------------------",
                                                                  "-------------------------", logFormatter);

            var config = new LoggingConfiguration();

            config.AddLogSource("Hummingbird", SourceLevels.All, true).AddTraceListener(flatFileTraceListener);
            Logger = new LogWriter(config);
        }
        public void CanGetAllTraceListeners()
        {
            var listener1 = new MockTraceListener();
            var listener2 = new MockTraceListener();
            var listener3 = new MockTraceListener();
            var listener4 = new MockTraceListener();

            var config = new LoggingConfiguration();

            config.AddLogSource("source1", listener1, listener2);
            config.AddLogSource("source2", listener2);
            config.AddLogSource("source3", listener1, listener3);
            config.AddLogSource("source4");

            config.SpecialSources.Unprocessed.AddTraceListener(listener2);
            config.SpecialSources.Unprocessed.AddTraceListener(listener4);

            var allListeners = config.AllTraceListeners.ToArray();

            Assert.AreEqual(4, allListeners.Length);
            CollectionAssert.AreEquivalent(new TraceListener[] { listener1, listener2, listener3, listener4 }, allListeners);
        }
Exemplo n.º 31
0
        static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatters
            TextFormatter briefFormatter    = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");
            TextFormatter extendedFormatter = new TextFormatter("Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}Severity: {severity}{newline}Title: {title}{newline}Activity ID: {property(ActivityId)}{newline}Machine: {localMachine}{newline}App Domain: {localAppDomain}{newline}ProcessId: {localProcessId}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}Win32 ThreadId:{win32ThreadId}{newline}Extended Properties: {dictionary({key} - {value}{newline})}");

            // Category Filters
            ICollection <string> categories = new List <string>();

            categories.Add("BlockedByFilter");

            // Log Filters
            var priorityFilter   = new PriorityFilter("Priority Filter", 2, 99);
            var logEnabledFilter = new LogEnabledFilter("LogEnabled Filter", true);
            var categoryFilter   = new CategoryFilter("Category Filter", categories, CategoryFilterMode.AllowAllExceptDenied);

            // Trace Listeners
            var causeLoggingErrorTraceListener = new FormattedDatabaseTraceListener(DatabaseFactory.CreateDatabase("DoesNotExist"), "WriteLog", "AddCategory", null);
            var databaseTraceListener          = new FormattedDatabaseTraceListener(DatabaseFactory.CreateDatabase("ExampleDatabase"), "WriteLog", "AddCategory", extendedFormatter);
            var flatFileTraceListener          = new FlatFileTraceListener(@"C:\Temp\FlatFile.log", "----------------------------------------", "----------------------------------------", briefFormatter);
            var eventLog = new EventLog("Application", ".", "Enterprise Library Logging");
            var eventLogTraceListener            = new FormattedEventLogTraceListener(eventLog);
            var rollingFlatFileTraceListener     = new RollingFlatFileTraceListener(@"C:\Temp\RollingFlatFile.log", "----------------------------------------", "----------------------------------------", extendedFormatter, 20, "yyyy-MM-dd", RollFileExistsBehavior.Increment, RollInterval.None, 3);
            var unprocessedFlatFileTraceListener = new FlatFileTraceListener(@"C:\Temp\Unprocessed.log", "----------------------------------------", "----------------------------------------", extendedFormatter);
            var xmlTraceListener = new XmlTraceListener(@"C:\Temp\XmlLogFile.xml");

            xmlTraceListener.Filter = new EventTypeFilter(SourceLevels.Error);

            // Build Configuration
            var config = new LoggingConfiguration();

            config.Filters.Add(priorityFilter);
            config.Filters.Add(logEnabledFilter);
            config.Filters.Add(categoryFilter);

            config.AddLogSource("BlockedByFilter", SourceLevels.All, true).AddTraceListener(eventLogTraceListener);
            config.AddLogSource("CauseLoggingError", SourceLevels.All, true).AddTraceListener(causeLoggingErrorTraceListener);
            config.AddLogSource("Database", SourceLevels.All, true).AddTraceListener(databaseTraceListener);
            // The defaults for the asynchronous wrapper are:
            //   bufferSize: 30000
            //   disposeTimeout: infinite
            config.AddLogSource("AsyncDatabase", SourceLevels.All, true).AddAsynchronousTraceListener(databaseTraceListener);
            config.AddLogSource("DiskFiles", SourceLevels.All, true).AddTraceListener(flatFileTraceListener);
            config.LogSources["DiskFiles"].AddTraceListener(xmlTraceListener);
            config.AddLogSource("General", SourceLevels.All, true).AddTraceListener(eventLogTraceListener);
            config.AddLogSource("Important", SourceLevels.All, true).AddTraceListener(eventLogTraceListener);
            config.LogSources["Important"].AddTraceListener(rollingFlatFileTraceListener);

            // Special Sources Configuration
            config.SpecialSources.Unprocessed.AddTraceListener(unprocessedFlatFileTraceListener);
            config.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(eventLogTraceListener);

            return(config);
        }
        public void CanGetAllTraceListeners()
        {
            var listener1 = new MockTraceListener();
            var listener2 = new MockTraceListener();
            var listener3 = new MockTraceListener();
            var listener4 = new MockTraceListener();

            var config = new LoggingConfiguration();

            config.AddLogSource("source1", listener1, listener2);
            config.AddLogSource("source2", listener2);
            config.AddLogSource("source3", listener1, listener3);
            config.AddLogSource("source4");

            config.SpecialSources.Unprocessed.AddTraceListener(listener2);
            config.SpecialSources.Unprocessed.AddTraceListener(listener4);

            var allListeners = config.AllTraceListeners.ToArray();

            Assert.AreEqual(4, allListeners.Length);
            CollectionAssert.AreEquivalent(new TraceListener[] { listener1, listener2, listener3, listener4 }, allListeners);
        }
Exemplo n.º 33
0
        public void DisposingWriterDisposesAllTraceListenersOnce()
        {
            var traceListener = new MockDisposableTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("cat1", traceListener);
            config.AddLogSource("cat2", traceListener);
            config.SpecialSources.AllEvents.Listeners.Add(traceListener);

            var logWriter = new LogWriter(config);
            logWriter.Dispose();

            Assert.AreEqual(1, traceListener.DisposedCalls);
        }
        public void ShouldHaveDefaultSourceLevel()
        {
            var config = new LoggingConfiguration();
            config.AddLogSource("Default");

            Assert.AreEqual<SourceLevels>(SourceLevels.All, config.LogSources["Default"].Level);
        }
        public void AddLogSourcesIsSetAsDefault()
        {
            var config = new LoggingConfiguration();

            Assert.IsNull(config.DefaultSource);

            config.AddLogSource("Default");

            Assert.AreEqual<string>("Default", config.DefaultSource);

            config.AddLogSource("Second");

            Assert.AreEqual<string>("Default", config.DefaultSource);
        }
        public void ShouldNotAutoflushByDefault()
        {
            var config = new LoggingConfiguration();
            config.AddLogSource("Default");

            Assert.AreEqual<bool>(false, config.LogSources["Default"].AutoFlush);
        }
        public void ReconfigureDisposesUnusedListeners()
        {
            var traceListener = new MockDisposableTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("General", traceListener);

            var logWriter = new LogWriter(config);
            logWriter.Configure((cfg) =>
            {
                cfg.LogSources.Clear();

                cfg.AddLogSource("New", new DefaultTraceListener());
            });

            Assert.AreEqual(1, traceListener.DisposedCalls);
        }
        public void ReconfigureDoesNotDisposeListenersStillUsedInSpecialSources()
        {
            var traceListener = new MockDisposableTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("General", traceListener);

            var logWriter = new LogWriter(config);
            logWriter.Configure((cfg) =>
            {
                cfg.LogSources.Clear();

                cfg.AddLogSource("New", new DefaultTraceListener());
                cfg.SpecialSources.AllEvents.Listeners.Add(traceListener);
            });

            Assert.AreEqual(0, traceListener.DisposedCalls);
        }
        public void ThrowsArgumentNullIfAddLogSourceIsNull()
        {
            MockDisposableTraceListener listener = null;

            var config = new LoggingConfiguration();

            AssertEx.Throws<ArgumentNullException>(() => config.AddLogSource("test", listener));
        }
        public void CanAddAsynchronousTraceListener()
        {
            var listener = new MockTraceListener { Name = "listener", Filter = new EventTypeFilter(SourceLevels.Critical) };

            var config = new LoggingConfiguration();

            config.AddLogSource("test").AddAsynchronousTraceListener(listener);

            var addedListener = (AsynchronousTraceListenerWrapper)config.AllTraceListeners.First();

            Assert.AreSame(listener, addedListener.TraceListener);
            Assert.AreEqual("listener", addedListener.Name);
            Assert.AreEqual(SourceLevels.Critical, ((EventTypeFilter)addedListener.Filter).EventType);
        }
        public void SharedTraceListener()
        {
            var sharedTraceListener = new DefaultTraceListener();

            var config = new LoggingConfiguration();
            config.AddLogSource("General").AddTraceListener(sharedTraceListener);
            config.AddLogSource("Special", SourceLevels.Critical, true, sharedTraceListener);

            Assert.AreEqual<int>(2, config.LogSources.Count);
            Assert.AreEqual<string>("General", config.LogSources.First().Name);
            Assert.AreEqual<string>("Special", config.LogSources.Last().Name);
        }