示例#1
0
        //----------------------------------------------------------------------------
        #endregion

        #region Methods
        //----------------------------------------------------------------------------
        /// <summary>
        /// Создаёт объетк журнала событий на основе свойств
        /// </summary>
        private void CreateLog()
        {
            if (_Logger != null)
            {
                _Logger.Close();
                _Logger.Filter = null;
            }

            _Logger = new TextWriterTraceListener(_PathToLogFile);

            Trace.Listeners.Clear();
            Trace.Listeners.Add(_Logger);
            Trace.AutoFlush = true;
            Trace.TraceInformation(String.Empty); // Для форматирования текста, отделяет сессию от сесии
            Trace.TraceInformation("{0}: {1} Старт сессии",
                                   DateTime.Now.ToShortDateString(), DateTime.Now.ToLongTimeString());
            Process prs = Process.GetCurrentProcess();

            Trace.TraceInformation("{0}: ID процесса: {1}",
                                   DateTime.Now.ToLongTimeString(), prs.Id);
            Trace.TraceInformation("{0}: Наименование процесса: {1}",
                                   DateTime.Now.ToLongTimeString(), prs.ProcessName);
            Trace.TraceInformation("{0}: Приоритет потка: {1}",
                                   DateTime.Now.ToLongTimeString(), prs.PriorityClass);
            Thread thread = Thread.CurrentThread;

            Trace.TraceInformation("{0}: ID потка: {1}",
                                   DateTime.Now.ToLongTimeString(), thread.ManagedThreadId);
            Trace.TraceInformation("{0}: Наименование потока: {1}",
                                   DateTime.Now.ToLongTimeString(), thread.Name);
            Trace.TraceInformation("{0}: Приоритет потока: {1}",
                                   DateTime.Now.ToLongTimeString(), thread.Priority);

            return;
        }
        public JobOutcome Execute(IJobProcessorServices context, IJob job)
        {
            try
            {
                FileInfo mLogFileInfo = new FileInfo(System.IO.Path.Combine(
                                                         mLogDir, mLogFile));
                if (mLogFileInfo.Exists)
                {
                    mLogFileInfo.Delete();
                }
                mTrace.WriteLine("Starting Job...");

                //start step export
                mCreateExport(context, job);

                mTrace.IndentLevel = 0;
                mTrace.WriteLine("... successfully ending Job.");
                mTrace.Flush();
                mTrace.Close();

                return(JobOutcome.Success);
            }
            catch (Exception ex)
            {
                context.Log(ex, "Autodesk.STEP.ExportSampleJob failed: " + ex.ToString() + " ");

                mTrace.IndentLevel = 0;
                mTrace.WriteLine("... ending Job with failures.");
                mTrace.Flush();
                mTrace.Close();

                return(JobOutcome.Failure);
            }
        }
示例#3
0
        public void resetTraceCounterToOne()
        {
            traceCounter = 1;

            traceLog.Flush(); // flush & close trace log file to be opened for review
            traceLog.Close();

            traceLog = new TextWriterTraceListener(System.IO.File.CreateText("trace.log"));
            Debug.Listeners.Add(traceLog);
        }
示例#4
0
        public void TestPenDoSomethingElse(int sizeInk, double sizeLetter, string color, string nameTxtFile)
        {
            result = "";
            pen    = new Pen(sizeInk, sizeLetter, color);
            using (TextWriter writer = File.CreateText(nameTxtFile))
            {
                TextWriterTraceListener trcListener = new TextWriterTraceListener(writer);
                Debug.Listeners.Add(trcListener);
                pen.doSomethingElse();
                Debug.Flush();
                trcListener.Close();
            }
            FileStream file = new FileStream(nameTxtFile, FileMode.Open, FileAccess.ReadWrite, FileShare.None);

            using (StreamReader sr = new StreamReader(file, System.Text.Encoding.Default))
            {
                while (!sr.EndOfStream)
                {
                    result = sr.ReadLine();
                }
            }
            file.Close();
            File.Delete(nameTxtFile);
            Assert.AreEqual(color, result);
        }
