public void RollingFlatFileTraceListenerReplacedEnviromentVariablesWillFallBackIfNotPrivilegesToRead()
        {
            string environmentVariable = "%USERPROFILE%";
            string fileName            = Path.Combine(environmentVariable, "foo.log");

            EnvironmentPermission denyPermission = new EnvironmentPermission(PermissionState.Unrestricted);

            denyPermission.Deny();

            try
            {
                RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(fileName, "header", "footer", null, 1, "", RollFileExistsBehavior.Increment, RollInterval.Day);
                listener.TraceData(new TraceEventCache(), "source", TraceEventType.Error, 1, "This is a test");
                listener.Dispose();
            }
            catch (InvalidOperationException)
            {
                throw;
            }
            finally
            {
                EnvironmentPermission.RevertAll();
            }

            Assert.Fail("Permission was not denied.");
        }
Пример #2
0
        public static LoggingConfiguration Create(string name, string filePath = null)
        {
            if (string.IsNullOrWhiteSpace(name))
            {
                name = "Default";
            }

            // Trace Listeners
            var listener = new RollingFlatFileTraceListener((filePath ?? "Logging") + "\\" + name + ".log",
                                                            header: string.Empty, footer: string.Empty, formatter: _SimplyFormatter,
                                                            rollFileExistsBehavior: RollFileExistsBehavior.Increment, rollInterval: RollInterval.Day, maxArchivedFiles: 30);

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

            config.DefaultSource    = LogLevel.Information.ToString();
            config.IsLoggingEnabled = true;
            //config.AddLogSource(Logger.InformationCategoryName, SourceLevels.All, autoFlush: true).AddAsynchronousTraceListener(listener);
            // Special Sources Configuration
            //config.SpecialSources.Unprocessed.AddTraceListener(listener);
            config.SpecialSources.Unprocessed.Level     = SourceLevels.All;
            config.SpecialSources.Unprocessed.AutoFlush = true;
            var eventLogListener = CreateEventLogTraceListener();

            config.SpecialSources.LoggingErrorsAndWarnings.AddTraceListener(eventLogListener);
            config.SpecialSources.LoggingErrorsAndWarnings.Level     = SourceLevels.All;
            config.SpecialSources.LoggingErrorsAndWarnings.AutoFlush = true;
            // All Event
            config.SpecialSources.AllEvents.AddAsynchronousTraceListener(listener);
            config.SpecialSources.AllEvents.Level     = SourceLevels.All;
            config.SpecialSources.AllEvents.AutoFlush = true;
            return(config);
        }
        public void CanCreatePoliciesForRollingFlatFileTraceListener()
        {
            RollingFlatFileTraceListenerData listenerData
                = new RollingFlatFileTraceListenerData(
                      "listener",
                      Path.Combine(Environment.CurrentDirectory, "test.log"),
                      "header",
                      "footer",
                      100,
                      "pattern",
                      RollFileExistsBehavior.Overwrite,
                      RollInterval.Midnight,
                      TraceOptions.Callstack | TraceOptions.ProcessId,
                      "");

            listenerData.Filter = SourceLevels.Error;
            loggingSettings.TraceListeners.Add(listenerData);

            using (var container = CreateContainer())
            {
                RollingFlatFileTraceListener createdObject =
                    (RollingFlatFileTraceListener)((ReconfigurableTraceListenerWrapper)container.Resolve <TraceListener>("listener")).InnerTraceListener;

                Assert.IsNotNull(createdObject);
                Assert.AreEqual(listenerData.TraceOutputOptions, createdObject.TraceOutputOptions);
                Assert.IsNotNull(createdObject.Filter);
                Assert.IsInstanceOfType(createdObject.Filter, typeof(EventTypeFilter));
                Assert.AreEqual(listenerData.Filter, ((EventTypeFilter)createdObject.Filter).EventType);
                Assert.IsNull(createdObject.Formatter);
                Assert.AreEqual(listenerData.FileName, ((FileStream)((StreamWriter)createdObject.Writer).BaseStream).Name);
            }
        }
