public void CanCreateInstanceFromConfigurationFileWithMinimalConfiguration()
        {
            LoggingSettings loggingSettings = new LoggingSettings();

            loggingSettings.Formatters.Add(new TextFormatterData("formatter", "some template"));
            FormattedEventLogTraceListenerData listenerData = new FormattedEventLogTraceListenerData();

            listenerData.Name             = "listener";
            listenerData.Type             = typeof(FormattedEventLogTraceListener);
            listenerData.ListenerDataType = typeof(FormattedEventLogTraceListenerData);
            listenerData.Source           = "unknown source";
            listenerData.Formatter        = "formatter";
            loggingSettings.TraceListeners.Add(listenerData);

            TraceListener listener =
                GetListener("listener", CommonUtil.SaveSectionsAndGetConfigurationSource(loggingSettings));

            Assert.IsNotNull(listener);
            Assert.AreEqual(listener.GetType(), typeof(FormattedEventLogTraceListener));
            FormattedEventLogTraceListener castedListener = (FormattedEventLogTraceListener)listener;

            Assert.IsNotNull(castedListener.Formatter);
            Assert.AreEqual("unknown source", ((EventLogTraceListener)castedListener.InnerListener).EventLog.Source);
            //Assert.AreEqual(FormattedEventLogTraceListener.DefaultLogName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.Log);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultMachineName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.MachineName);
            Assert.AreEqual(castedListener.Formatter.GetType(), typeof(TextFormatter));
            Assert.AreEqual("some template", ((TextFormatter)castedListener.Formatter).Template);
        }
        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"));
        }
コード例 #3
0
        public void CanCreatePoliciesForFormattedEventLogTraceListenerWithFormatter()
        {
            FormattedEventLogTraceListenerData listenerData
                = new FormattedEventLogTraceListenerData("listener", CommonUtil.EventLogSourceName, CommonUtil.EventLogName, "machine", "formatter");

            listenerData.TraceOutputOptions = TraceOptions.Callstack | TraceOptions.ProcessId;
            listenerData.Filter             = SourceLevels.Error;
            loggingSettings.TraceListeners.Add(listenerData);

            FormatterData formatterData = new TextFormatterData("formatter", "template");

            loggingSettings.Formatters.Add(formatterData);

            using (var container = CreateContainer())
            {
                FormattedEventLogTraceListener createdObject =
                    (FormattedEventLogTraceListener)container.Resolve <TraceListener>("listener\u200cimplementation");

                Assert.IsNotNull(createdObject);
                Assert.AreEqual(listenerData.TraceOutputOptions, createdObject.TraceOutputOptions);
                Assert.IsNotNull(createdObject.Filter);
                Assert.IsInstanceOfType(createdObject.Filter, typeof(EventTypeFilter));
                Assert.AreEqual(listenerData.Filter, ((EventTypeFilter)createdObject.Filter).EventType);
                Assert.IsNotNull(createdObject.Formatter);
                Assert.AreSame(typeof(TextFormatter), createdObject.Formatter.GetType());
                Assert.AreEqual("template", ((TextFormatter)createdObject.Formatter).Template);
                Assert.AreEqual(CommonUtil.EventLogSourceName, ((EventLogTraceListener)createdObject.InnerListener).EventLog.Source);
                Assert.AreEqual(CommonUtil.EventLogName, ((EventLogTraceListener)createdObject.InnerListener).EventLog.Log);
                Assert.AreEqual("machine", ((EventLogTraceListener)createdObject.InnerListener).EventLog.MachineName);
            }
        }