示例#5
0
        public void LogToAllDestinations()
        {
            // Set up binary file destination.
            Logger.DefaultBinaryFile.Name = "AllDestinationsBinaryFileOut";
            Logger.DefaultBinaryFile.CircularStartDelaySeconds = 0;
            Logger.DefaultBinaryFile.CircularStartSizeKb       = 1;
            Logger.DefaultBinaryFile.MaxSizeMb = 1;
            Logger.Root.BinaryFileTraceLevel   = TracerX.TraceLevel.Verbose;
            Logger.DefaultBinaryFile.Open();
            MessageBox.Show("Opened " + Path.Combine(Logger.DefaultBinaryFile.Directory, Logger.DefaultBinaryFile.Name));

            // Set up Debug (Trace) listener destination.
            TextWriterTraceListener myTextListener = SetupTraceListener("AllDestinationsDebugOut.txt");

            // Set up EventHandler destination.
            SetupEventHandler();

            // Set up the text file destination.
            Log.TextFileTraceLevel      = TracerX.TraceLevel.Verbose;
            Logger.DefaultTextFile.Name = "AllDestinationsTextFileOut.txt";
            Logger.DefaultTextFile.Open();
            MessageBox.Show("Opened " + Path.Combine(Logger.DefaultTextFile.Directory, Logger.DefaultTextFile.Name));

            // Set up the event log destination
            Logger.Root.EventLogTraceLevel      = TracerX.TraceLevel.Verbose;
            Logger.EventLogging.EventLog.Source = "TracerX - All Destinations";

            // Generate some output.
            random = new Random();
            RandomCall();

            // Close output files.
            myTextListener.Writer.Close();
            myTextListener.Close();
        }
示例#6
0
        static void Main(string[] args)
        {
            var consoleTraceListener = new TextWriterTraceListener(Console.Out);

            Trace.Listeners.Add(consoleTraceListener);

            try
            {
                ArgumentsValidation(args);

                using (var connection = new Connection(Address.ToString(), Port))
                {
                    Controller controller = new Controller(connection);

                    //await controller.Process().ConfigureAwait(false); //This requires C# 7.1 or later, TeamCity build and packaging is not using this yet.
                    controller.Process().Wait();
                }
            }
            catch (System.Exception ex)
            {
                Trace.WriteLine(ex.Message);
                Trace.WriteLine($"Exception Details: \n {ex.StackTrace}");
            }
            finally
            {
                Trace.Flush();
                Trace.Listeners.Remove(consoleTraceListener);
                consoleTraceListener.Close();
                Trace.Close();
            }
        }
示例#7
0
文件: Program.cs 项目: Marceli/MSTest
        private static void DisplayResults()
        {
            watch.Reset();

            watch.Start();

            var results = messageProcessor.Results;

            watch.Stop();
            var histogram = results.GroupBy(m => m.Despathes).OrderBy(g => g.Key);

            SetUpListeners();
            //histogram.Select(g => string.Format("{0}    {1}", g.Key, g.Count())).ToList().ForEach(PrintHistogram);
            Trace.WriteLine("Maximum despaches is:" + results.GroupBy(m => m.Despathes).Max(g => g.Key));
            Trace.WriteLine("Minimum despaches is:" + results.GroupBy(m => m.Despathes).Min(g => g.Key));
            Trace.WriteLine(string.Format("Avaerage despaches is:{0:0.000}", results.Average(m => m.Despathes)));


            Trace.WriteLine(string.Format("Run time: {0:00}:{1:00}:{2:00}.{3:000}",
                                          watch.Elapsed.Hours,
                                          watch.Elapsed.Minutes,
                                          watch.Elapsed.Seconds,
                                          watch.Elapsed.Milliseconds));
            Console.WriteLine("Results are stored in {0} file.", fileName);
            textWriterTraceListener.Close();
            myEvent.Signal();
        }