Пример #4
0
        public void RolledFileWithOverwriteWillOverwriteArchiveFileIfDateTemplateMatches()
        {
            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;
                traceListener.Write("1234567890");

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
                traceListener.Write("12345");

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
                traceListener.Write("abcde");
            }

            Assert.IsTrue(File.Exists(this.fileName));
            Assert.AreEqual("abcde", File.ReadAllText(this.fileName));
            Assert.IsTrue(File.Exists(this.fileNameWithoutExtension + ".2007" + extension));
            Assert.AreEqual("12345", File.ReadAllText(this.fileNameWithoutExtension + ".2007" + extension));

            string[] archiveFiles = Directory.GetFiles(".", this.fileNameWithoutExtension + ".2007" + extension + "*");
            Assert.AreEqual(1, archiveFiles.Length);
        }
        public void RolledFileWithIncrementWillCreateArchiveFileWithMaxSequenceIfDateTemplateDoesMatch()
        {
            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
                traceListener.Write("1234567890");

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
                traceListener.Write("12345");

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 02));
                traceListener.Write("abcde");
            }

            Assert.IsTrue(File.Exists(fileName));
            Assert.AreEqual("abcde", File.ReadAllText(fileName));
            Assert.IsTrue(File.Exists(fileNameWithoutExtension + ".2007.2" + extension));
            Assert.AreEqual("12345", File.ReadAllText(fileNameWithoutExtension + ".2007.2" + extension));
            Assert.IsTrue(File.Exists(fileNameWithoutExtension + ".2007.1" + extension));
            Assert.AreEqual("1234567890", File.ReadAllText(fileNameWithoutExtension + ".2007.1" + extension));

            string[] archiveFiles = Directory.GetFiles(".", fileNameWithoutExtension + ".2007*" + extension + "*");
            Assert.AreEqual(2, archiveFiles.Length);
        }
