Пример #1
0
        public void Check1TraceErrorWithoutDelayed()
        {
            CleanOutput();

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory, 2, false))
            {
                AdvancedTrace.AddTraceListener(AdvancedTrace.ListenerType.All, logStorage);

                try
                {
                    throw new Exception("Exception 1");
                }
                catch (Exception e)
                {
                    try
                    {
                        throw new Exception("Exception 2", e);
                    }
                    catch (Exception e1)
                    {
                        AdvancedTrace.TraceError("MyError", e1, "Info");
                    }
                }

                AdvancedTrace.RemoveTraceListener(AdvancedTrace.ListenerType.All, logStorage);
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.Load(Path.Combine(CurrentDirectory, "Working_session_1_1.xml"));
        }
Пример #2
0
        private static void StartExecTimer()
        {
            _execTimer.Start();
            Console.WriteLine("execTimer started");
            try
            {
                Delay(10);
                Log("execution 10 milliseconds");
                Delay(3000);
                Log("execution 6000 milliseconds");
                Delay(3000);
                Log("execution 6000 milliseconds");
                Delay(4000);
                Log("execution 6000 milliseconds");
            }
            catch (System.Exception ex)
            {
                using (XmlWriterTraceListener xmlLogger = new XmlWriterTraceListener("./ErrorLog.xml"))
                {
                    xmlLogger.TraceEvent(new TraceEventCache(), ex.Message, TraceEventType.Error, ex.HResult);
                    xmlLogger.Flush();
                }

                XmlWriterTraceListener xmlLogger2 = new XmlWriterTraceListener("./ErrorLog2.xml");
                xmlLogger2.WriteLine(ex.Message);
                xmlLogger2.Flush();
                xmlLogger2.Close();
            }
        }
Пример #3
0
        public TraceWorker()
        {
            // simple trace listeners
            TraceListener tlConsole = new ConsoleTraceListener();

            tlConsole.Filter = new EventTypeFilter(SourceLevels.All);

            // trace listener - file in solution folder
            TraceListener tlFile = new TextWriterTraceListener(new StreamWriter("ClassDemoLogFile.txt"));

            tlFile.Filter = new EventTypeFilter(SourceLevels.Warning);

            // trace listener - file in solution folder
            TraceListener tlXmlFile = new XmlWriterTraceListener(new StreamWriter("ClassDemoLogFile.xml"));

            tlXmlFile.Filter = new EventTypeFilter(SourceLevels.Warning);

            // This is deprecated in .Net Core does only exists by download a nuget packet 'Microsoft.Extensions.Logging.EventLog'
            //trace listener - windows event log
            TraceListener tlEventLog = new EventLogTraceListener("MyTrace");

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

            // My own trace listener
            tlOwn        = new MyOwnTraceListener();
            tlOwn.Filter = new EventTypeFilter(SourceLevels.All);

            Trace.Listeners.Add(tlConsole);
            Trace.Listeners.Add(tlFile);
            Trace.Listeners.Add(tlXmlFile);
            Trace.Listeners.Add(tlEventLog);
            Trace.Listeners.Add(tlOwn);
        }
        public void TraceData_MultipleXPathNavigators()
        {
            string xml1 = "<Error xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\">" +
                          "<Info>Exception thrown</Info>" +
                          "<Detail>Failed when trying to connect to server</Detail>" +
                          "</Error>";
            XPathNavigator navigator1 = XDocument.Parse(xml1).CreateNavigator();

            string xml2 = "<TestTrace xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\">" +
                          "<TraceInformationTest>This is some information</TraceInformationTest>" +
                          "</TestTrace>";
            XPathNavigator navigator2 = XDocument.Parse(xml2).CreateNavigator();

            string file       = GetTestFilePath();
            var    eventCache = new TraceEventCache();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.TraceData(eventCache, "Trace", TraceEventType.Information, 100, navigator1, navigator2);
            }

            var document = new XmlDocument();

            document.Load(file);

            ValidateSystemInfo(document, "100", TraceEventType.Information, eventCache.DateTime, eventCache);

            XmlNodeList nodes = document.GetElementsByTagName("DataItem");

            Assert.Equal(2, nodes.Count);

            Assert.Equal(xml1, nodes[0].InnerXml);
            Assert.Equal(xml2, nodes[1].InnerXml);
        }
        public void TraceData_NullObjectArray()
        {
            string file       = GetTestFilePath();
            var    eventCache = new TraceEventCache();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.TraceData(eventCache, "Trace", TraceEventType.Information, 100, null, null, null);
            }

            var document = new XmlDocument();

            document.Load(file);

            ValidateSystemInfo(document, "100", TraceEventType.Information, eventCache.DateTime, eventCache);

            XmlNodeList nodes = document.GetElementsByTagName("DataItem");

            Assert.Equal(3, nodes.Count);

            foreach (XmlNode node in nodes)
            {
                Assert.Equal(string.Empty, node.InnerText);
            }

            Assert.Equal("<TraceData xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\"><DataItem></DataItem><DataItem></DataItem><DataItem></DataItem></TraceData>", document.GetElementsByTagName("ApplicationData")[0].InnerXml);
        }
        public void FailTest(string message, string detailMessage)
        {
            string   file = GetTestFilePath();
            DateTime date;

            using (var listener = new XmlWriterTraceListener(file))
            {
                // Let's cache the date right before creating the trace so that later on we don't get different values if for some reason teh date changed.
                date = DateTime.Now;
                listener.Fail(message, detailMessage);
            }

            var document = new XmlDocument();

            document.Load(file);

            ValidateSystemInfo(document, "0", TraceEventType.Error, date, null);

            XmlNode node            = document.GetElementsByTagName("ApplicationData")[0];
            string  actualMessage   = node.InnerText;
            string  expectedMessage = detailMessage != null ? $"{message} {detailMessage}" : message;

            Assert.Equal(expectedMessage, actualMessage);
            Assert.Equal(expectedMessage.Length, actualMessage.Length);
        }
