Пример #1
0
        private LogWriter CreateFlatFileLogWriter(FileStream logFile)
        {
            // This is our message template for any Sink you add below in our case the Windows Event Log
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp}{newline}" +
                                                        "Message: {message}{newline}" +
                                                        "Machine: {machine}{newline}{newline}{newline}");
            
            LogSource emptyTraceSource = new LogSource("none");
            LogSource errorsTraceSource = new LogSource(CONS_ERROR_CATEGORY, System.Diagnostics.SourceLevels.All);

            // Create for all Errors a Listener which writes the messages to the Windows Event Log
            // with the Event Log Source Property "Code Source". The message format is specified by
            // the TextFormatter which is in our case the template above.
            errorsTraceSource.Listeners.Add(new FlatFileTraceListener(logFile, formatter));
            IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();

            // Add to Category "Error" our EventLog Listener with the corresponding category in it.
            traceSources.Add(errorsTraceSource.Name, errorsTraceSource);

            return new LogWriter(new ILogFilter[0], // ICollection<ILogFilter> filters
                              traceSources,        // IDictionary<string, LogSource> traceSources
                              emptyTraceSource,    // LogSource allEventsTraceSource
                              emptyTraceSource,    // LogSource notProcessedTraceSource
                              errorsTraceSource,    // LogSource errorsTraceSource
                              CONS_ERROR_CATEGORY,        // string defaultCategory
                              false,                // bool tracingEnabled
                              true);                // bool logWarningsWhenNoCategoriesMatch
        }
        /// <summary>
        /// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
        /// Initializes a new instance of the <see cref="LogWriterStructureHolder"/> class.
        /// </summary>
        /// <param name="filters">The collection of filters to use when processing an entry.</param>
        /// <param name="traceSources">The trace sources to dispatch entries to.</param>
        /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
        /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
        /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
        /// <param name="defaultCategory">The default category to set when entry categories list of a log entry is empty.</param>
        /// <param name="tracingEnabled">The tracing status.</param>
        /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
        /// <param name="revertImpersonation">true if impersonation should be reverted while logging.</param>
        public LogWriterStructureHolder(
            IEnumerable<ILogFilter> filters,
            IDictionary<string, LogSource> traceSources,
            LogSource allEventsTraceSource,
            LogSource notProcessedTraceSource,
            LogSource errorsTraceSource,
            string defaultCategory,
            bool tracingEnabled,
            bool logWarningsWhenNoCategoriesMatch,
            bool revertImpersonation)
        {
            if (filters == null)
                throw new ArgumentNullException("filters");
            if (traceSources == null)
                throw new ArgumentNullException("traceSources");
            if (errorsTraceSource == null)
                throw new ArgumentNullException("errorsTraceSource");

            this.filters = filters;
            this.traceSources = traceSources;
            this.allEventsTraceSource = allEventsTraceSource;
            this.notProcessedTraceSource = notProcessedTraceSource;
            this.errorsTraceSource = errorsTraceSource;
            this.defaultCategory = defaultCategory;
            this.tracingEnabled = tracingEnabled;
            this.logWarningsWhenNoCategoriesMatch = logWarningsWhenNoCategoriesMatch;
            this.revertImpersonation = revertImpersonation;
        }
Пример #3
0
        static LogService()
        {
            var formatter = new TextFormatter
                ("Timestamp: {timestamp}{newline}" +
                 "Message: {message}{newline}" +
                 "Category: {category}{newline}");

            //Create the Trace listeners
            var logFileListener = new FlatFileTraceListener(@"C:\temp\temp.log", "",
                                                            "", formatter);

            //Add the trace listeners to the source
            var mainLogSource =
                new LogSource("MainLogSource", SourceLevels.All);
            mainLogSource.Listeners.Add(logFileListener);

            var nonExistantLogSource = new LogSource("Empty");

            IDictionary<string, LogSource> traceSources =
                new Dictionary<string, LogSource>
                    {{"Info", mainLogSource}, {"Warning", mainLogSource}, {"Error", mainLogSource}};

            Writer = new LogWriterImpl(new ILogFilter[0],
                                       traceSources,
                                       nonExistantLogSource,
                                       nonExistantLogSource,
                                       mainLogSource,
                                       "Info",
                                       false,
                                       true);
        }