Пример #6
0
        /// <summary>
        /// Builds Programmatic Configuration for Logging
        /// </summary>
        /// <returns>LoggingConfiguration</returns>
        public static LoggingConfiguration BuildProgrammaticConfig()
        {
            ResourceManager resxManager = new ResourceManager(ConfigurationManager.AppSettings["FmoMessages_ResourceFileName"], Assembly.GetExecutingAssembly());

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

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

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

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

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

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

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

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

            loggingConfiguration.AddLogSource("RollFFOverwrite", SourceLevels.All, true, rollingFlatFileTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(rollingFlatFileTraceListener);
        }
        public void FileIsRolledWhenIntervalSetToMidnightAndOverwrite()
        {
            fileNameWithoutExtension = Guid.NewGuid().ToString();
            fileName = fileNameWithoutExtension + Extension;

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "--header--", "--footer--", null,
                                                          0, String.Empty, RollFileExistsBehavior.Overwrite, RollInterval.Midnight))
            {
                traceListener.TraceData(new TraceEventCache(),
                                        "source",
                                        TraceEventType.Information,
                                        0,
                                        "logged message 1");
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                dateTimeProvider.SetCurrentDateTime(DateTime.Now);
                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                dateTimeProvider.SetCurrentDateTime(DateTime.Now.AddDays(1).Date);
                //dateTimeProvider.currentDateTime = DateTime.Now.AddMinutes(2);
                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.TraceData(new TraceEventCache(), "source", TraceEventType.Information, 1, "logged message 2");
            }

            Assert.IsTrue(File.Exists(fileName));
            Assert.IsTrue(LogFileReader.ReadFileWithoutLock(fileName).Contains("logged message 2"));
            Assert.IsFalse(LogFileReader.ReadFileWithoutLock(fileName).Contains("logged message 1"));

            string[] archiveFiles = Directory.GetFiles(".", fileNameWithoutExtension + "*");

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

            loggingConfiguration.AddLogSource("RollFFIncrement", SourceLevels.All, true, rollingFlatFileTraceListener);
            loggingConfiguration.SpecialSources.Unprocessed.Listeners.Add(rollingFlatFileTraceListener);
        }
        public void RolledFileWithOverwriteWillFallBackToUniqueNameIfDateTemplateMatchesButArchiveFileIsInUse()
        {
            string targetArchiveFile = fileNameWithoutExtension + ".2007" + extension;

            using (FileStream stream = File.Open(targetArchiveFile, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                using (RollingFlatFileTraceListener traceListener
                           = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                              0, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
                {
                    traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
                    traceListener.Write("1234567890");

                    Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                    traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
                    traceListener.Write("12345");
                }
            }

            Assert.IsTrue(File.Exists(fileName));
            Assert.AreEqual("12345", File.ReadAllText(fileName));
            Assert.IsTrue(File.Exists(targetArchiveFile));
            Assert.AreEqual("", File.ReadAllText(targetArchiveFile)); // couldn't archive

            string[] archiveFiles = Directory.GetFiles(".", targetArchiveFile + "*");
            Assert.AreEqual(2, archiveFiles.Length);
            foreach (string archiveFile in archiveFiles)
            {
                if (!Path.GetFileName(archiveFile).Equals(targetArchiveFile))
                {
                    Assert.AreEqual("1234567890", File.ReadAllText(archiveFile));
                }
            }
        }
        public void DontWriteHeaderOrFooterWhenEventsAreFiltered()
        {
            const string header   = "MockHeader";
            const string footer   = "MockFooter";
            const string fileName = "rolling.log";
            string       filePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + fileName;

            try
            {
                LogEntry log = new LogEntry("Header nor footer written", "Category", 1, 1, TraceEventType.Error, "FilteredEventsDontWriteHeaderNorFooter", null);

                RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(filePath, header, footer, null, 100, "mmddyyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day);

                listener.Filter = new EventTypeFilter(SourceLevels.Off);
                listener.TraceData(null, "Error", TraceEventType.Error, 1, log);
                listener.Flush();
                listener.Close();

                Assert.IsTrue(File.Exists(filePath));

                StreamReader reader  = new StreamReader(filePath);
                string       content = reader.ReadToEnd();
                reader.Close();

                Assert.IsFalse(content.Contains(header));
                Assert.IsFalse(content.Contains(footer));
            }
            finally
            {
                File.Delete(filePath);
            }
        }
        public void WillRollForDateIfEnabled()
        {
            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                dateTimeProvider.currentDateTime = DateTime.Now;
                traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

                dateTimeProvider.currentDateTime = DateTime.Now.AddDays(2);
                Assert.IsNotNull(traceListener.RollingHelper.CheckIsRollNecessary());
            }

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Increment, RollInterval.None))
            {
                traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                dateTimeProvider.currentDateTime = DateTime.Now;
                traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

                dateTimeProvider.currentDateTime = DateTime.Now.AddDays(2);
                Assert.IsNull(traceListener.RollingHelper.CheckIsRollNecessary());
            }
        }
        public void WillTruncateExistingFileIfOverSizeThresholdAndNoPatternIsSpecifiedForOverwriteBehavior()
        {
            string   existingPayload = new string('c', 5000);
            DateTime currentDateTime = new DateTime(2007, 1, 1);

            File.WriteAllText(fileName, existingPayload);
            File.SetCreationTime(fileName, currentDateTime);

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          1, "", RollFileExistsBehavior.Overwrite, RollInterval.None))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
                dateTimeProvider.currentDateTime             = currentDateTime;

                traceListener.TraceData(new TraceEventCache(),
                                        "source",
                                        TraceEventType.Error,
                                        0,
                                        "logged message");
            }

            Assert.IsFalse(File.ReadAllText(fileName).Contains(existingPayload));
            Assert.IsTrue(File.ReadAllText(fileName).Contains("logged message"));
        }
        public void ArchiveFilesAreWrittenWhenAddingUnprocessedSourceForRollingFlatFile()
        {
            var config = new LoggingConfiguration();

            config.IsTracingEnabled = true;
            config.DefaultSource    = "General";
            config.LogWarningsWhenNoCategoriesMatch = true;

            var rollingFlatFileTraceListener = new RollingFlatFileTraceListener(Path.Combine(strPath, @"TraceTest.log"),
                                                                                "----------------------------------------",
                                                                                "----------------------------------------",
                                                                                new TextFormatter("Timestamp: {timestamp}{newline}&#xA;Message: {message}{newline}&#xA;Category: {category}{newline}&#xA;Priority: {priority}{newline}&#xA;EventId: {eventid}{newline}&#xA;Severity: {severity}{newline}&#xA;Title:{title}{newline}&#xA;Machine: {localMachine}{newline}&#xA;App Domain: {localAppDomain}{newline}&#xA;ProcessId: {localProcessId}{newline}&#xA;Process Name: {localProcessName}{newline}&#xA;Thread Name: {threadName}{newline}&#xA;Win32 ThreadId:{win32ThreadId}{newline}&#xA;Extended Properties: {dictionary({key} - {value}{newline})}"),
                                                                                1, "yyyy", RollFileExistsBehavior.Increment, RollInterval.None, 3);

            config.SpecialSources.Unprocessed.Listeners.Add(rollingFlatFileTraceListener);
            this.writer = new LogWriter(config);

            this.writer.Write("Test Logging Rolling 1");
            this.writer.Write("Test Logging Rolling 2");
            this.writer.Write("Test Logging Rolling 3");
            this.writer.Write("Test Logging Rolling 4");
            this.writer.Write("Test Logging Rolling 5");
            this.writer.Write("Test Logging Rolling 6");
            this.writer.Dispose();

            Assert.IsTrue(File.Exists(Path.Combine(this.strPath, "TraceTest.log")));
            Assert.IsTrue(File.Exists(Path.Combine(this.strPath, "TraceTest" + "." + DateTime.Now.Year + ".1" + ".log")));
            Assert.IsTrue(File.Exists(Path.Combine(this.strPath, "TraceTest" + "." + DateTime.Now.Year + ".2" + ".log")));
        }
        public void WillRollExistingFileIfOverDateThreshold()
        {
            string   existingPayload = new string('c', 10);
            DateTime currentDateTime = new DateTime(2007, 1, 1);

            File.WriteAllText(fileName, existingPayload);
            File.SetCreationTime(fileName, currentDateTime);

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          1, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
                dateTimeProvider.currentDateTime             = currentDateTime.AddDays(2);

                traceListener.TraceData(new TraceEventCache(),
                                        "source",
                                        TraceEventType.Error,
                                        0,
                                        "logged message");
            }

            Assert.AreEqual(existingPayload, File.ReadAllText(fileNameWithoutExtension + ".2007" + extension));
            Assert.IsTrue(File.ReadAllText(fileName).Contains("logged message"));
        }
        public void RollingFlatFileTraceListenerReplacedEnviromentVariables()
        {
            string fileName = @"%USERPROFILE%\foo.log";

            string fileNameFromListener = string.Empty;

            RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(fileName, "header", "footer", null, 1, "", RollFileExistsBehavior.Increment, RollInterval.Day);

            listener.TraceData(new TraceEventCache(), "source", TraceEventType.Error, 1, "This is a test");
            listener.Dispose();

            string expandedFileName = Environment.ExpandEnvironmentVariables(fileName);

            bool result = File.Exists(expandedFileName);

            Assert.IsTrue(result);

            using (FileStream stream = File.Open(expandedFileName, FileMode.Open))
            {
                fileNameFromListener = stream.Name;
            }

            File.Delete(expandedFileName);
            Assert.AreEqual(expandedFileName, fileNameFromListener);
        }
 public void WillNotRollWhenTracingIfNotOverThresholds()
 {
     using (RollingFlatFileTraceListener traceListener
                = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                   0, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Day))
     {
         traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
     }
 }
        public static void CheckListener()
        {
            string environmentVariable = "%USERPROFILE%";
            string fileName            = Path.Combine(environmentVariable, "test.log");

            RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(fileName, "header", "footer", null, 1, "", RollFileExistsBehavior.Increment, RollInterval.Day);

            listener.TraceData(new TraceEventCache(), "source", TraceEventType.Error, 1, "This is a test");
            listener.Dispose();
        }