示例#8
0
            public void Invoke()
            {
                try
                {
                    using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log"))
                    {
                        Trace.Listeners.Add(dbg);
                        Trace.Listeners.Add(new ConsoleTraceListener());

                        _main.Invoke(null, null);

                        dbg.Flush();
                        dbg.Close();
                    }
                }
                catch (TargetInvocationException expt)
                {
                    string ex_info;
                    if (expt.InnerException != null)
                    {
                        ex_info = expt.InnerException.ToString();
                    }
                    else
                    {
                        ex_info = expt.ToString();
                    }
                    //MessageBox.Show(ex_info, "An OpenTK example encountered an error.", MessageBoxButtons.OK, MessageBoxIcon.Warning);

                    Trace.WriteLine(ex_info.ToString());
                }
                catch (Exception expt)
                {
                    Trace.WriteLine(expt.ToString());
                }
            }
示例#9
0
        // </Snippet2>

        static void Main()
        {
            // Create a file for trace output.
            // A new file is created each time.  If a
            // previous log file exists, it is overwritten.
            StreamWriter myFile = File.CreateText(logFile);

            // Create a new trace listener writing to the text file,
            // and add it to the trace listeners.
            serviceTraceListener = new TextWriterTraceListener(myFile);
            Trace.Listeners.Add(serviceTraceListener);

            Trace.AutoFlush = true;
            Trace.WriteLine(DateTime.Now.ToLongTimeString() +
                            " - Service main method starting...",
                            "Main");

            // Load the service into memory.
            System.ServiceProcess.ServiceBase.Run(new SimpleService());

            Trace.WriteLine(DateTime.Now.ToLongTimeString() +
                            " - Service main method exiting...",
                            "Main");

            // Remove and close the trace listener for this service.
            Trace.Listeners.Remove(serviceTraceListener);

            serviceTraceListener.Close();
            serviceTraceListener = null;
            myFile.Close();
        }
示例#10
0
        private void WriteLine(string message, Exception exception)
        {
            if (listener != null)
            {
#if NETSTANDARD || DXCORE3
                if (listener.Writer == null)
                {
                    Stream fileStream = new FileStream(filename, FileMode.Append);
                    listener = new TextWriterTraceListener(fileStream, TraceListenerName);
                }
#endif
                listener.WriteLine(message);
                listener.Close();
            }
#if !NETSTANDARD && !NETCOREAPP
            else if (HasUnmanagedCodePermission)
            {
#else
            else
            {
#endif
                if (exception != null)
                {
                    string resultText = message.Replace("{", "{{").Replace("}", "}}");
                    Trace.TraceError(resultText, exception);
                }
                else
                {
                    Trace.WriteLine(message);
                }
            }
        }
        public static void LogException(string category, Exception exc)
        {
            string absolute_path = Path.Combine(Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase), Properties.Settings.Default.LogPath);
            Uri    uri           = new Uri(absolute_path);
            string path          = Path.GetFullPath(uri.AbsolutePath);

            if (!Directory.Exists(Path.GetDirectoryName(path)))
            {
                Directory.CreateDirectory(Path.GetDirectoryName(path));
            }
            TextWriterTraceListener listener = new TextWriterTraceListener(path);

            Trace.Listeners.Add(listener);

            Trace.WriteLine("SNMP Manager Exception");
            Trace.Indent();
            Trace.WriteLine("ExceptionType: " + exc.GetType().ToString());
            Trace.WriteLine("Category: " + category);
            Trace.WriteLine("Timestamp: " + DateTime.Now.ToString());
            Trace.WriteLine("HResult" + exc.HResult);
            Trace.WriteLine("Message: " + exc.Message);
            Trace.WriteLine("StackTrace: " + exc.StackTrace);
            Trace.Unindent();
            Trace.WriteLine("End Exception SNMP Manager");
            Trace.WriteLine("----");
            listener.Flush();
            listener.Close();
        }
        private void WriteLine(string message, Exception exception)
        {
            if (listener != null)
            {
                listener.WriteLine(message);
                listener.Close();
            }
#if !NETSTANDARD && !NETCOREAPP
            else if (HasUnmanagedCodePermission)
            {
#else
            else
            {
#endif
                if (exception != null)
                {
                    string resultText = message.Replace("{", "{{").Replace("}", "}}");
                    Trace.TraceError(resultText, exception);
                }
                else
                {
                    Trace.WriteLine(message);
                }
            }
        }
示例#13
0
        public static void LogExceptionToFile(Exception ex)
        {
            var logPath      = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);
            var logDirectory = logPath + @"\EXCEPTION";
            var filePath     = "";

            if (!Directory.Exists(logDirectory))
            {
                Directory.CreateDirectory(logDirectory);
                filePath = logDirectory + @"\EXCEPTION.0.log";
            }
            else
            {
                var filePaths = Directory.GetFiles(logDirectory, "*.log");
                if (filePaths.Length == 0)
                {
                    filePath = logDirectory + @"\EXCEPTION.0.log";
                }
                else
                {
                    var fPath = filePaths[filePaths.Length - 1];
                    if (File.Exists(fPath))
                    {
                        var lastestFile = new FileInfo(fPath);
                        // > 2 MB
                        if (((lastestFile.Length / 1024f) / 1024f) > 2)
                        {
                            var file     = new FileInfo(fPath);
                            var fileName = file.Name.Split('.');
                            filePath = logDirectory + @"\EXCEPTION." + (int.Parse(fileName[1]) + 1) + @".log";
                        }
                        else
                        {
                            filePath = fPath;
                        }
                    }
                }
            }

            var a          = Environment.NewLine;
            var logMessage = string.Concat(new object[]
            {
                ex.Message,
                Environment.NewLine,
                ex.Source,
                Environment.NewLine,
                ex.StackTrace,
                Environment.NewLine,
                ex.TargetSite,
                Environment.NewLine,
                ex.InnerException
            });

            logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage;
            var listener = new TextWriterTraceListener(filePath);

            listener.WriteLine(logMessage);
            listener.Flush();
            listener.Close();
        }