Пример #7
0
        static void Main()
        {
            DumpMaker.PathToDirectory = Application.StartupPath;

            // Получаем аргументы коммандной строки
            String[] args = Environment.GetCommandLineArgs();

            //_Trace.Switch.Level = SourceLevels.Error;
            String pathToExe = Application.StartupPath + @"\AppXmlLog.xml";

            _XmlLog = new XmlWriterTraceListener(pathToExe, "XmlLog");
            _XmlLog.TraceOutputOptions |= (TraceOptions.Callstack | TraceOptions.DateTime |
                                           TraceOptions.LogicalOperationStack | TraceOptions.ProcessId |
                                           TraceOptions.ThreadId | TraceOptions.Timestamp);
            _XmlLog.Filter = new EventTypeFilter(SourceLevels.Error);
            _Trace.Listeners.Add(_XmlLog);

            //Application.SetUnhandledExceptionMode(UnhandledExceptionMode.ThrowException);

            //AppDomain.CurrentDomain.UnhandledException += DumpMaker.CurrentDomain_UnhandledException;


            // Событие необработанного исключения в других потоках
            //Application.ThreadException += new System.Threading.ThreadExceptionEventHandler(Application_ThreadException);
            // Set the unhandled exception mode to force all Windows Forms errors to go through
            // our handler.
            Application.SetUnhandledExceptionMode(UnhandledExceptionMode.CatchException, true);

            // Событие необработанного исключения на уровне приложения
            AppDomain.CurrentDomain.UnhandledException += new UnhandledExceptionEventHandler(CurrentDomain_UnhandledException);

            Application.EnableVisualStyles();
            Application.SetCompatibleTextRenderingDefault(false);
            Application.Run(new FormMain(args));
        }
Пример #8
0
        public void StressTrace1ThreadAnd100000TraceWithoutDelayedWithFragment()
        {
            CleanOutput();

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory, 2, false, 1400000))
            {
                AdvancedTrace.AddTraceListener(AdvancedTrace.ListenerType.All, logStorage);

                var stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();

                for (var j = 0; j < 100000; j++)
                {
                    AdvancedTrace.TraceInformation("MyInformation " + j, "Info");
                }

                logStorage.Flush();

                stopWatch.Stop();
                var ts = stopWatch.Elapsed;
                System.Diagnostics.Debug.WriteLine("Time Execute Trace :" + $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}");

                AdvancedTrace.RemoveTraceListener(AdvancedTrace.ListenerType.All, logStorage);
            }

            var fileNames = Directory.GetFiles(CurrentDirectory, "*.xml").Select(p => new { FilePath = p, FileName = Path.GetFileName(p) }).OrderBy(p => p.FileName.Length).ThenBy(p => p.FileName).ToList();

            Assert.That(fileNames.Count, Is.EqualTo(10));
            for (var i = 0; i < fileNames.Count; i++)
            {
                Assert.That(fileNames[i].FileName, Is.EqualTo($"Working_session_1_{i + 1}.xml"));
                var xmlDoc = new XmlDocument();
                xmlDoc.Load(fileNames[i].FilePath);
            }
        }