Пример #4
0
        public DynamicELLogger(string logRoot, IEnumerable<string> applications)
        {
            string[] categories = new string[] { "Info", "Error", "Debug", "Perf" };

            LoggingSettings loggingSetting = LoggingSettings.GetLoggingSettings(ConfigurationSourceFactory.Create());

            Dictionary<string, TextFormatter> formatters = new Dictionary<string, TextFormatter>(categories.Count(), StringComparer.OrdinalIgnoreCase);

            foreach (string cate in categories)
            {
                var formatData = loggingSetting.Formatters.Where(f => f.Name.Equals(cate, StringComparison.OrdinalIgnoreCase)).SingleOrDefault() as TextFormatterData;

                if (formatData == null)
                    throw new Exception(string.Format("Missing logging formatter \"{0}\"", cate));

                TextFormatter formatter = new TextFormatter(formatData.Template);
                formatters[cate] = formatter;
            }

            string baseLogPath = Path.Combine(logRoot, "{0}.log");
            string logPath = Path.Combine(logRoot, "{0}\\{1}.log");

            List<LogSource> logSources = new List<LogSource>();

            foreach (var cate in categories)
            {
                logSources.Add(new LogSource(cate, new List<TraceListener>
                    {
                        new RollingFlatFileTraceListener(string.Format(baseLogPath, cate), "", "", formatters[cate], 0, "yyyyMMdd", RollFileExistsBehavior.Overwrite, RollInterval.Day)
                    }, SourceLevels.All));
            }

            foreach (var app in applications)
            {
                foreach (var cate in categories)
                {
                    logSources.Add(new LogSource(app + "." + cate, new List<TraceListener>
                        {
                            new RollingFlatFileTraceListener(string.Format(logPath, app, cate), "", "", formatters[cate], 0, "yyyyMMdd", RollFileExistsBehavior.Overwrite, RollInterval.Day)
                        }, SourceLevels.All));
                }
            }

            var nonExistantLog = new LogSource("Empty");

            m_Writer = new LogWriter(new ILogFilter[0], logSources, nonExistantLog, categories[0]);
        }
Пример #5
0
        public LogSource Create(IBuilderContext context, TraceSourceData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache, TraceListenerCustomFactory.TraceListenerCache traceListenersCache)
        {
            List <TraceListener> traceListeners = new List <TraceListener>(objectConfiguration.TraceListeners.Count);

            foreach (TraceListenerReferenceData traceListenerReference in objectConfiguration.TraceListeners)
            {
                TraceListener traceListener
                    = TraceListenerCustomFactory.Instance.Create(context, traceListenerReference.Name, configurationSource, reflectionCache, traceListenersCache);
                traceListeners.Add(traceListener);
            }
            LogSource createdObject
                = new LogSource(objectConfiguration.Name, traceListeners, objectConfiguration.DefaultLevel, objectConfiguration.AutoFlush);
            InstrumentationAttachmentStrategy instrumentationAttacher = new InstrumentationAttachmentStrategy();

            instrumentationAttacher.AttachInstrumentation(createdObject, configurationSource, reflectionCache);
            return(createdObject);
        }