示例#14
0
        public static void Dispose()
        {
            if (ts != null)
            {
                ts.Flush();
                ts.Close();
                StopTimer();

                objStream.Close();
                objStream.Dispose();
                try
                {
                    objTraceListener.Close();
                    objTraceListener.Dispose();
                }
                catch
                {
                }

                if (File.Exists(logFileName))
                {
                    FileStream file = new FileStream(logFileName, FileMode.OpenOrCreate, FileAccess.Write);
                    file.Close();
                }
            }
        }
    public static void Main()
    {
        TextWriterTraceListener myWriter = new
                                           TextWriterTraceListener(System.Console.Out);

        Debug.Listeners.Add(myWriter);
        Debug.WriteLine("Test output 1 ");
        Stream myFile = File.Create("output.txt");
        TextWriterTraceListener myTextListener = new
                                                 TextWriterTraceListener(myFile);

        Debug.Listeners.Add(myTextListener);
        Debug.WriteLine("Test output 2 ");


        if (!EventLog.SourceExists("Demo"))
        {
            EventLog.CreateEventSource("Demo", "Demo");
        }


        Debug.Listeners.Add(new EventLogTraceListener("Demo"));
        Debug.WriteLine("Test output 3 ");
        myWriter.Flush();
        myWriter.Close();
        myFile.Flush();
        myFile.Close();
    }
示例#16
0
        public void Write(FormatterBase formatter, string logFileName)
        {
            TextWriterTraceListener listener = new TextWriterTraceListener(logFileName);

            listener.WriteLine(formatter.Message);
            listener.Flush();
            listener.Close();
        }
 protected void FinishDebug()
 {
     if (myTextListener != null)
     {
         myTextListener.Flush();
         myTextListener.Close();
     }
 }
示例#18
0
        /**********************************************************************************************//**
        * Closes log files.
        *
        * \author  Ilan Hindy
        * \date    29/09/2016
        *
        **************************************************************************************************/

        private static void CloseLogFiles()
        {
            if (traceListener != null)
            {
                traceListener.Flush();
                Trace.Listeners.Remove(traceListener);
                traceListener.Close();
            }

            foreach (TextWriterTraceListener listener in processLogFiles.Values)
            {
                listener.Flush();
                Trace.Listeners.Remove(listener);
                listener.Close();
            }
            processLogFiles.Clear();
        }
