Exemplo n.º 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
        }
 private TraceListener CreateListener(IUnityContainer c)
 {
     var formatter = new TextFormatter("{message}{dictionary({key} - {value}{newline})}");
     var data = new CommonLoggingEntlibTraceListenerData(this.GetType().FullName, "{listenerName}.{sourceName}", "Text Formatter");
     var listener = new CommonLoggingEntlibTraceListener(data, formatter);
     return listener;
 }
        public void ShouldBeAbleToFormatLogWithExtraProperties()
        {
            Dictionary<string, object> parameterValues = new Dictionary<string, object>();
            parameterValues["one"] = 1;
            parameterValues["two"] = "two";

            TraceLogEntry logEntry = new TraceLogEntry();
            logEntry.Categories.Add("General");
            logEntry.Categories.Add("Callhandler");
            logEntry.Message = "Logging call";
            logEntry.ExtendedProperties = parameterValues;
            logEntry.TypeName = GetType().Name;
            logEntry.MethodName = "SomeMethod";
            logEntry.ReturnValue = 42.ToString();

            string template =
                @"Message logged on {timestamp}{newline}{message}{newline}
Call on type {property(TypeName)} method {property(MethodName)}{newline}
Parameter values:{newline}
{dictionary({key} = {value}{newline})}{newline}
Return value: {property(ReturnValue)}{newline}";

            TextFormatter formatter = new TextFormatter(template);

            string formatted = formatter.Format(logEntry);

            Assert.IsTrue(formatted.Contains("Logging call"));
            Assert.IsTrue(
                formatted.Contains("Call on type TraceLogEntryFixture method SomeMethod\r\n"));
            Assert.IsTrue(formatted.Contains("one = 1\r\n"));
            Assert.IsTrue(formatted.Contains("two = two\r\n"));
            Assert.IsTrue(formatted.Contains("Return value: 42\r\n"));
        }
Exemplo n.º 4
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);
        }
        /// <summary>
        /// Distribute a log entry to the sinks using a <see cref="LogDistributor"/>.
        /// </summary>
        /// <param name="logEntry">Message body</param>
        public void SendLog(LogEntry logEntry)
        {
            this.logDistributor.ProcessLog(logEntry);

            TextFormatter formatter = new TextFormatter(new TextFormatterData());
            string message = formatter.Format(logEntry);
            LoggingLogDistributedEvent.Fire(message);
        }
Exemplo n.º 6
0
        public void LogSendingMessageException(Exception ex, string sink, LogEntry logEntry)
        {
            logger.AddMessage(Header, SR.InvalidSink(sink));

            TextFormatter formatter = new TextFormatter(new TextFormatterData());
            string formattedMessage = formatter.Format(logEntry);
            logger.AddMessage(logEntry.Category, SR.InvalidSinkMessage(formattedMessage));

            logger.WriteToLog(ex, Severity.Warning);
        }
Exemplo n.º 7
0
        public void LogProcessLogException(LogEntry logEntry, Exception ex)
        {
            // distribution failed so write the event to the event log as a backup
            logger.AddMessage(Header, SR.ProcessMessageFailed);

            TextFormatter formatter = new TextFormatter(new TextFormatterData());
            string formattedMessage = formatter.Format(logEntry);
            logger.AddMessage(SR.ProcessMessageFailed2, SR.ProcessMessageFailed3(formattedMessage));

            logger.WriteToLog(ex, Severity.Error);
        }
Exemplo n.º 8
0
        public LoggingViewModel()
        {
            var logFormatter = new TextFormatter();

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

            var config = new LoggingConfiguration();
            config.AddLogSource("Hummingbird", SourceLevels.All, true).AddTraceListener(flatFileTraceListener);
            Logger = new LogWriter(config);
        }