Пример #19
0
        static LoggingConfiguration BuildProgrammaticConfig()
        {
            // Formatters
            TextFormatter briefFormatter    = new TextFormatter("Timestamp: {timestamp(local)}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}ActivityId: {property(ActivityId)}{newline}Severity: {severity}{newline}Title:{title}{newline}");
            TextFormatter extendedFormatter = new TextFormatter("Timestamp: {timestamp}{newline}Message: {message}{newline}Category: {category}{newline}Priority: {priority}{newline}EventId: {eventid}{newline}Severity: {severity}{newline}Title: {title}{newline}Activity ID: {property(ActivityId)}{newline}Machine: {localMachine}{newline}App Domain: {localAppDomain}{newline}ProcessId: {localProcessId}{newline}Process Name: {localProcessName}{newline}Thread Name: {threadName}{newline}Win32 ThreadId:{win32ThreadId}{newline}Extended Properties: {dictionary({key} - {value}{newline})}");

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

            categories.Add("BlockedByFilter");

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

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

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

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

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

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

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

            return(config);
        }
 /// <summary>
 ///     Creates a new logger that will send log output to a file. If the file already exists then
 ///     it is overwritten.
 /// </summary>
 /// <param name="path">A path to the file to which log output will be written.</param>
 public TSharpDatabaseLogger(string path)
 {
     traceWriter = new RollingFlatFileTraceListener(
         path,
         null,
         null,
         1024,
         "HHmmssfff",
         "yyyyMMdd",
         RollFileExistsBehavior.Increment,
         RollInterval.Day);
     innerWriter = traceWriter.WriteLine;
 }
 /// <summary>
 ///     Creates a new logger that will send log output to the console.
 /// </summary>
 public TSharpDatabaseLogger()
 {
     traceWriter = new RollingFlatFileTraceListener(
         @"App_data\Sqls\trace.csv",
         null,
         null,
         1024,
         "yyyyMMddHHmmss",
         "yyyyMMdd",
         RollFileExistsBehavior.Increment,
         RollInterval.Day);
     innerWriter = traceWriter.Write;
 }