示例#19
0
        ///<summary>
        /// Implement this method as an external command for Revit.
        /// </summary>
        /// <param name="commandData">An object that is passed to the external application
        /// which contains data related to the command,
        /// such as the application object and active view.</param>
        /// <param name="message">A message that can be set by the external application
        /// which will be displayed if a failure or cancellation is returned by
        /// the external command.</param>
        /// <param name="elements">A set of elements to which the external application
        /// can add elements that are to be highlighted in case of failure or cancellation.</param>
        /// <returns>Return the status of the external command.
        /// A result of Succeeded means that the API external method functioned as expected.
        /// Cancelled can be used to signify that the user cancelled the external operation
        /// at some point. Failure should be returned if the application is unable to proceed with
        /// the operation.</returns>
        public Autodesk.Revit.UI.Result Execute(ExternalCommandData commandData,
                                                ref string message, Autodesk.Revit.DB.ElementSet elements)
        {
            string assemblyLocation = Assembly.GetExecutingAssembly().Location;
            string log = assemblyLocation + "." + DateTime.Now.ToString("yyyyMMdd") + ".log";

            if (File.Exists(log))
            {
                File.Delete(log);
            }
            TraceListener txtListener = new TextWriterTraceListener(log);

            Trace.Listeners.Add(txtListener);
            try
            {
                // variable initialization
                m_application = commandData.Application.Application;
                m_document    = commandData.Application.ActiveUIDocument.Document;
                Environment.CurrentDirectory = Path.GetDirectoryName(assemblyLocation);

                FindRoomBoundingRoofs(ref message, elements);

                // Not show TaskDialog in regression mode
                if (0 == commandData.JournalData.Count)
                {
                    TaskDialog.Show("Roofs Rooms", message);
                }

                // Insert result to journal data for regression purpose.
                const string DataKey = "Results";
                if (!commandData.JournalData.ContainsKey(DataKey))
                {
                    // In normal/recording mode
                    commandData.JournalData.Add(DataKey, message);
                }
                else
                {
                    // In regression/replaying mode
                    commandData.JournalData[DataKey] = message;
                }

                return(Autodesk.Revit.UI.Result.Succeeded);
            }
            catch (Exception ex)
            {
                Trace.WriteLine(ex.ToString());
                message = ex.ToString();
                return(Autodesk.Revit.UI.Result.Failed);
            }
            finally
            {
                Trace.Flush();
                txtListener.Close();
                Trace.Close();
                Trace.Listeners.Remove(txtListener);
            }
        }
示例#20
0
        /**********************************************************************************************//**
        * Closes edit log file.
        *
        * \author  Ilan Hindy
        * \date    16/01/2017
        **************************************************************************************************/

        public static void CloseEditLogFile()
        {
            if (editTraceListener != null)
            {
                editTraceListener.Flush();
                Trace.Listeners.Remove(editTraceListener);
                editTraceListener.Close();
            }
        }
示例#21
0
        /// <summary>
        /// Write trace information to disk
        /// </summary>
        public void Close()
        {
            if (_textWriterTraceListener == null)
            {
                return;
            }

            _textWriterTraceListener.Flush();
            _textWriterTraceListener.Close();
        }
示例#22
0
        private static void handleUnhandledException(Exception exc)
        {
            bool useHandler = true;

            Trace.WriteLine(exc.ToString());
            if (useHandler)
            {
                FUnhandledExceptionHandler handler = new FUnhandledExceptionHandler(exc);
                handler.ApplicationName    = AssemblyTitle;
                handler.ApplicationVersion = Assembly.GetExecutingAssembly().GetName().Version;
                if (app != null)
                {
                    try
                    {
                        if (app.CommonCode.CurrentFilename != null)
                        {
                            handler.CurrentFilename.Add(app.CommonCode.CurrentFilename);
                        }
                    }
                    catch (NullReferenceException)
                    {
                    }
                }
                if (listener != null)
                {
                    try
                    {
                        Debug.Listeners.Remove(listener);
                        listener.Close();
                        listener.Dispose();
                        handler.CurrentFilename.Add(traceFile);
                    }
                    catch (Exception excLocal)
                    {
                        Trace.WriteLine(excLocal.ToString());
                    }
                }
                if (Application.MessageLoop)
                {
                    handler.Show();
                }
                else
                {
                    Application.Run(handler);
                }
            }
            else
            {
                MessageBox.Show("Ett allvarligt fel har uppstått: \"" + exc.ToString() + "\"",
                                "Major Failure",
                                MessageBoxButtons.OK,
                                MessageBoxIcon.Stop);
            }
            //Application.Exit();
        }