コード例 #4
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);
        }
        public void CanCreateInstanceFromGivenName()
        {
            FormattedEventLogTraceListenerData listenerData = new FormattedEventLogTraceListenerData("listener", "unknown source", "formatter");

            MockLogObjectsHelper helper = new MockLogObjectsHelper();

            helper.loggingSettings.Formatters.Add(new TextFormatterData("formatter", "some template"));
            helper.loggingSettings.TraceListeners.Add(listenerData);

            TraceListener listener = GetListener("listener", helper.configurationSource);

            Assert.IsNotNull(listener);
            Assert.AreEqual("listener", listener.Name);
            Assert.AreEqual(listener.GetType(), typeof(FormattedEventLogTraceListener));
            FormattedEventLogTraceListener castedListener = (FormattedEventLogTraceListener)listener;

            Assert.IsNotNull(castedListener.Formatter);
            Assert.AreEqual("unknown source", ((EventLogTraceListener)castedListener.InnerListener).EventLog.Source);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultMachineName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.MachineName);
            Assert.AreEqual(castedListener.Formatter.GetType(), typeof(TextFormatter));
            Assert.AreEqual("some template", ((TextFormatter)castedListener.Formatter).Template);

            try
            {
                Assert.AreEqual(FormattedEventLogTraceListener.DefaultLogName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.Log);
            }
            catch (SecurityException ex)
            {
                Assert.Inconclusive("In order to run the tests, please run Visual Studio as Administrator.\r\n{0}", ex.ToString());
            }
        }
コード例 #6
0
        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 CanCreateListenerWithSourceAndFormatter()
        {
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener("unknown source", new TextFormatter("TEST"));

            Assert.IsNotNull(listener.Formatter);
            Assert.IsNotNull(listener.InnerListener);
            Assert.AreEqual(typeof(EventLogTraceListener), listener.InnerListener.GetType());
            Assert.AreEqual("unknown source", ((EventLogTraceListener)listener.InnerListener).EventLog.Source);
            Assert.AreEqual("", ((EventLogTraceListener)listener.InnerListener).EventLog.Log);
            Assert.AreEqual(".", ((EventLogTraceListener)listener.InnerListener).EventLog.MachineName);
        }
コード例 #8
0
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry     testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StringWriter writer    = new StringWriter();
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, null);
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);

            source.Listeners.Add(listener);
            source.TraceData(TraceEventType.Error, 1, testEntry);
            Assert.AreEqual(testEntry.ToString(), CommonUtil.GetLastEventLogEntryCustom());
        }
コード例 #9
0
        public void CanCreateListenerWithSourceFormatterAndDefaultLogMachineName()
        {
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener("unknown source", "", ".", new TextFormatter("TEST"));

            Assert.IsNotNull(listener.Formatter);
            Assert.IsNotNull(listener.SlaveListener);
            Assert.AreEqual(typeof(EventLogTraceListener), listener.SlaveListener.GetType());
            Assert.AreEqual("unknown source", ((EventLogTraceListener)listener.SlaveListener).EventLog.Source);
            Assert.AreEqual("", ((EventLogTraceListener)listener.SlaveListener).EventLog.Log);
            Assert.AreEqual(".", ((EventLogTraceListener)listener.SlaveListener).EventLog.MachineName);
        }
コード例 #10
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);
        }
コード例 #11
0
        public void ListenerWillFallbackToTraceEntryToStringIfFormatterDoesNotExists()
        {
            LogEntry testEntry = new LogEntry("message", "cat1", 0, 0, TraceEventType.Error, "title", null);
            StringWriter writer = new StringWriter();
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, null);

            // need to go through the source to get a TraceEventCache
            LogSource source = new LogSource("notfromconfig", new[] { listener }, SourceLevels.All);
            source.TraceData(TraceEventType.Error, 1, testEntry);

            Assert.AreEqual(testEntry.ToString(), CommonUtil.GetLastEventLogEntryCustom());
        }
コード例 #12
0
        public void ListenerWillUseFormatterIfExists()
        {
            StringWriter writer = new StringWriter();
            FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, new TextFormatter("DUMMY{newline}DUMMY"));
            LogSource source = new LogSource("notfromconfig", SourceLevels.All);

            source.Listeners.Add(listener);
            LogEntry logEntry = CommonUtil.GetDefaultLogEntry();

            source.TraceData(TraceEventType.Error, 1, logEntry);
            Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", CommonUtil.GetLastEventLogEntryCustom());
        }