Пример #22
0
        /// <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
        }
        public void ListenerForNewFileWillUseCreationDateToCalculateRollDate()
        {
            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                Assert.AreEqual(traceListener.RollingHelper.CalculateNextRollDate(File.GetCreationTime(fileName)), traceListener.RollingHelper.NextRollDateTime);
                Assert.IsNull(traceListener.RollingHelper.CheckIsRollNecessary());
            }
        }
        public void WriterKeepsTally()
        {
            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null, 10, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                traceListener.Write("12345");

                Assert.AreEqual(5L, ((RollingFlatFileTraceListener.TallyKeepingFileStreamWriter)traceListener.Writer).Tally);
            }
        }
        public void RollIsNecessaryWhenUsingJsonFormatterWithRollingFlatFileTraceListener()
        {
            this.fileNameWithoutExtension = Guid.NewGuid().ToString();
            this.fileName = this.fileNameWithoutExtension + JsonLogFormatterFixture.Extension;

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(this.fileName, "header", "footer", new JsonLogFormatter(JsonFormatting.Indented),
                                                          1, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Year))
            {
                traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

                traceListener.Write(new string('c', 1200));

                Assert.IsNotNull(traceListener.RollingHelper.CheckIsRollNecessary());
            }
        }
        /// <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);
        }