示例#23
0
        public string HelloWorld()
        {
            TextWriterTraceListener list;

            Debug.Listeners.Add(list = new TextWriterTraceListener(Server.MapPath("../TraceLog1.txt")));
            Debug.Write("hello world " + DateTime.Now.ToString());
            Debug.Listeners.Remove(list);
            list.Close();
            list.Dispose();
            return("Hello World");
        }
示例#24
0
 /// <summary>
 /// Stop logging.
 /// </summary>
 public void StopLogging()
 {
     if (m_Listener != null)
     {
         DiagnosticsHelper.LogMessage(DiagSeverity.Information, "Logging disabled");
         Trace.Listeners.Remove(m_Listener);
         m_Listener.Flush();
         m_Listener.Close();
         m_Listener = null;
     }
 }
示例#25
0
        public async Task TestFilters()
        {
            // While this seems ideal for a Theory test case, the IEnumerable<Product> would need to be serialize-able in
            // order to generate an Xunit 2.0 test case.
            var testCases = SpecialCharacterData
                            .Union(OperatorData)
                            .Union(StringFunctionData)
                            .Union(DateAndTimeOfDayData);

            //.Union(MixQueries) 1559
            //.Union*AdHocTests);

            foreach (var testCase in testCases)
            {
                string filter = (string)testCase[0];
                IEnumerable <Product> expected = (IEnumerable <Product>)testCase[1];

                var requestUri = this.BaseAddress + "/api/FilterTests/GetProducts?$filter=" + filter;

                var response = await this.Client.GetAsync(requestUri);

                if (response.StatusCode != HttpStatusCode.OK)
                {
                    /*
                     * This if statement is added due to that the test data is generated randomly, and sometimes the test case fails on CI,
                     * but we have no way to investigate as both the request and response are not logged.
                     */

                    // C:\Users\{user}\AppData\Local\Temp\
                    var now           = DateTimeOffset.Now;
                    var path          = System.IO.Path.GetTempPath() + "FilterTests.TestFilters.Error." + now.ToString("yyyy-MM-dd_HH-mm-ss_fffffff.") + Guid.NewGuid().ToString() + ".log";
                    var traceListener = new TextWriterTraceListener(path, "FilterTests.TestFilters");
                    Trace.Listeners.Add(traceListener);

                    Trace.TraceInformation("Request: {0}", requestUri);
                    Trace.TraceError("StatusCode: {0}", response.StatusCode);
                    Trace.TraceError(await response.Content.ReadAsStringAsync());

                    Trace.Flush();
                    Trace.Listeners.Remove(traceListener);
                    traceListener.Close();
                    Assert.True(false);
                }
                var result = await response.Content.ReadAsObject <IEnumerable <Product> >();

                Assert.Equal(expected.Count(), result.Count());
                for (int i = 0; i < expected.Count(); i++)
                {
                    Assert.Equal(expected.ElementAt(i).ID, result.ElementAt(i).ID);
                    Assert.Equal(expected.ElementAt(i).Name, result.ElementAt(i).Name);
                    Assert.Equal(expected.ElementAt(i).Description, result.ElementAt(i).Description);
                }
            }
        }
示例#26
0
 public void LoggerClose()
 {
     if (textWriterTraceListener != null)
     {
         textWriterTraceListener.Flush();
         textWriterTraceListener.Close();
     }
     if (myFile != null)
     {
         myFile.Close();
     }
 }