コード例 #13
0
		public void ListenerWillUseFormatterIfExists()
		{
			StringWriter writer = new StringWriter();
			FormattedEventLogTraceListener listener = new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName, CommonUtil.EventLogNameCustom, new TextFormatter("DUMMY{newline}DUMMY"));

			// need to go through the source to get a TraceEventCache
			LogSource source = new LogSource("notfromconfig", SourceLevels.All);
			source.Listeners.Add(listener);

			LogEntry logEntry = CommonUtil.GetDefaultLogEntry();
			source.TraceData(TraceEventType.Error, 1, logEntry);

			Assert.AreEqual("DUMMY" + Environment.NewLine + "DUMMY", CommonUtil.GetLastEventLogEntryCustom());
		}
コード例 #14
0
        public override TraceListener Assemble(IBuilderContext context, TraceListenerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            FormattedEventLogTraceListenerData castedObjectConfiguration
                = (FormattedEventLogTraceListenerData)objectConfiguration;
            ILogFormatter formatter
                = GetFormatter(context, castedObjectConfiguration.Formatter, configurationSource, reflectionCache);
            TraceListener createdObject
                = new FormattedEventLogTraceListener(
                      castedObjectConfiguration.Source,
                      castedObjectConfiguration.Log,
                      castedObjectConfiguration.MachineName,
                      formatter);

            return(createdObject);
        }
コード例 #15
0
        private static void ConfigureEventLogLogging(LoggingConfiguration config)
        {
            //  Create an event log Object
            // This maps to the appropriate log and ensure it exists
            var eventLog
                = new EventLog("Application", ".", "Enterprise Library Logging Sample");

            //  Create the listener
            var eventLogTraceListener
                = new FormattedEventLogTraceListener(eventLog);

            //  Tell the config to use this (Category = EventLog)
            config.AddLogSource("EventLog", SourceLevels.All, true)
            .AddTraceListener(eventLogTraceListener);
        }
コード例 #16
0
        private static LoggingConfiguration BuildLoggingConfig()
        {
            // Formatters
            TextFormatter formatter =
                new TextFormatter(
                    @"Timestamp: {timestamp}{newline}
Message: {message}{newline}Category: {category}{newline}
Priority: {priority}{newline}EventId: {eventid}{newline}
Severity: {severity}{newline}Title:{title}{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})}");

            // Listeners
            var flatFileTraceListener =
                new FlatFileTraceListener(
                    @"C:\Temp\Puzzler.log",
                    "----------------------------------------",
                    "----------------------------------------",
                    formatter);
            var eventLog =
                new EventLog("Application", ".",
                             "Enterprise Library Logging");
            var eventLogTraceListener = new
                                        FormattedEventLogTraceListener(eventLog);

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

            config.AddLogSource("General", SourceLevels.All, true)
            .AddTraceListener(eventLogTraceListener);
            config.LogSources["General"]
            .AddTraceListener(flatFileTraceListener);

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

            return(config);
        }
コード例 #17
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);
        }
コード例 #18
0
        public void CanCreateInstanceFromConfigurationFile()
        {
            LoggingSettings loggingSettings = new LoggingSettings();

            loggingSettings.Formatters.Add(new TextFormatterData("formatter", "foobar template"));
            loggingSettings.TraceListeners.Add(new FormattedEventLogTraceListenerData("listener", "unknown source", "log", "machine", "formatter"));

            TraceListener listener = TraceListenerCustomFactory.Instance.Create(context, "listener", CommonUtil.SaveSectionsAndGetConfigurationSource(loggingSettings), reflectionCache);

            Assert.IsNotNull(listener);
            Assert.AreEqual(listener.GetType(), typeof(FormattedEventLogTraceListener));
            FormattedEventLogTraceListener castedListener = (FormattedEventLogTraceListener)listener;

            Assert.IsNotNull(castedListener.Formatter);
            Assert.AreEqual("unknown source", ((EventLogTraceListener)castedListener.SlaveListener).EventLog.Source);
            Assert.AreEqual("log", ((EventLogTraceListener)castedListener.SlaveListener).EventLog.Log);
            Assert.AreEqual("machine", ((EventLogTraceListener)castedListener.SlaveListener).EventLog.MachineName);
            Assert.AreEqual(castedListener.Formatter.GetType(), typeof(TextFormatter));
            Assert.AreEqual("foobar template", ((TextFormatter)castedListener.Formatter).Template);
        }
