/// <summary> /// Creates an Enterprise Library exception handler that utilizes /// a rolling flat file trace listener to write to log files. /// </summary> /// <param name="Name">The name of the <see cref="EnterpriseExceptionLogging.LoggingExceptionHandler"/>.</param> /// <param name="FilePath">Location of log file. If this is not provided, <see cref="DEFAULT_CONFIG_FILE_PATH"/> is used to try and retrieve file path from Web.config file.</param> /// <param name="FileName">Name of log file. If this is not provided, "default_rolling.log" is used.</param> /// <param name="Interval">How often a new file should be created.</param> /// <param name="Save">States whether or not to store the handler in memory.</param> /// <returns></returns> private EnterpriseExceptionLogging.LoggingExceptionHandler CreateTempLogger(string Name = "", string FilePath = "", string FileName = "", LoggingInterval Interval = LoggingInterval.Day, /*bool ForceCreate = false,*/ bool Save = true) { string default_file_path = FilePath; if (string.IsNullOrEmpty(default_file_path)) { try { default_file_path = ConfigurationManager.AppSettings[DEFAULT_CONFIG_FILE_PATH]; } catch (ConfigurationErrorsException) { } } if (string.IsNullOrEmpty(default_file_path)) { return(default(EnterpriseExceptionLogging.LoggingExceptionHandler)); } if (string.IsNullOrEmpty(Name)) { Name = default_file_path + (!string.IsNullOrEmpty(FileName) ? FileName : "default_rolling.log"); } string FullName = default_file_path + (!string.IsNullOrEmpty(FileName) ? FileName : "default_rolling.log"); if (!FullName.EndsWith(".log")) { FullName += ".log"; } if (_temp_enterprise_loggers.ContainsKey(Name)) { return(_temp_enterprise_loggers[Name]); } EnterpriseExceptionLogging.LoggingExceptionHandler handler = default(EnterpriseExceptionLogging.LoggingExceptionHandler); try { //EnterpriseLogging.LogWriter writer = default(EnterpriseLogging.LogWriter); //using (EnterpriseLogging.LogWriterFactory factory = new EnterpriseLogging.LogWriterFactory()) //using (writer = factory.CreateDefault()) //{ // if (writer == null) // return handler; // if (!ForceCreate && writer.TraceSources.Count > 0) // { // // there already exists listeners in web config that we do // // not want to overwrite, so there is no need to create a // // default listener // return handler; // } //} // create formatter for rolling log file EnterpriseLogging.Formatters.TextFormatter formatter = new EnterpriseLogging.Formatters.TextFormatter( template: "GMT Timestamp: {timestamp(MM/dd/yyyy HH:mm:ss)}\n" + "Local Timestamp: {timestamp(local:hh:mm:ss:tt)}\n" + "Message: {message}\n" + "Category: {category}\n" + "Priority: {priority}\n" + "EventId: {eventid}\n" + "Severity: {severity}\n" + "Title:{title}\n" + "Machine: {machine}\n" + "Application Domain: {appDomain}\n" + "Process Id: {processId}\n" + "Process Name: {processName}\n" + "Win32 Thread Id: {win32ThreadId}\n" + "Thread Name: {threadName}\n" + "Extended Properties: {dictionary({key} - {value})}\n"); EnterpriseLogging.TraceListeners.RollInterval interval; if (!Enum.TryParse(Enum.GetName(typeof(LoggingInterval), Interval), true, out interval)) { interval = EnterpriseLogging.TraceListeners.RollInterval.Day; } // create trace listener for exception handler EnterpriseLogging.TraceListeners.RollingFlatFileTraceListener listener = new EnterpriseLogging.TraceListeners.RollingFlatFileTraceListener( fileName: FullName, header: "----------------------------------------", footer: "----------------------------------------", formatter: formatter, rollSizeKB: 0, timeStampPattern: "yyyy-MM-dd", rollFileExistsBehavior: EnterpriseLogging.TraceListeners.RollFileExistsBehavior.Overwrite, rollInterval: interval); listener.TraceOutputOptions = TraceOptions.None; listener.Name = "Default Rolling Flat File Trace Listener"; // add trace listener to the log writer's sources //if (OverwriteTraceListeners) // writer.TraceSources.Clear(); //if (writer.TraceSources.ContainsKey("General")) // writer.TraceSources["General"].Listeners.Add(listener); //else // writer.TraceSources.Add( // key: "General", // value: new EnterpriseLogging.LogSource( // name: "Default Enterprise Logger", // level: SourceLevels.All, // traceListeners: new List<TraceListener>(1) { listener }, // autoFlush: true // )); // create the exception handler that will handle the exceptions //handler = new EnterpriseExceptionLogging.LoggingExceptionHandler( // logCategory: "General", // eventId: 100, // severity: TraceEventType.Error, // title: "Default Enterprise Library Exception Handler", // priority: 0, // formatterType: typeof(TextExceptionFormatter), // writer: writer); //List<EnterpriseLogging.Filters.LogFilter> filters = new List<EnterpriseLogging.Filters.LogFilter>(); //EnterpriseLogging.LogSource main_source = new EnterpriseLogging.LogSource( // name: "Default Enterprise Logger", // level: SourceLevels.All, // traceListeners: new List<TraceListener>(1) { listener }, // autoFlush: true // ); //IDictionary<string, EnterpriseLogging.LogSource> trace_sources = new Dictionary<string, EnterpriseLogging.LogSource>(); //trace_sources.Add("General", main_source); //EnterpriseLogging.LogWriterStructureHolder holder = new EnterpriseLogging.LogWriterStructureHolder(filters, trace_sources, main_source, main_source, main_source, "General", true, true, false); //EnterpriseLogging.LogWriterImpl writer = new EnterpriseLogging.LogWriterImpl(holder, new EnterpriseLogging.Instrumentation.LoggingInstrumentationProvider(false, true, "EnhancedPartnerCenter"), new EnterpriseLogging.LoggingUpdateCoordinator(new Microsoft.Practices.EnterpriseLibrary.Common.Configuration.ContainerModel.ConfigurationChangeEventSourceImpl())); //handler = new EnterpriseExceptionLogging.LoggingExceptionHandler( // logCategory: "General", // eventId: 100, // severity: TraceEventType.Error, // title: "Default Enterprise Library Exception Handler", // priority: 0, // formatterType: typeof(TextExceptionFormatter), // writer: writer); //if (Save) // _temp_enterprise_loggers.Add(Name, handler); // Try to fix this to work.. List <EnterpriseLogging.Filters.LogFilter> filters = new List <EnterpriseLogging.Filters.LogFilter>(); EnterpriseLogging.LogSource main_source = new EnterpriseLogging.LogSource( name: "Default Enterprise Logger", level: SourceLevels.All, traceListeners: new List <TraceListener>(1) { listener }, autoFlush: true ); IDictionary <string, EnterpriseLogging.LogSource> trace_sources = new Dictionary <string, EnterpriseLogging.LogSource>(); trace_sources.Add("General", main_source); EnterpriseLogging.LogWriterFactory factory_writer = new EnterpriseLogging.LogWriterFactory(); EnterpriseLogging.LogWriterStructureHolder holder = new EnterpriseLogging.LogWriterStructureHolder(filters, trace_sources, main_source, main_source, main_source, "General", true, true, false); EnterpriseLogging.LogWriter writer = factory_writer.Create(); // this is where chiz hit the fan writer.Configure(new Action <EnterpriseLogging.LoggingConfiguration>((EnterpriseLogging.LoggingConfiguration lc) => { lc.AddLogSource(""); })); handler = new EnterpriseExceptionLogging.LoggingExceptionHandler( logCategory: "General", eventId: 100, severity: TraceEventType.Error, title: "Default Enterprise Library Exception Handler", priority: 0, formatterType: typeof(TextExceptionFormatter), writer: writer); } catch (Exception) { handler = default(EnterpriseExceptionLogging.LoggingExceptionHandler); } return(handler); }
/// <summary> /// Logs the provided <paramref name="Exception"/> based on the <paramref name="ErrorSeverity"/>. /// If <paramref name="UseLoggingConfig"/> is true, the logging configuration will /// attempt to be used to log the <paramref name="Exception"/>. If the <paramref name="Exception"/> /// could not be logged because the policy name in the logging configuration is incorrect, /// that error will be logged separately to a text file. /// </summary> /// <param name="Exception">The exception to log.</param> /// <param name="ErrorSeverity">The severity level of the exception.</param> /// <param name="UseLoggingConfig">States whether or not to use the custom logging configuration.</param> private void WriteToEnterpriseLibraryFile(Exception Exception, ErrorSeverity ErrorSeverity, bool UseLoggingConfig = true) { // get all elements with similar severity from web config if UseLoggingConfig is true, // otherwise make it an empty list to skip the foreach loop string LogFilePath = string.Empty; List <LoggingElement> LoggingElements = (UseLoggingConfig) ? GetLoggingElementsByPropertyValue("Severity", ErrorSeverity) : new List <LoggingElement>(0); // variables to track whether or not the exception was logged int handled_count = 0; bool handled = false; // loop through each configuration and log the exception to the corresponding files foreach (LoggingElement LoggingElement in LoggingElements) { // but remember, only log to files if their logging type // is designated as EnterpriseLibrary if (!LoggingElement.LoggingType.HasFlag(LoggingType.EnterpriseLibrary)) { continue; } // initially, set handled to false to denote that the exception was not logged handled = false; try { // if a policy is provided.. if (!string.IsNullOrEmpty(LoggingElement.EnterprisePolicy)) { ExceptionPolicy.HandleException(Exception, LoggingElement.EnterprisePolicy); handled_count++; } // if a file path for the log file was provided.. else if (!string.IsNullOrEmpty(LoggingElement.LogFilePath)) { // for this situation, we will make a new handler for a different path // instead of modifying the default // create new handler if it does not exist, otherwise retrieve handler from _temp_enterprise_loggers EnterpriseExceptionLogging.LoggingExceptionHandler temp_handler = CreateTempLogger( FilePath: LoggingElement.LogFilePath, FileName: LoggingElement.LogFileName + (LoggingElement.LogFileName.EndsWith(".log") ? "" : ".log"), Interval: LoggingElement.Interval /*, * ForceCreate: true*/); // handle exception if (temp_handler != null) { temp_handler.HandleException(Exception, Guid.NewGuid()); handled_count++; } } handled = true; } catch (Microsoft.Practices.ServiceLocation.ActivationException aex) { // HandleException failed - this occurs when a policy is not present or the exception could not be handled properly Log(aex, LoggingType.TextFile, ErrorSeverity.Warning); } // if the exception failed to be logged because the policy was incorrect.. if (!handled) { // if the default logger was successfully created.. if (_temp_enterprise_loggers.ContainsKey(DEFAULT_ENTERPRISE_LOGGER_NAME)) { // try to write to default logger try { _temp_enterprise_loggers[DEFAULT_ENTERPRISE_LOGGER_NAME].HandleException(Exception, Guid.NewGuid()); handled_count++; } catch (Microsoft.Practices.ServiceLocation.ActivationException aex) { // HandleException failed - this occurs when a policy is not present or the exception could not be handled properly Log(aex, LoggingType.TextFile, ErrorSeverity.Warning); } } else { // try to log using default policy name try { ExceptionPolicy.HandleException(Exception, DEFAULT_EXCEPTION_POLICY); handled_count++; } catch (Microsoft.Practices.ServiceLocation.ActivationException) { // HandleException failed - this occurs when a policy is not present or the exception could not be handled properly // do not try to log this, this is the last resort } } } } // if no elements are found with the same severity that was provided or // the policies were not found, try to use default policy name if (handled_count == 0) { // if the default logger was created (i.e. there are no policies in config) if (_temp_enterprise_loggers.ContainsKey(DEFAULT_ENTERPRISE_LOGGER_NAME)) { // try to write to default logger try { _temp_enterprise_loggers[DEFAULT_ENTERPRISE_LOGGER_NAME].HandleException(Exception, Guid.NewGuid()); } catch (Microsoft.Practices.ServiceLocation.ActivationException aex) { // HandleException failed - this occurs when a policy is not present or the exception could not be handled properly Log(aex, LoggingType.TextFile, ErrorSeverity.Warning); } } else { // try to log using default policy name // if that fails, there is no hope.. try { ExceptionPolicy.HandleException(Exception, DEFAULT_EXCEPTION_POLICY); } catch (Microsoft.Practices.ServiceLocation.ActivationException) { // HandleException failed - this occurs when a policy is not present or the exception could not be handled properly // do not try to log this, this is the last resort } } } }