Пример #9
0
        static TraceManager()
        {
            string logDirectoryPath = Path.Combine(
                Environment.GetFolderPath(Environment.SpecialFolder.ApplicationData),
                Resources.ProductName,
                "log");
            string logFilePath = Path.Combine(
                logDirectoryPath,
                string.Format("log_{0}.svclog", Guid.NewGuid()));

            if (!Directory.Exists(logDirectoryPath))
            {
                Directory.CreateDirectory(logDirectoryPath);
            }

            var traceListener = new XmlWriterTraceListener(logFilePath)
            {
                TraceOutputOptions = TraceOptions.DateTime
            };

            System.Diagnostics.Trace.AutoFlush = true;
            System.Diagnostics.Trace.Listeners.Add(traceListener);

            // Tracing binding errors
            PresentationTraceSources.DataBindingSource.Listeners.Add(new BindingErrorListener());
            PresentationTraceSources.DataBindingSource.Switch.Level = SourceLevels.Error;
        }
Пример #10
0
        public void StressTrace1ThreadAnd100000TraceWithoutDelayed()
        {
            CleanOutput();

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory, 2, false))
            {
                AdvancedTrace.AddTraceListener(AdvancedTrace.ListenerType.All, logStorage);

                var stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();

                for (var j = 0; j < 100000; j++)
                {
                    AdvancedTrace.TraceInformation("MyInformation " + j, "Info");
                }

                logStorage.Flush();

                stopWatch.Stop();
                var ts = stopWatch.Elapsed;
                System.Diagnostics.Debug.WriteLine("Time Execute Trace :" + $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}");

                AdvancedTrace.RemoveTraceListener(AdvancedTrace.ListenerType.All, logStorage);
            }

            var xmlDoc = new XmlDocument();

            xmlDoc.Load(Path.Combine(CurrentDirectory, "Working_session_1_1.xml"));
        }
        public void WriteTest(string message, string expectedXml)
        {
            string file = GetTestFilePath();

            DateTime date;

            using (var listener = new XmlWriterTraceListener(file))
            {
                // Let's cache the date right before creating the trace so that later on we don't get different values if for some reason teh date changed.
                date = DateTime.Now;
                listener.Write(message);
            }


            var document = new XmlDocument();

            document.Load(file);

            ValidateSystemInfo(document, "0", TraceEventType.Information, date, null);

            XmlNode node = document.GetElementsByTagName("ApplicationData")[0];

            Assert.Equal(expectedXml, node.InnerXml);
            Assert.Equal(message, node.InnerText);
        }
Пример #12
0
 public static void LogError(Exception ex)
 {
     using (XmlWriterTraceListener log = new XmlWriterTraceListener("./TraceEvent.log"))
     {
         log.TraceEvent(new TraceEventCache(), ex.Message, TraceEventType.Error, ex.HResult);
         log.Flush();
     }
 }
Пример #13
0
        public static void LogError(string errorMsg)
        {
            XmlWriterTraceListener listener = new XmlWriterTraceListener("./Error.log");

            listener.WriteLine(errorMsg);
            listener.Flush();
            listener.Close();
        }