コード例 #19
0
        public void CanWriteToEventLog()
        {
            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName,
                                                   CommonUtil.EventLogNameCustom,
                                                   FormattedEventLogTraceListener.DefaultMachineName,
                                                   new TextFormatter("{message}"));
            LogSource source = new LogSource("transient", SourceLevels.All);

            source.Listeners.Add(listener);
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            entry.Severity = TraceEventType.Error;
            CommonUtil.ResetEventLogCounterCustom();
            source.TraceData(entry.Severity, entry.EventId, entry);
            using (EventLog customLog = CommonUtil.GetCustomEventLog())
            {
                Assert.AreEqual(1, CommonUtil.EventLogEntryCountCustom());
                Assert.AreEqual(CommonUtil.MsgBody, customLog.Entries[customLog.Entries.Count - 1].Message);
            }
        }
コード例 #20
0
        public void CanCreateInstanceFromGivenConfiguration()
        {
            FormattedEventLogTraceListenerData listenerData = new FormattedEventLogTraceListenerData("listener", "unknown source", "formatter");

            MockLogObjectsHelper helper = new MockLogObjectsHelper();

            helper.loggingSettings.Formatters.Add(new TextFormatterData("formatter", "foobar template"));

            TraceListener listener = TraceListenerCustomFactory.Instance.Create(context, listenerData, helper.configurationSource, reflectionCache);

            Assert.IsNotNull(listener);
            Assert.AreEqual("listener", listener.Name);
            Assert.AreEqual(listener.GetType(), typeof(FormattedEventLogTraceListener));
            FormattedEventLogTraceListener castedListener = (FormattedEventLogTraceListener)listener;

            Assert.IsNotNull(castedListener.Formatter);
            Assert.AreEqual("unknown source", ((EventLogTraceListener)castedListener.SlaveListener).EventLog.Source);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultLogName, ((EventLogTraceListener)castedListener.SlaveListener).EventLog.Log);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultMachineName, ((EventLogTraceListener)castedListener.SlaveListener).EventLog.MachineName);
            Assert.AreEqual(castedListener.Formatter.GetType(), typeof(TextFormatter));
            Assert.AreEqual("foobar template", ((TextFormatter)castedListener.Formatter).Template);
        }
コード例 #21
0
        public void WillNotWriteToTheEventLogIfRequestIsFilteredOut()
        {
            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName,
                                                   CommonUtil.EventLogNameCustom,
                                                   FormattedEventLogTraceListener.DefaultMachineName,
                                                   new TextFormatter("{message}"));

            listener.Filter = new EventTypeFilter(SourceLevels.Critical);
            LogSource source = new LogSource("transient", SourceLevels.All);

            source.Listeners.Add(listener);
            LogEntry entry = CommonUtil.GetDefaultLogEntry();

            entry.Severity = TraceEventType.Error;
            CommonUtil.ResetEventLogCounterCustom();
            source.TraceData(entry.Severity, entry.EventId, entry);
            using (EventLog customLog = CommonUtil.GetCustomEventLog())
            {
                Assert.AreEqual(0, CommonUtil.EventLogEntryCountCustom());
            }
        }
コード例 #22
0
        public void EntryIsWrittenWithNoFormattingWhenUsingJsonFormatterWithFormattedEventLogTraceListener()
        {
            var eventLog = new EventLog(LoggingFixtureBase.EventLogName, ".", "Enterprise Library Logging");

            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(eventLog, new JsonLogFormatter());

            LoggingConfiguration loggingConfiguration = BuildProgrammaticConfigForTrace();

            loggingConfiguration.AddLogSource("notfromconfig", SourceLevels.All, true, listener);

            LogEntry logEntry = MsmqUtil.GetDefaultLogEntry();

            logEntry.Categories = new string[] { "notfromconfig" };

            this.writer = new LogWriter(loggingConfiguration);
            this.writer.Write(logEntry);

            EventLogEntry eventLogEntry = GetLastEventLogEntry();

            Assert.IsTrue(eventLogEntry.Message.IndexOf("\"Message\":\"My message body\",\"Categories\":[\"notfromconfig\"],\"Priority\":100,\"EventId\":1,\"Severity\":8,\"LoggedSeverity\":\"Information\",\"Title\":\"=== Header ===\",\"TimeStamp\":") != -1);
        }