Пример #6
0
Файл: Logger.cs Проект: mnisl/OD
		/// <summary>
		/// Static constructor
		/// </summary>
		static Logger() {
			string LogFile = ConfigurationManager.AppSettings["LogFile"].ToString();// a static constructor works because changing the web.config restarts the appliaction.
			// this defaults to the namespace WebForms even when used in another application so it's not used
			//string LogFile=Properties.Settings.Default.LogFile;

			if(ConfigurationManager.AppSettings["LogErr"].ToString().ToLower()=="yes") {
				LogErr=true;
			}
			if(ConfigurationManager.AppSettings["LogInfo"].ToString().ToLower()=="yes") {
				LogInfo=true;
			}

			// formatter
			TextFormatter formatter = new TextFormatter("[{timestamp(local)}] [{machine}] {category}  \t: {message}");

			// listeners
			FlatFileTraceListener logFileListener=new FlatFileTraceListener(LogFile,"","",formatter);
			RollingFlatFileTraceListener rollingFlatFileListener=new RollingFlatFileTraceListener(LogFile,"","",formatter,1000,"yyyy-MM-dd",RollFileExistsBehavior.Increment,RollInterval.Day);
			//uncomment if an event log is needed
			//FormattedEventLogTraceListener logEventListener = new FormattedEventLogTraceListener("Enterprise Library Logging",formatter);

			// Sources
			LogSource mainLogSource = new LogSource("MainLogSource",SourceLevels.All);
			//mainLogSource.Listeners.Add(logFileListener);//regular flat file
			mainLogSource.Listeners.Add(rollingFlatFileListener);
			//uncomment if an event log is needed
			//LogSource errorLogSource = new LogSource("ErrorLogSource",SourceLevels.Error);
			//errorLogSource.Listeners.Add(logEventListener);

			// empty source
			LogSource nonExistantLogSource = new LogSource("Empty");//non matching category.

			// trace sources
			IDictionary<string,LogSource> traceSources = new Dictionary<string,LogSource>();
			//traceSources.Add("Error",errorLogSource);//uncomment if an event log is needed
			traceSources.Add("Warning",mainLogSource);
			traceSources.Add("Information",mainLogSource);


			// log writer
			writer = new LogWriter(new ILogFilter[0],traceSources,mainLogSource,nonExistantLogSource,
				mainLogSource,"Error",false,true);
			//writer = new LogWriter(new ILogFilter[0],traceSources,mainLogSource,nonExistantLogSource,
			//errorLogSource,"Error",false,true);//uncomment if 'internal' error are to be logged to an event log is needed
		}
 /// <summary>
 /// Initializes a new instance of the <see cref="LogWriter"/> class.
 /// </summary>
 /// <param name="filters">The collection of filters to use when processing an entry.</param>
 /// <param name="traceSources">The trace sources to dispatch entries to.</param>
 /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
 /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
 /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
 /// <param name="defaultCategory">The default category to set when entry categories list is empty.</param>
 /// <param name="tracingEnabled">The tracing status.</param>
 /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
 public LogWriter(ICollection <ILogFilter> filters,
                  ICollection <LogSource> traceSources,
                  LogSource allEventsTraceSource,
                  LogSource notProcessedTraceSource,
                  LogSource errorsTraceSource,
                  string defaultCategory,
                  bool tracingEnabled,
                  bool logWarningsWhenNoCategoriesMatch)
     : this(filters,
            CreateTraceSourcesDictionary(traceSources),
            allEventsTraceSource,
            notProcessedTraceSource,
            errorsTraceSource,
            defaultCategory,
            tracingEnabled,
            logWarningsWhenNoCategoriesMatch)
 {
 }
Пример #8
0
		private LogWriter CreateEventLogWriter()
		{
			// This is our message template for any Sink you add below in our case the Windows Event Log
			TextFormatter formatter = new TextFormatter("Timestamp: {timestamp}{newline}" +
														"Message: {message}{newline}" +
														"Category: {category}{newline}" +
														"Priority: {priority}{newline}" +
														"Severity: {severity}{newline}" +
														"Title:{title}{newline}" +
														"Application Domain: {appDomain}{newline} " +
														"Process Id: {processId}{newline}" +
														"Process Name: {processName}{newline}" +
														"Win32 Thread Id: {win32ThreadId}{newline}" +
														"Thread Name: {threadName}{newline}" +
														"Extended Properties: {dictionary({key} - {value})}{newline}");

			LogSource emptyTraceSource = new LogSource("none");
			LogSource errorsTraceSource = new LogSource(CONS_ERROR_CATEGORY, System.Diagnostics.SourceLevels.All);

			// Create for all Errors a Listener which writes the messages to the Windows Event Log
			// with the Event Log Source Property "Code Source". The message format is specified by
			// the TextFormatter which is in our case the template above.
			if (!EventLog.SourceExists(LoggingConstants.CONS_LOG_SOURCE))
				EventLog.CreateEventSource(LoggingConstants.CONS_LOG_SOURCE, LoggingConstants.CONS_LOG_NAME);

			EventLog eventLog = new EventLog();
			eventLog.Source = LoggingConstants.CONS_LOG_SOURCE;
			eventLog.Log = LoggingConstants.CONS_LOG_NAME;

			errorsTraceSource.Listeners.Add(new FormattedEventLogTraceListener(eventLog, formatter));
			IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();

			// Add to Category "Error" our EventLog Listener with the corresponding category in it.
			traceSources.Add(errorsTraceSource.Name, errorsTraceSource);

			return new LogWriter(new ILogFilter[0], // ICollection<ILogFilter> filters
							  traceSources,        // IDictionary<string, LogSource> traceSources
							  emptyTraceSource,    // LogSource allEventsTraceSource
							  emptyTraceSource,    // LogSource notProcessedTraceSource
							  errorsTraceSource,    // LogSource errorsTraceSource
							  CONS_ERROR_CATEGORY,        // string defaultCategory
							  false,                // bool tracingEnabled
							  true);                // bool logWarningsWhenNoCategoriesMatch
		}