Пример #14
0
        public void ListenerWithFilter()
        {
            // Ensure we use an arbitrary ID that doesn't match the process ID or thread ID.
            int traceTransferId = 1;

            using (Process p = Process.GetCurrentProcess())
            {
                while (traceTransferId == p.Id || traceTransferId == Environment.CurrentManagedThreadId)
                {
                    traceTransferId++;
                }
            }

            string file = GetTestFilePath();
            Guid   guid = Guid.NewGuid();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.Filter = new EventTypeFilter(SourceLevels.Error);
                listener.Write("Hello");
                listener.Fail("Goodbye");

                listener.Filter = new EventTypeFilter(SourceLevels.Critical);
                listener.Fail("InexistentFailure");
                listener.TraceEvent(null, "Trace", TraceEventType.Information, 1, "format", null);
                listener.TraceData(null, "Trace", TraceEventType.Critical, 1, "shouldbehere");
                listener.TraceData(null, "Trace", TraceEventType.Error, 1, "shouldnotbehere");
                listener.TraceData(null, "Trace", TraceEventType.Error, 1, "ghost", "not", "here");
                listener.TraceData(null, "Trace", TraceEventType.Critical, 1, "existent", ".net", "code");

                listener.TraceTransfer(null, "Transfer", traceTransferId, "this is a transfer", guid);
            }

            string text = File.ReadAllText(file);

            Assert.Contains("Goodbye", text);
            Assert.DoesNotContain("Hello", text);
            Assert.DoesNotContain("InexistentFailure", text);
            Assert.DoesNotContain("format", text);
            Assert.Contains("shouldbehere", text);
            Assert.DoesNotContain("shouldnotbehere", text);

            Assert.DoesNotContain("<DataItem>ghost</DataItem>", text);
            Assert.DoesNotContain("<DataItem>not</DataItem>", text);
            Assert.DoesNotContain("<DataItem>here</DataItem>", text);
            Assert.Contains("<DataItem>existent</DataItem><DataItem>.net</DataItem><DataItem>code</DataItem>", text);

            if (!PlatformDetection.IsFullFramework)
            {
                // Desktop has a boolean to turn on filtering in TraceTransfer due to a bug.
                // https://referencesource.microsoft.com/#System/compmod/system/diagnostics/XmlWriterTraceListener.cs,26
                Assert.DoesNotContain('"' + traceTransferId.ToString(CultureInfo.InvariantCulture) + '"', text);
                Assert.DoesNotContain("this is a transfer", text);
                Assert.DoesNotContain("Transfer", text);
                Assert.DoesNotContain(guid.ToString("B"), text);
            }
        }
Пример #15
0
        public void WriteLine1()
        {
            StringWriter           sw = new StringWriter();
            XmlWriterTraceListener x  = new XmlWriterTraceListener(sw);

            x.WriteLine("sample");
            x.Close();
            Assert.AreEqual(sample1.Replace('\'', '"'), sw.ToString());
        }
Пример #16
0
        public void TraceEvent2()
        {
            StringWriter           sw = new StringWriter();
            XmlWriterTraceListener x  = new XmlWriterTraceListener(sw);

            x.TraceEvent(null, "bulldog", TraceEventType.Error, 5);
            x.Close();
            Assert.AreEqual(sample3.Replace('\'', '"'), sw.ToString());
        }
Пример #17
0
        public void TraceTransfer1()
        {
            StringWriter           sw = new StringWriter();
            XmlWriterTraceListener x  = new XmlWriterTraceListener(sw);

            x.TraceTransfer(null, "bulldog", 0, "hoge", Guid.Empty);
            x.Close();
            Assert.AreEqual(sample6.Replace('\'', '"'), sw.ToString());
        }
Пример #18
0
        //------------------------------------------------------------------------------------------------------
        #endregion
        //------------------------------------------------------------------------------------------------------
        #region Constructors and Destructors
        //------------------------------------------------------------------------------------------------------
        /// <summary>
        /// Конструктор
        /// </summary>
        /// <remarks>Файл всегда находится в папке приложения и называетя AppXmlLog.xml</remarks>
        private XmlLog()
        {
            // Получаем путь к папке приложения (.exe)
            String pathToLogFile = Environment.CurrentDirectory;

            this._Log =
                new XmlWriterTraceListener(pathToLogFile + "AppXmlLog.xml", "AppXmlLog");
            // Добавляем его в коллекцию
            Trace.Listeners.Add(_Log);
        }
Пример #19
0
        public void Fail1()
        {
            StringWriter           sw = new StringWriter();
            XmlWriterTraceListener x  = new XmlWriterTraceListener(sw);
            TraceEventCache        cc = new TraceEventCache();

            x.Fail("error summary", "error details");
            x.Close();
            Assert.AreEqual(sample7.Replace('\'', '"'), sw.ToString());
        }
Пример #20
0
        public void TraceDataWithCache1()
        {
            StringWriter           sw = new StringWriter();
            XmlWriterTraceListener x  = new XmlWriterTraceListener(sw);
            TraceEventCache        cc = new TraceEventCache();

            x.TraceData(cc, null, TraceEventType.Error, 2);
            x.TraceData(cc, null, TraceEventType.Error, 3);
            x.Close();
            Assert.AreEqual(sample4.Replace('\'', '"'), sw.ToString());
        }
        public void Close_NoWriteSuccess()
        {
            string file = GetTestFilePath();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.Close();
                listener.Write("Hello");
            }

            Assert.False(File.Exists(file));
        }