Пример #27
0
        public void ListenerForExistingFileWillUseCreationDateToCalculateRollDate()
        {
            File.WriteAllText(this.fileName, "existing text");
            File.SetCreationTime(this.fileName, new DateTime(2000, 01, 01));

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
            {
                traceListener.RollingHelper.DateTimeProvider = this.dateTimeProvider;

                Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                Assert.AreEqual(traceListener.RollingHelper.CalculateNextRollDate(File.GetCreationTime(this.fileName)), traceListener.RollingHelper.NextRollDateTime);
                Assert.AreEqual(this.dateTimeProvider.CurrentDateTime, traceListener.RollingHelper.CheckIsRollNecessary());
            }
        }
Пример #28
0
        public void RollingFlatFileTraceListenerReplacedInexistingEnviromentVariables()
        {
            string fileName = @"tmp\%FOO%\%MY_VARIABLE%\foo.log";

            RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(fileName, "header", "footer", null, 1, "", RollFileExistsBehavior.Increment, RollInterval.Day);

            listener.TraceData(new TraceEventCache(), "source", TraceEventType.Error, 1, "This is a test");
            listener.Dispose();

            string expandedFileName = EnvironmentHelper.ReplaceEnvironmentVariables(fileName);
            string expectedFileName = Path.GetFileName(expandedFileName);

            bool result = File.Exists(expandedFileName);

            Assert.IsTrue(result);

            File.Delete(expandedFileName);
        }