Пример #9
0
        /// <summary>
        /// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
        /// Builds a <see cref="LogWriterStructureHolder"/> described by the <see cref="LoggingSettings"/> configuration section.
        /// </summary>
        /// <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
        /// <param name="name">The name of the instance to build. It is part of the <see cref="ICustomFactory.CreateObject(IBuilderContext, string, IConfigurationSource, ConfigurationReflectionCache)"/> method, but it is not used in this implementation.</param>
        /// <param name="configurationSource">The source for configuration objects.</param>
        /// <param name="reflectionCache">The cache to use retrieving reflection information.</param>
        /// <returns>A fully initialized instance of <see cref="LogWriterStructureHolder"/>.</returns>
        public object CreateObject(IBuilderContext context, string name, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            LoggingSettings loggingSettings = LoggingSettings.GetLoggingSettings(configurationSource);

            ValidateLoggingSettings(loggingSettings);

            TraceListenerCustomFactory.TraceListenerCache traceListenerCache
                = TraceListenerCustomFactory.CreateTraceListenerCache(loggingSettings.TraceListeners.Count);

            ICollection <ILogFilter> logFilters = new List <ILogFilter>();

            foreach (LogFilterData logFilterData in loggingSettings.LogFilters)
            {
                logFilters.Add(LogFilterCustomFactory.Instance.Create(context, logFilterData, configurationSource, reflectionCache));
            }

            IDictionary <string, LogSource> traceSources = new Dictionary <string, LogSource>();

            foreach (TraceSourceData traceSourceData in loggingSettings.TraceSources)
            {
                traceSources.Add(traceSourceData.Name, LogSourceCustomFactory.Instance.Create(context, traceSourceData, configurationSource, reflectionCache, traceListenerCache));
            }

            LogSource allEventsTraceSource
                = LogSourceCustomFactory.Instance.Create(context, loggingSettings.SpecialTraceSources.AllEventsTraceSource, configurationSource, reflectionCache, traceListenerCache);
            LogSource notProcessedTraceSource
                = LogSourceCustomFactory.Instance.Create(context, loggingSettings.SpecialTraceSources.NotProcessedTraceSource, configurationSource, reflectionCache, traceListenerCache);
            LogSource errorsTraceSource
                = LogSourceCustomFactory.Instance.Create(context, loggingSettings.SpecialTraceSources.ErrorsTraceSource, configurationSource, reflectionCache, traceListenerCache);

            LogWriterStructureHolder createdObject
                = new LogWriterStructureHolder(
                      logFilters,
                      traceSources,
                      allEventsTraceSource,
                      notProcessedTraceSource,
                      errorsTraceSource,
                      loggingSettings.DefaultCategory,
                      loggingSettings.TracingEnabled,
                      loggingSettings.LogWarningWhenNoCategoriesMatch);

            return(createdObject);
        }