Пример #22
0
        public void InstanciationVerifyCreationDirectory()
        {
            CleanOutput();

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory))
            {
                logStorage.WriteLineEx("Test", "1");
                logStorage.Flush();

                var nbDirectoryWithCurrentDay = Directory.GetDirectories(logStorage.BaseRootPath).Count(p => Path.GetFileName(p) == DateTime.Now.ToString("yyyy-MM-dd"));
                Assert.IsTrue(nbDirectoryWithCurrentDay == 1, "Nb Directory With Current Day Name : " + nbDirectoryWithCurrentDay);
            }
        }
        public static TraceSource CreateTraceSource()
        {
            var traceSource = new TraceSource("MockLanguageExtension", SourceLevels.Verbose | SourceLevels.ActivityTracing);

            var traceFileDirectoryPath = Path.Combine(Path.GetTempPath(), "VisualStudio", "LSP");
            var logFilePath            = Path.Combine(traceFileDirectoryPath, "MockLog.svclog");
            var traceListener          = new XmlWriterTraceListener(logFilePath);

            traceSource.Listeners.Add(traceListener);

            Trace.AutoFlush = true;

            return(traceSource);
        }
Пример #24
0
        public void Instanciation5FileCreateFor5Instanciation()
        {
            CleanOutput();

            for (var i = 1; i <= 5; i++)
            {
                var pathFileSession = Path.Combine(CurrentDirectory, "Working_session_" + i + "_1.xml");

                using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory))
                    logStorage.WriteLineEx("Test", "1");

                Assert.IsTrue(File.Exists(pathFileSession));
            }
        }
        public void StressTrace10ThreadAnd10000TraceWithDelayedWithFragment()
        {
            CleanOutput();

            System.Diagnostics.Debug.WriteLine("DirectoryCreated");

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory, 2, true, 1400000))
            {
                AdvancedTrace.AddTraceListener(AdvancedTrace.ListenerType.All, logStorage);
                var tasks = new List <Task>();

                System.Diagnostics.Debug.WriteLine("Listener added");

                var stopWatch = new System.Diagnostics.Stopwatch();
                stopWatch.Start();
                for (var i = 0; i < 10; i++)
                {
                    var i1 = i;
                    tasks.Add(Task.Factory.StartNew(() =>
                    {
                        for (var j = 0; j < 10000; j++)
                        {
                            AdvancedTrace.TraceInformation("MyInformation " + i1 + " " + j, "Info");
                        }
                    }));
                }

                logStorage.Flush();

                Task.WaitAll(tasks.ToArray());

                System.Diagnostics.Debug.WriteLine("Tasks finished added");

                stopWatch.Stop();
                var ts = stopWatch.Elapsed;
                System.Diagnostics.Debug.WriteLine("Time Execute Trace :" + $"{ts.Hours:00}:{ts.Minutes:00}:{ts.Seconds:00}.{ts.Milliseconds / 10:00}");

                Thread.Sleep(31000);

                var fileNames = Directory.GetFiles(CurrentDirectory, "*.xml").Select(p => new { FilePath = p, FileName = Path.GetFileName(p) }).OrderBy(p => p.FileName.Length).ThenBy(p => p.FileName).ToList();

                Assert.That(fileNames.Count, Is.EqualTo(10));
                for (var i = 0; i < fileNames.Count; i++)
                {
                    Assert.That(fileNames[i].FileName, Is.EqualTo($"Working_session_1_{i + 1}.xml"));
                    var xmlDoc = new XmlDocument();
                    xmlDoc.Load(fileNames[i].FilePath);
                }
            }
        }
Пример #26
0
        public void Check1TraceWarningWithoutDelayed()
        {
            CleanOutput();

            using (var logStorage = new XmlWriterTraceListener("Application 1", AppDomain.CurrentDomain.BaseDirectory, 2, false))
            {
                AdvancedTrace.AddTraceListener(AdvancedTrace.ListenerType.All, logStorage);
                AdvancedTrace.TraceWarning("MyWarning", "Info");

                AdvancedTrace.RemoveTraceListener(AdvancedTrace.ListenerType.All, logStorage);
            }
            var xmlDoc = new XmlDocument();

            xmlDoc.Load(Path.Combine(CurrentDirectory, "Working_session_1_1.xml"));
        }