コード例 #23
0
        public static ExceptionManager InicializarPoliticas()
        {
            TextFormatter formatterF = new TextFormatter("Timestamp:...");

            var flatFileTraceListener = new FlatFileTraceListener(@"c:\fumit.log");


            var eventLog = new EventLog("Application", ".", "Enterprise Library Logging");
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog);


            LoggingConfiguration conf = new LoggingConfiguration();

            conf.AddLogSource("General", System.Diagnostics.SourceLevels.All, true, flatFileTraceListener);
            conf.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(eventLogTraceListener);
            conf.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(flatFileTraceListener);

            LogWriter logWriter = new LogWriter(conf); //new LogWriterFactory().Create();

            //var v = new  RollingFlatFileTraceListener("",)
            //logWriter.Configure((A) => A.AddLogSource("General", new System.Diagnostics.ConsoleTraceListener(), eventLogTraceListener));


            policies.Add(new ExceptionPolicyDefinition(CrearActualizarEntidadesDesdeUI, new ExceptionPolicyEntry[] {
                new ExceptionPolicyEntry(typeof(System.Data.Entity.Validation.DbEntityValidationException), PostHandlingAction.None, new IExceptionHandler[] {
                    new NotificarUsuarioEFValidationExceptionHandler()
                }),
                new ExceptionPolicyEntry(typeof(Exception), PostHandlingAction.None, new IExceptionHandler[] {
                    new LoggingExceptionHandler("Error", 10, System.Diagnostics.TraceEventType.Error, "Ocurrió una excepción no controlada", 10, typeof(TextExceptionFormatter), logWriter),
                    new NotificarUsuarioMessageBoxExceptionHandler()
                })
                //,
                //new ExceptionPolicyEntry(typeof(ArgumentNullException),PostHandlingAction.None,new IExceptionHandler[]{
                //    new NotificarUsuarioMessageBoxExceptionHandler()
                //})
            }));

            return(new ExceptionManager(policies));
        }
        public void CanCreateInstanceFromGivenName()
        {
            FormattedEventLogTraceListenerData listenerData = new FormattedEventLogTraceListenerData("listener", "unknown source", "formatter");

            MockLogObjectsHelper helper = new MockLogObjectsHelper();

            helper.loggingSettings.Formatters.Add(new TextFormatterData("formatter", "foobar template"));
            helper.loggingSettings.TraceListeners.Add(listenerData);

            TraceListener listener = GetListener("listener\u200cimplementation", helper.configurationSource);

            Assert.IsNotNull(listener);
            Assert.AreEqual("listener\u200cimplementation", listener.Name);
            Assert.AreEqual(listener.GetType(), typeof(FormattedEventLogTraceListener));
            FormattedEventLogTraceListener castedListener = (FormattedEventLogTraceListener)listener;

            Assert.IsNotNull(castedListener.Formatter);
            Assert.AreEqual("unknown source", ((EventLogTraceListener)castedListener.InnerListener).EventLog.Source);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultLogName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.Log);
            Assert.AreEqual(FormattedEventLogTraceListener.DefaultMachineName, ((EventLogTraceListener)castedListener.InnerListener).EventLog.MachineName);
            Assert.AreEqual(castedListener.Formatter.GetType(), typeof(TextFormatter));
            Assert.AreEqual("foobar template", ((TextFormatter)castedListener.Formatter).Template);
        }