Пример #10
0
        /// <summary>
        /// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
        /// Builds a <see cref="LogSource"/> based on an instance of <see cref="TraceSourceData"/>.
        /// </summary>
        /// <param name="context">The <see cref="IBuilderContext"/> that represents the current building process.</param>
        /// <param name="objectConfiguration">The configuration object that describes the object to build.</param>
        /// <param name="configurationSource">The source for configuration objects.</param>
        /// <param name="reflectionCache">The cache to use retrieving reflection information.</param>
        /// <param name="traceListenersCache">The cache of already built trace listeners, used to share trace listeners across <see cref="LogSource"/> instances.</param>
        /// <returns>A fully initialized instance of <see cref="LogSource"/>.</returns>
        public LogSource Create(IBuilderContext context, TraceSourceData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache, TraceListenerCustomFactory.TraceListenerCache traceListenersCache)
        {
            List<TraceListener> traceListeners = new List<TraceListener>(objectConfiguration.TraceListeners.Count);

            foreach (TraceListenerReferenceData traceListenerReference in objectConfiguration.TraceListeners)
            {
                TraceListener traceListener
                    = TraceListenerCustomFactory.Instance.Create(context, traceListenerReference.Name, configurationSource, reflectionCache, traceListenersCache);

                traceListeners.Add(traceListener);
            }

            LogSource createdObject
                = new LogSource(objectConfiguration.Name, traceListeners, objectConfiguration.DefaultLevel);

            InstrumentationAttachmentStrategy instrumentationAttacher = new InstrumentationAttachmentStrategy();
            instrumentationAttacher.AttachInstrumentation(createdObject, configurationSource, reflectionCache);

            return createdObject;
        }
Пример #11
0
        public static void InitializeLogManager()
        {
            if (formatter == null)
            {
                formatter = new TextFormatter()
                {
                    Template = " ------------------------------------------------------{newline}Timestamp:{timestamp}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}Title:{title}{newline}Machine: {localMachine}{newline}App Domain: {localAppDomain}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}-----------------------------------------)}",
                };
            }

            if (flatFileTraceListener == null)
            {
                flatFileTraceListener = new FlatFileTraceListener(formatter) { };
            }

            if (logSource == null)
            {
                logSource = new LogSource("Logging", new List<TraceListener>() { flatFileTraceListener }, SourceLevels.Information);
            }
        }
Пример #12
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogWriterImpl"/> class.
 /// </summary>
 /// <param name="filters">The collection of filters to use when processing an entry.</param>
 /// <param name="traceSources">The trace sources to dispatch entries to.</param>
 /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
 /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
 /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
 /// <param name="defaultCategory">The default category to set when entry categories list of a log entry is empty.</param>
 /// <param name="tracingEnabled">The tracing status.</param>
 /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
 public LogWriterImpl(
     IEnumerable <ILogFilter> filters,
     IDictionary <string, LogSource> traceSources,
     LogSource allEventsTraceSource,
     LogSource notProcessedTraceSource,
     LogSource errorsTraceSource,
     string defaultCategory,
     bool tracingEnabled,
     bool logWarningsWhenNoCategoriesMatch)
     : this(
         filters,
         traceSources,
         allEventsTraceSource,
         notProcessedTraceSource,
         errorsTraceSource,
         defaultCategory,
         tracingEnabled,
         logWarningsWhenNoCategoriesMatch,
         true)
 {
 }
Пример #13
0
 /// <summary>
 /// Initializes a new instance of the <see cref="LogWriterImpl"/> class.
 /// </summary>
 /// <param name="filters">The collection of filters to use when processing an entry.</param>
 /// <param name="traceSources">The trace sources to dispatch entries to.</param>
 /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
 /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
 /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
 /// <param name="defaultCategory">The default category to set when entry categories list is empty.</param>
 /// <param name="tracingEnabled">The tracing status.</param>
 /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
 /// <param name="instrumentationProvider">The instrumentation provider to use.</param>
 public LogWriterImpl(IEnumerable <ILogFilter> filters,
                      IEnumerable <LogSource> traceSources,
                      LogSource allEventsTraceSource,
                      LogSource notProcessedTraceSource,
                      LogSource errorsTraceSource,
                      string defaultCategory,
                      bool tracingEnabled,
                      bool logWarningsWhenNoCategoriesMatch,
                      ILoggingInstrumentationProvider instrumentationProvider)
     : this(filters,
            CreateTraceSourcesDictionary(traceSources),
            allEventsTraceSource,
            notProcessedTraceSource,
            errorsTraceSource,
            defaultCategory,
            tracingEnabled,
            logWarningsWhenNoCategoriesMatch,
            true,
            instrumentationProvider)
 {
 }