Пример #29
0
        ///////////////////////////////////////////////////////////////////////////////////////////
        ///////////////////////////////////////////////////////////////////////////////////////////

        // APIREV: make own type like TraceEventType so user won't have a need to add a reference to Logger dll.
        // Create log instance
        static public 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
        }
        public void RolledAtMidnight()
        {
            DateTime rollDate = DateTime.Now.AddDays(1).Date;

            using (RollingFlatFileTraceListener traceListener
                       = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                          0, "yyyy", RollFileExistsBehavior.Increment, RollInterval.Midnight))
            {
                traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;

                dateTimeProvider.currentDateTime = rollDate;

                traceListener.RollingHelper.UpdateRollingInformationIfNecessary();

                Assert.IsNotNull(traceListener.RollingHelper.NextRollDateTime);
                Assert.IsNotNull(traceListener.RollingHelper.CheckIsRollNecessary());
                Assert.AreEqual(rollDate, traceListener.RollingHelper.NextRollDateTime);
            }
        }
        public void FallbackFileNameIsUsedForRoll()
        {
            using (FileStream fileStream = File.Open(fileName, FileMode.CreateNew, FileAccess.Write, FileShare.Read))
            {
                using (RollingFlatFileTraceListener traceListener
                           = new RollingFlatFileTraceListener(fileName, "header", "footer", null,
                                                              10, "yyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day))
                {
                    traceListener.RollingHelper.DateTimeProvider = dateTimeProvider;
                    traceListener.Write("1234567890");

                    Assert.IsTrue(traceListener.RollingHelper.UpdateRollingInformationIfNecessary());

                    traceListener.RollingHelper.PerformRoll(new DateTime(2007, 01, 01));
                    traceListener.Write("12345");

                    Assert.AreEqual(5L, ((RollingFlatFileTraceListener.TallyKeepingFileStreamWriter)traceListener.Writer).Tally);
                }
            }
        }
        /// <summary>
        /// This method supports the Enterprise Library infrastructure and is not intended to be used directly from your code.
        /// Builds a <see cref="FlatFileTraceListener"/> based on an instance of <see cref="FlatFileTraceListenerData"/>.
        /// </summary>
        /// <seealso cref="TraceListenerCustomFactory"/>
        /// <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. Must be an instance of <see cref="FlatFileTraceListenerData"/>.</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="FlatFileTraceListener"/>.</returns>
        public override TraceListener Assemble(IBuilderContext context, TraceListenerData objectConfiguration, IConfigurationSource configurationSource, ConfigurationReflectionCache reflectionCache)
        {
            RollingFlatFileTraceListenerData castObjectConfiguration
                = (RollingFlatFileTraceListenerData)objectConfiguration;

            ILogFormatter formatter = GetFormatter(context, castObjectConfiguration.Formatter, configurationSource, reflectionCache);

            RollingFlatFileTraceListener createdObject
                = new RollingFlatFileTraceListener(
                      castObjectConfiguration.FileName,
                      castObjectConfiguration.Header,
                      castObjectConfiguration.Footer,
                      formatter,
                      castObjectConfiguration.RollSizeKB,
                      castObjectConfiguration.TimeStampPattern,
                      castObjectConfiguration.RollFileExistsBehavior,
                      castObjectConfiguration.RollInterval
                      );

            return(createdObject);
        }
            /// <summary>
            /// Initialize a new instance of the <see cref="StreamWriterRollingHelper"/> class with a <see cref="RollingFlatFileTraceListener"/>.
            /// </summary>
            /// <param name="owner">The <see cref="RollingFlatFileTraceListener"/> to use.</param>
            public StreamWriterRollingHelper(RollingFlatFileTraceListener owner)
            {
                this.owner = owner;
                dateTimeProvider = new DateTimeProvider();

                performsRolling = this.owner.rollInterval != RollInterval.None || this.owner.rollSizeInBytes > 0;
            }
        private RollingFlatFileTraceListener RollingFlatFileTraceListenerGet()
        {
            if (this._rollingFlatFileTraceListener == null)
            {
                this.AttributesSetDefaultValues();

                this._rollingFlatFileTraceListener = new RollingFlatFileTraceListener(
                                                            this.Attributes[_fileNameAttribute]
                                                            , string.Empty
                                                            , string.Empty
                                                            , null
                                                            , this._rollSizeKB
                                                            , this._timeStampPattern
                                                            , RollFileExistsBehavior.Overwrite
                                                            , RollInterval.None
                                                            , this._maxArchivedFiles);
            }

            return this._rollingFlatFileTraceListener;
        }
        /// <summary>
        ///     Stops logging and closes the underlying file if output is being written to a file.
        /// </summary>
        /// <param name="disposing">
        ///     True to release both managed and unmanaged resources; False to release only unmanaged resources.
        /// </param>
        protected virtual void Dispose(bool disposing)
        {
            StopLogging();

            if (disposing && traceWriter != null)
            {
                traceWriter.Dispose();
                traceWriter = null;
            }
            if (disposing && innerWriter != null) innerWriter = null;
        }
        public void DontWriteHeaderOrFooterWhenEventsAreFiltered()
        {
            const string header = "MockHeader";
            const string footer = "MockFooter";
            const string fileName = "rolling.log";
            string filePath = AppDomain.CurrentDomain.BaseDirectory + "\\" + fileName;

            try
            {
                LogEntry log = new LogEntry("Header nor footer written", "Category", 1, 1, TraceEventType.Error, "FilteredEventsDontWriteHeaderNorFooter", null);

                RollingFlatFileTraceListener listener = new RollingFlatFileTraceListener(filePath, header, footer, null, 100, "mmddyyyy", RollFileExistsBehavior.Overwrite, RollInterval.Day);

                listener.Filter = new EventTypeFilter(SourceLevels.Off);
                listener.TraceData(null, "Error", TraceEventType.Error, 1, log);
                listener.Flush();
                listener.Close();

                Assert.IsTrue(File.Exists(filePath));

                StreamReader reader = new StreamReader(filePath);
                string content = reader.ReadToEnd();
                reader.Close();

                Assert.IsFalse(content.Contains(header));
                Assert.IsFalse(content.Contains(footer));
            }
            finally
            {
                File.Delete(filePath);
            }
        }