コード例 #25
0
        public void CanCreatePoliciesForFormattedEventLogTraceListener()
        {
            FormattedEventLogTraceListenerData listenerData
                = new FormattedEventLogTraceListenerData("listener", CommonUtil.EventLogSourceName, CommonUtil.EventLogName, "machine", "");

            listenerData.TraceOutputOptions = TraceOptions.Callstack | TraceOptions.ProcessId;
            listenerData.Filter             = SourceLevels.Error;
            loggingSettings.TraceListeners.Add(listenerData);

            container.AddExtension(new LoggingBlockExtension());

            FormattedEventLogTraceListener createdObject = (FormattedEventLogTraceListener)container.Resolve <TraceListener>("listener");

            Assert.IsNotNull(createdObject);
            Assert.AreEqual(listenerData.TraceOutputOptions, createdObject.TraceOutputOptions);
            Assert.IsNotNull(createdObject.Filter);
            Assert.IsInstanceOfType(createdObject.Filter, typeof(EventTypeFilter));
            Assert.AreEqual(listenerData.Filter, ((EventTypeFilter)createdObject.Filter).EventType);
            Assert.IsNull(createdObject.Formatter);
            Assert.AreEqual(CommonUtil.EventLogSourceName, ((EventLogTraceListener)createdObject.SlaveListener).EventLog.Source);
            Assert.AreEqual(CommonUtil.EventLogName, ((EventLogTraceListener)createdObject.SlaveListener).EventLog.Log);
            Assert.AreEqual("machine", ((EventLogTraceListener)createdObject.SlaveListener).EventLog.MachineName);
        }
コード例 #26
0
        protected void ShoutLoop()
        {
            // Configue a LogWriter to write to the Windows Event Log.
            var eventLog = new EventLog("Application", ".", "ShoutService");
            var eventLogTraceListener = new FormattedEventLogTraceListener(eventLog)
            {
                Filter = new SeverityFilter(new TraceEventType[] {
                    TraceEventType.Error, TraceEventType.Information, TraceEventType.Warning
                })
            };
            var config = new LoggingConfiguration();

            config.AddLogSource("All", SourceLevels.All, true)
            .AddTraceListener(eventLogTraceListener);
            // A using statement ensures the log gets flushed when this process exits.
            using (var logWriter = new LogWriter(config))
            {
                var shouter = new Shouter(logWriter);
                do
                {
                    shouter.Shout(cancellationTokenSource.Token);
                } while (!cancellationTokenSource.Token.IsCancellationRequested);
            }
        }
        public void CanWriteToEventLog()
        {
            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName,
                                                   CommonUtil.EventLogNameCustom,
                                                   FormattedEventLogTraceListener.DefaultMachineName,
                                                   new TextFormatter("{message}"));
            LogSource source = new LogSource("transient", SourceLevels.All);
            source.Listeners.Add(listener);

            LogEntry entry = CommonUtil.GetDefaultLogEntry();
            entry.Severity = TraceEventType.Error;

            CommonUtil.ResetEventLogCounterCustom();
            source.TraceData(entry.Severity, entry.EventId, entry);
            using (EventLog customLog = CommonUtil.GetCustomEventLog())
            {
                Assert.AreEqual(1, CommonUtil.EventLogEntryCountCustom());
                Assert.AreEqual(CommonUtil.MsgBody, customLog.Entries[customLog.Entries.Count - 1].Message);
            }
        }
        public void WillNotWriteToTheEventLogIfRequestIsFilteredOut()
        {
            FormattedEventLogTraceListener listener =
                new FormattedEventLogTraceListener(CommonUtil.EventLogSourceName,
                                                   CommonUtil.EventLogNameCustom,
                                                   FormattedEventLogTraceListener.DefaultMachineName,
                                                   new TextFormatter("{message}"));
            listener.Filter = new EventTypeFilter(SourceLevels.Critical);
            LogSource source = new LogSource("transient", SourceLevels.All);
            source.Listeners.Add(listener);

            LogEntry entry = CommonUtil.GetDefaultLogEntry();
            entry.Severity = TraceEventType.Error;

            CommonUtil.ResetEventLogCounterCustom();
            source.TraceData(entry.Severity, entry.EventId, entry);
            using (EventLog customLog = CommonUtil.GetCustomEventLog())
            {
                Assert.AreEqual(0, CommonUtil.EventLogEntryCountCustom());
            }
        }
        public void ShouldThrowArgumentNull()
        {
            string name = null;

            var listener = new FormattedEventLogTraceListener(name);
        }