Пример #14
0
 static LogWriterStructureHolder CreateStructureHolder(
     ICollection <ILogFilter> filters,
     IDictionary <string, LogSource> traceSources,
     LogSource allEventsTraceSource,
     LogSource notProcessedTraceSource,
     LogSource errorsTraceSource,
     string defaultCategory,
     bool tracingEnabled,
     bool logWarningsWhenNoCategoriesMatch,
     bool revertImpersonation)
 {
     return(new LogWriterStructureHolder(
                filters,
                traceSources,
                allEventsTraceSource,
                notProcessedTraceSource,
                errorsTraceSource,
                defaultCategory,
                tracingEnabled,
                logWarningsWhenNoCategoriesMatch,
                revertImpersonation));
 }
Пример #15
0
 /// <summary>
 /// This constructor supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
 /// Initializes a new instance of the <see cref="LogWriterStructureHolder"/> class.
 /// </summary>
 /// <param name="filters">The collection of filters to use when processing an entry.</param>
 /// <param name="traceSourceNames">Names of the trace sources to dispatch entries to.</param>
 /// <param name="traceSources">The trace sources to dispatch entries to.</param>
 /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
 /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
 /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
 /// <param name="defaultCategory">The default category to set when entry categories list of a log entry is empty.</param>
 /// <param name="tracingEnabled">The tracing status.</param>
 /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
 /// <param name="revertImpersonation">true if impersonation should be reverted while logging.</param>
 public LogWriterStructureHolder(
     IEnumerable <ILogFilter> filters,
     IEnumerable <string> traceSourceNames,
     IEnumerable <LogSource> traceSources,
     LogSource allEventsTraceSource,
     LogSource notProcessedTraceSource,
     LogSource errorsTraceSource,
     string defaultCategory,
     bool tracingEnabled,
     bool logWarningsWhenNoCategoriesMatch,
     bool revertImpersonation)
     : this(
         filters,
         traceSourceNames.ToDictionary(traceSources),
         allEventsTraceSource,
         notProcessedTraceSource,
         errorsTraceSource,
         defaultCategory,
         tracingEnabled,
         logWarningsWhenNoCategoriesMatch,
         revertImpersonation)
 {
 }
        private void ReportExceptionDuringTracing(Exception exception, LogEntry log, LogSource traceSource)
        {
            try
            {
                NameValueCollection additionalInfo = new NameValueCollection();
                additionalInfo.Add(ExceptionFormatter.Header,
                                   string.Format(Resources.Culture, Resources.TraceSourceFailed, traceSource.Name));
                additionalInfo.Add(Resources.TraceSourceFailed2,
                                   string.Format(Resources.Culture, Resources.TraceSourceFailed3, log.ToString()));
                ExceptionFormatter formatter =
                    new ExceptionFormatter(additionalInfo, Resources.DistributorEventLoggerDefaultApplicationName);

                LogEntry reportingLogEntry = new LogEntry();
                reportingLogEntry.Severity = TraceEventType.Error;
                reportingLogEntry.Message  = formatter.GetMessage(exception);
                reportingLogEntry.EventId  = LogWriterFailureEventID;

                structureHolder.ErrorsTraceSource.TraceData(reportingLogEntry.Severity, reportingLogEntry.EventId, reportingLogEntry);
            }
            catch (Exception ex)
            {
                instrumentationProvider.FireFailureLoggingErrorEvent(Resources.FailureWhileTracing, ex);
            }
        }
 /// <summary>
 /// This constructor supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
 /// Initializes a new instance of the <see cref="LogWriterStructureHolder"/> class.
 /// </summary>
 /// <param name="filters">The collection of filters to use when processing an entry.</param>
 /// <param name="traceSourceNames">Names of the trace sources to dispatch entries to.</param>
 /// <param name="traceSources">The trace sources to dispatch entries to.</param>
 /// <param name="allEventsTraceSource">The special <see cref="LogSource"/> to which all log entries should be logged.</param>
 /// <param name="notProcessedTraceSource">The special <see cref="LogSource"/> to which log entries with at least one non-matching category should be logged.</param>
 /// <param name="errorsTraceSource">The special <see cref="LogSource"/> to which internal errors must be logged.</param>
 /// <param name="defaultCategory">The default category to set when entry categories list of a log entry is empty.</param>
 /// <param name="tracingEnabled">The tracing status.</param>
 /// <param name="logWarningsWhenNoCategoriesMatch">true if warnings should be logged when a non-matching category is found.</param>
 /// <param name="revertImpersonation">true if impersonation should be reverted while logging.</param>
 public LogWriterStructureHolder(
     IEnumerable<ILogFilter> filters,
     IEnumerable<string> traceSourceNames,
     IEnumerable<LogSource> traceSources,
     LogSource allEventsTraceSource,
     LogSource notProcessedTraceSource,
     LogSource errorsTraceSource,
     string defaultCategory,
     bool tracingEnabled,
     bool logWarningsWhenNoCategoriesMatch,
     bool revertImpersonation)
     : this(
         filters,
         traceSourceNames.ToDictionary(traceSources),
         allEventsTraceSource,
         notProcessedTraceSource,
         errorsTraceSource,
         defaultCategory,
         tracingEnabled,
         logWarningsWhenNoCategoriesMatch,
         revertImpersonation)
 {
 }
 private void DisposeSpecialLogSource(LogSource specialLogSource)
 {
     if (specialLogSource != null)
     {
         specialLogSource.Dispose();
     }
 }
 private static bool IsValidTraceSource(LogSource traceSource)
 {
     return(traceSource != null && traceSource.Listeners.Count > 0);
 }