Пример #27
0
        public void XPathNavigatorAsData()
        {
            // While XmlReader, XmlDocument and XDocument are not supported as direct xml content (i.e. to not get escaped), XPathNavigator is.
            var    sw  = new StringWriter();
            var    xl  = new XmlWriterTraceListener(sw);
            var    doc = new XmlDocument();
            string xml = "<root><child xmlns=\"urn:foo\">text</child></root>";

            doc.LoadXml(xml);
            xl.TraceData(null, "my source", TraceEventType.Information, 1, doc.CreateNavigator(), doc.CreateNavigator());
            // Note that it does not result in "<root xmlns=''>...".
            // See XmlWriterTraceListener.TraceCore() for details.
            Assert.IsTrue(sw.ToString().IndexOf(xml) > 0, "#1");
            Assert.IsTrue(sw.ToString().IndexOf("</DataItem><DataItem>") > 0, "#2");
        }
        public void Close_WriteBeforeAndAfter()
        {
            string file = GetTestFilePath();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.Write("Hello");
                listener.Close();
                listener.Write("Goodbye");
            }

            string text = File.ReadAllText(file);

            Assert.Contains("Hello", text);
            Assert.DoesNotContain("Goodbye", text);
        }
        public void Close_AfterXPathNavigatorTraced()
        {
            string xml1 = "<Error xmlns=\"http://schemas.microsoft.com/2004/06/E2ETraceEvent\">" +
                          "<Info>Exception thrown</Info>" +
                          "<Detail>Failed when trying to connect to server</Detail>" +
                          "</Error>";
            XPathNavigator navigator1 = XDocument.Parse(xml1).CreateNavigator();

            string file = GetTestFilePath();

            using (var listener = new XmlWriterTraceListener(file))
            {
                // shouldn't fail.
                listener.TraceData(null, "Trace", TraceEventType.Information, 100, navigator1);
                listener.Close();
            }
        }
Пример #30
0
        public void ListenerWithFilter()
        {
            string file = GetTestFilePath();
            Guid   guid = Guid.NewGuid();

            using (var listener = new XmlWriterTraceListener(file))
            {
                listener.Filter = new EventTypeFilter(SourceLevels.Error);
                listener.Write("Hello");
                listener.Fail("Goodbye");

                listener.Filter = new EventTypeFilter(SourceLevels.Critical);
                listener.Fail("InexistentFailure");
                listener.TraceEvent(null, "Trace", TraceEventType.Information, 1, "format", null);
                listener.TraceData(null, "Trace", TraceEventType.Critical, 1, "shouldbehere");
                listener.TraceData(null, "Trace", TraceEventType.Error, 1, "shouldnotbehere");
                listener.TraceData(null, "Trace", TraceEventType.Error, 1, "ghost", "not", "here");
                listener.TraceData(null, "Trace", TraceEventType.Critical, 1, "existent", ".net", "code");

                listener.TraceTransfer(null, "Transfer", 2304, "this is a transfer", guid);
            }

            string text = File.ReadAllText(file);

            Assert.Contains("Goodbye", text);
            Assert.DoesNotContain("Hello", text);
            Assert.DoesNotContain("InexistentFailure", text);
            Assert.DoesNotContain("format", text);
            Assert.Contains("shouldbehere", text);
            Assert.DoesNotContain("shouldnotbehere", text);

            Assert.DoesNotContain("<DataItem>ghost</DataItem>", text);
            Assert.DoesNotContain("<DataItem>not</DataItem>", text);
            Assert.DoesNotContain("<DataItem>here</DataItem>", text);
            Assert.Contains("<DataItem>existent</DataItem><DataItem>.net</DataItem><DataItem>code</DataItem>", text);

            if (!PlatformDetection.IsFullFramework)
            {
                // Desktop has a boolean to turn on filtering in TraceTransfer due to a bug.
                // https://referencesource.microsoft.com/#System/compmod/system/diagnostics/XmlWriterTraceListener.cs,26
                Assert.DoesNotContain("2304", text);
                Assert.DoesNotContain("this is a transfer", text);
                Assert.DoesNotContain("Transfer", text);
                Assert.DoesNotContain(guid.ToString("B"), text);
            }
        }