Exemplo n.º 9
0
		private Logger()
		{
			string connectionString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
			TextFormatter formatter = new TextFormatter();
			var databaseTraceListener =
			  new FormattedDatabaseTraceListener(new SqlDatabase(connectionString)
			  , "WriteLog", "AddCategory", formatter);

			var config = new LoggingConfiguration();
			config.AddLogSource(LogCategories.General.ToString(), SourceLevels.All, true).AddTraceListener(databaseTraceListener);
			writer = new LogWriter(config);
			writer.Write("Starting...", LogCategories.General.ToString(), 9, 0, TraceEventType.Verbose, "Log Starting");
		}
Exemplo n.º 10
0
		static void Main(string[] args)
		{
			TextFormatter briefFormatter = new TextFormatter();

			var flatFileTraceListerner = new FlatFileTraceListener(@"C:\temp\xxx.log",
				"-------------------------------",
				"-------------------------------",
				briefFormatter);

			var config = new LoggingConfiguration();
			config.AddLogSource("my_log", System.Diagnostics.SourceLevels.All, true).AddTraceListener(flatFileTraceListerner);
			LogWriter logger = new LogWriter(config);
		}
Exemplo n.º 11
0
        private static LoggingConfiguration BuildProgrammaticConfig()
        {
            var formatter = new TextFormatter();
            var flatFileTraceListener = new FlatFileTraceListener(
                "log.txt",
                "----------------------------------------",
                "----------------------------------------",
                formatter);

            var config = new LoggingConfiguration();
            config.AddLogSource("General", SourceLevels.All, true).AddTraceListener(flatFileTraceListener);
            config.IsTracingEnabled = true;
            return config;
        }
Exemplo n.º 12
0
        private void ConfigureLogging()
        {
            // Formatter
            TextFormatter fm = new TextFormatter();
            var flatFileTraceListener = new
              FlatFileTraceListener(@"trace.log", "----------------------------------------", "----------------------------------------", fm);

            // Build Configuration
            var config = new LoggingConfiguration();
            config.AddLogSource("General", SourceLevels.All,
               true).AddTraceListener(flatFileTraceListener);
            config.IsTracingEnabled = true;
            config.SpecialSources.AllEvents.AddTraceListener(flatFileTraceListener);
            Logger.SetLogWriter(new LogWriter(config));
        }
Exemplo n.º 13
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]);
        }
Exemplo n.º 14
0
Arquivo: Logger.cs Projeto: 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
		}
Exemplo n.º 15
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
		}
Exemplo n.º 16
0
        internal static LoggingConfiguration BuildLoggingConfig(GlobalStateModel model)
        {
            // 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})}");
            TextFormatter errorFormatter = new TextFormatter("{timestamp} {message}");
            TextFormatter consoleFormatter = new TextFormatter("{timestamp} {severity} : {message}");
            // Listeners
            var errorFlatFileTraceListener = new FlatFileTraceListener(Directory.GetCurrentDirectory() + "\\" + "Error.log", "----------------------------------------", "----------------------------------------", errorFormatter);
            var outputFlatFileTraceListener = new FlatFileTraceListener(Directory.GetCurrentDirectory() + "\\" + "Output.log", "----------------------------------------", "----------------------------------------", errorFormatter);
            var outputViewTraceListener = new OutputViewTraceListener(model, consoleFormatter);
            //var consoleTraceListener = new CustomTraceListener();
            // Build Configuration
            var config = new LoggingConfiguration();
            config.AddLogSource("Error", SourceLevels.All, true).AddTraceListener(errorFlatFileTraceListener);
            config.AddLogSource("Output", SourceLevels.All, true).AddTraceListener(outputViewTraceListener);
            config.LogSources["Output"].AddTraceListener(outputFlatFileTraceListener);
            config.AddLogSource("Debug", SourceLevels.All, true).AddTraceListener(outputViewTraceListener);
            config.AddLogSource("OutputToFile", SourceLevels.All, true).AddTraceListener(outputFlatFileTraceListener);

            return config;
        }