Пример #20
0
        /// <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);
        }
Пример #21
0
 internal static SpecialLogSourceData FromLogSource(LogSource logSource)
 {
     return new SpecialLogSourceData(logSource.Name, logSource.Level, logSource.AutoFlush, logSource.Listeners.ToArray());
 }
Пример #22
0
 internal static SpecialLogSourceData FromLogSource(LogSource logSource)
 {
     return(new SpecialLogSourceData(logSource.Name, logSource.Level, logSource.AutoFlush, logSource.Listeners.ToArray()));
 }
Пример #23
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////
        // APIREV: make own type like TraceEventType so user won't have a need to add a reference to Logger dll.
        // Create log instance
        public static void Initialize(string logFilePath, int logFileSize,
            TraceEventType minimalSeverity, bool isLogEnabled)
        {
            if (logFileSize < 1)
                throw new SettingsException(Properties.Resources.LogFileCantBeSmall);
            _minimalSeverity = minimalSeverity;
            _isLogEnabled = isLogEnabled;

            // Create message formatter
            TextFormatter formatter = new TextFormatter(MESSAGE_FORMAT);

            // Create Log sources
            LogSource emptyTraceSource = new LogSource("EmptySource");
            LogSource errorsTraceSource = new LogSource("Logger", SourceLevels.All);

            // Create listener for rolling log file
            RollingFlatFileTraceListener rollingTrace = new RollingFlatFileTraceListener(logFilePath, "", "", formatter, logFileSize, "yyyy - MM - dd", RollFileExistsBehavior.Overwrite, RollInterval.Year);
            errorsTraceSource.Listeners.Add(rollingTrace);

            // Create and fill sources array
            IDictionary<string, LogSource> traceSources = new Dictionary<string, LogSource>();
            traceSources.Add(TraceEventType.Critical.ToString(), errorsTraceSource);
            traceSources.Add(TraceEventType.Error.ToString(), errorsTraceSource);
            traceSources.Add(TraceEventType.Warning.ToString(), errorsTraceSource);
            traceSources.Add(TraceEventType.Information.ToString(), errorsTraceSource);

            // create default category string
            string defaultCategory = _minimalSeverity.ToString();

            ICollection<ILogFilter> filters = new ILogFilter[0];
            _logWriter = new LogWriter(filters,   // filters collection
                                      traceSources,        // sources array
                                      emptyTraceSource,    // all events trace source
                                      emptyTraceSource,    // not processed trace source
                                      errorsTraceSource,   // errors trace source
                                      defaultCategory,     // string defaultCategory
                                      false,               // enable tracing
                                      true);               // save message as warning, when no categories match
        }