示例#27
0
        protected override void OnDragOver(DragEventArgs e)
        {
            endX = e.X;
            endY = e.Y;
            TextWriterTraceListener list;

            Debug.Listeners.Add(list = new TextWriterTraceListener(System.Web.HttpContext.Current.Server.MapPath("../TraceLog1.txt")));
            Debug.Write("x: " + startX + " y: " + startY + "; x1: " + endX + " y1: " + endY + DateTime.Now.ToString());
            Debug.Listeners.Remove(list);
            list.Close();
            list.Dispose();
            this.Refresh();
        }
示例#28
0
        public static IDisposable Enable(string path)
        {
            var listener = new TextWriterTraceListener(path);

            _logging.Value.Sources.ForEach(s => s.Listeners.Add(listener));

            return(new DisposableAction(() =>
            {
                listener.Flush();
                _logging.Value.Sources.ForEach(s => s.Listeners.Remove(listener));
                listener.Close();
            }));
        }
示例#29
0
        public void TraceOptionValues()
        {
            Assert.AreEqual(TraceOptions.None,
                            new TextWriterTraceListener(TextWriter.Null).TraceOutputOptions, "#1");
            Assert.AreEqual(TraceOptions.None,
                            new XmlWriterTraceListener(TextWriter.Null).TraceOutputOptions, "#2");

            StringWriter            sw = new StringWriter();
            TextWriterTraceListener t  = new TextWriterTraceListener(sw);

            Trace.CorrelationManager.StartLogicalOperation("foo");
            Trace.CorrelationManager.StartLogicalOperation("bar");
            t.TraceOutputOptions = TraceOptions.LogicalOperationStack | TraceOptions.DateTime | TraceOptions.Timestamp;            // | TraceOptions.ProcessId | TraceOptions.ThreadId | TraceOptions.Callstack;
            t.TraceEvent(null, null, TraceEventType.Error, 0, null);
            t.TraceEvent(null, "bulldog", TraceEventType.Error, 0);
            TraceEventCache cc   = new TraceEventCache();
            DateTime        date = cc.DateTime;
            long            time = cc.Timestamp;

            t.TraceData(cc, null, TraceEventType.Error, 0);
            t.TraceData(cc, null, TraceEventType.Error, 0);
            t.TraceTransfer(null, "bulldog", 0, "hoge", Guid.Empty);
            Trace.CorrelationManager.StopLogicalOperation();
            Trace.CorrelationManager.StopLogicalOperation();
            t.Close();
            string expected = String.Format(@" Error: 0 : 
bulldog Error: 0 : 
 Error: 0 : 
    LogicalOperationStack=bar, foo
    DateTime={0}
    Timestamp={1}" +

/*
 *  Callstack=   at System.Environment.GetStackTrace(Exception e, Boolean needFileInfo)
 * at System.Environment.get_StackTrace()
 * at System.Diagnostics.TraceEventCache.get_Callstack()
 * at System.Diagnostics.TraceListener.WriteFooter(TraceEventCache eventCache)
 * at System.Diagnostics.TraceListener.TraceData(TraceEventCache eventCache, String source, TraceEventType eventType, Int32 id, Object[] data)
 * at MonoTests.System.Diagnostics.TraceListenerTest.TraceOptionValues()
 * ...
 */
                                            @"
 Error: 0 : 
    LogicalOperationStack=bar, foo
    DateTime={0}
    Timestamp={1}
bulldog Transfer: 0 : hoge, relatedActivityId=00000000-0000-0000-0000-000000000000
", date.ToString("o"), time);  // date and time are in current culture

            Assert.AreEqual(expected, sw.ToString().Replace("\r\n", "\n"));
        }
示例#30
0
    private static void Main()
    {
        TextWriterTraceListener debugLog = new TextWriterTraceListener(Console.Out);

        Debug.Listeners.Add(debugLog);

        using (Game game = new Game())
        {
            game.Run(60.0);
        }

        debugLog.Flush();
        debugLog.Close();
    }