Exemplo n.º 17
0
        public static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatter
            TextFormatter briefFormatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}");

            // Trace Listener
            var flatFileTraceListener = new FlatFileTraceListener(
                @"C:\Temp\jarwin.log",
                "----------------------------------------",
                "----------------------------------------",
                briefFormatter);

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

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

            config.IsLoggingEnabled = Convert.ToBoolean(ConfigurationManager.AppSettings["loggingEnabled"]);

            return config;
        }
Exemplo n.º 18
0
        static LoggingConfiguration BuildProgrammaticConfig()
        {
          // Formatters
          TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");

          // Category Filters
          ICollection<string> categories = new List<string>();
          categories.Add("BlockedByFilter");

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

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

          // Build Configuration
          var config = new LoggingConfiguration();
          config.Filters.Add(priorityFilter);
          config.Filters.Add(logEnabledFilter);
          config.Filters.Add(categoryFilter);

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

          return config;
        }
        public void SetupLogWriter()
        {
            writer = new StringWriter();
            TextFormatter formatter = new TextFormatter(preCallTemplate);
            listener = new FormattedTextWriterTraceListener(writer, formatter);

            LogSource logSource = new LogSource("Logging");
            logSource.Listeners.Add(listener);

            log = new LogWriterImpl(new ILogFilter[0], new LogSource[] { logSource },
                                    logSource, logSource, logSource, "General", true, true);
        }
Exemplo n.º 20
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\SalaryCalculator.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;
    }
        /// <summary>Builds the configuration used to log entries to the file system.</summary>
        /// <returns>A <see cref="LoggingConfiguration"/> with default settings.</returns>
        private LoggingConfiguration BuildLoggingConfiguration()
        {
            TextFormatter formatter = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");

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

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

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

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

            // Build Configuration
            LoggingConfiguration config = new LoggingConfiguration();
            config.Filters.Add(priorityFilter);
            config.Filters.Add(logEnabledFilter);
            config.Filters.Add(categoryFilter);

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

            return config;
        }
Exemplo n.º 22
0
        /// <summary>
        /// Write the log entry to the configured event log.
        /// </summary>
        /// <param name="logEntry"><see cref="LogEntry"></see> to be written to the event log</param>
        public void SendMessage(LogEntry logEntry)
        {
            try
            {
                short categoryID = GetCategoryId(logEntry);

                logEntry.AddErrorMessage(SR.DefaultLogDestinationMessage);

                TextFormatter formatter = formatter = new TextFormatter(new TextFormatterData());
                string message = FormatEntry(formatter, logEntry);

                EventLog.WriteEntry(
                    eventLogSourceName,
                    message,
                    SeverityMap.GetEventLogEntryType(logEntry.Severity),
                    logEntry.EventId,
                    categoryID);

                LoggingLogDeliveryFailureEvent.Fire(message);
            }
            catch (Exception e)
            {
                throw new LoggingException(SR.DefaultLogDestinationFailed, e);
            }
            catch
            {
                throw new LoggingException(SR.DefaultLogDestinationFailed);
            }
        }
Exemplo n.º 23
0
        public void SetupLogWriter()
        {
            writer = new StringWriter();
            TextFormatter formatter = new TextFormatter(preCallTemplate);
            listener = new FormattedTextWriterTraceListener(writer, formatter);

            LogSource logSource = new LogSource("Logging", new[] { listener }, SourceLevels.All);

            log = new LogWriter(new ILogFilter[0], new LogSource[] { logSource },
                                    logSource, logSource, logSource, "General", true, true);

            Logger.SetLogWriter(this.log, false);
        }
Exemplo n.º 24
0
 static LogEntry()
 {
     isFullyTrusted = typeof(LogEntry).Assembly.IsFullyTrusted;
     toStringFormatter = new TextFormatter();
 }
Exemplo n.º 25
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
        }
Exemplo n.º 26
0
        private 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.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;
        }