public static void VisualLog(LogLevels loglevel, string type, String ex) { // create output to console TextWriterTraceListener console = new TextWriterTraceListener(); console.Writer = Console.Out; Trace.Listeners.Add(console); //output error if (System.Diagnostics.Trace.Listeners.Count > 0) { Trace.Write(new TraceData(loglevel, DateTime.Now, type, ex)); } //close streams console.Close(); if (!ApplicationType.GetApplicationType().Equals(ApplicationType.Type.Console)) { //messagebox MessageBoxIcon icon = MessageBoxIcon.None; switch (loglevel) { case LogLevels.Error: icon = MessageBoxIcon.Error; break; case LogLevels.Warning: icon = MessageBoxIcon.Warning; break; case LogLevels.Info: icon = MessageBoxIcon.Information; break; } MessageBox.Show(ex, type, MessageBoxButtons.OK, icon); } }
/// <summary> /// 設定Log路徑 /// </summary> /// <param name="path"></param> private static void SetLogFilePath(string path) { m_LogFilePath = path; if (myTraceLog != null) { myTraceLog.Close(); } myTraceLog = new System.IO.FileStream(path, System.IO.FileMode.Append); // Creates the new trace listener. if (myListener != null) { myListener.Close(); } myListener = new System.Diagnostics.TextWriterTraceListener(myTraceLog); System.Diagnostics.Trace.Listeners.Add(myListener); }
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(); }
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"; }
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(); }); }
public static void LogToFile(LogLevels loglevel, string type, String ex) { if (loglevel <= m_LogLevel) { // craete output to file TextWriterTraceListener writer = new TextWriterTraceListener(@"Error.log"); Trace.Listeners.Add(writer); //output error if (System.Diagnostics.Trace.Listeners.Count > 0) { Trace.Write(new TraceData(loglevel, DateTime.Now, type, ex)); } //close streams writer.Close(); } }
public void TraceEventAndTraceData () { StringWriter sw = new StringWriter (); TextWriterTraceListener t = new TextWriterTraceListener (sw); t.TraceEvent (null, null, TraceEventType.Error, 0, null); t.TraceEvent (null, "bulldog", TraceEventType.Error, 0); TraceEventCache cc = new TraceEventCache (); t.TraceData (cc, null, TraceEventType.Error, 0); t.TraceData (cc, null, TraceEventType.Error, 0); t.TraceTransfer (null, "bulldog", 0, "hoge", Guid.Empty); t.Close (); string expected = @" Error: 0 : bulldog Error: 0 : Error: 0 : Error: 0 : bulldog Transfer: 0 : hoge, relatedActivityId=00000000-0000-0000-0000-000000000000 "; Assert.AreEqual (expected, sw.ToString ().Replace ("\r\n", "\n")); }
private void Page_Load(object sender, System.EventArgs e) { // this is page's trace will be appended to page if trace=true in page directive //this trace is diff from diagnostics trace Trace.Write("cat1","msg1"); Trace.Warn("cat1","warn1"); //will be displayed in debug and release mode - see output window TextWriterTraceListener list; System.Diagnostics.Trace.Listeners.Add(list = new TextWriterTraceListener(Server.MapPath("./TraceLog.txt")));//also write it to a file System.Diagnostics.Trace.Assert(false,"ha ha ha","he ha he heheh");//when fasle the text is written System.Diagnostics.Trace.WriteIf(true,"cat1","msg2"); System.Diagnostics.Trace.Write("this","is not page tazce"); System.Diagnostics.Trace.Listeners.Remove(list); list.Close(); list.Dispose(); //will not be displayed in debug mode Debug.WriteLine("cat1","debugmsg1"); Debug.Assert(false,"ok","ok ok"); }
static void LaunchExample(string type) { try { if (File.Exists("debug.log")) File.Delete("debug.log"); if (File.Exists("trace.log")) File.Delete("trace.log"); } catch (Exception e) { Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); } using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) using (OpenTK.Toolkit.Init()) { Trace.Listeners.Add(dbg); try { var example = Type.GetType(type); if (example != null) { example.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); } } catch (Exception e) { Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", type, e.ToString())); } Trace.Listeners.Remove(dbg); dbg.Flush(); dbg.Close(); } }
private static void Console_CancelKeyPress(object sender, ConsoleCancelEventArgs e) { if (closing) { Console.WriteLine("Ok, ok! Shutting down ASAP."); e.Cancel = false; } else { Console.WriteLine("CTRL-C detected. Program will shut down as soon as gracefully possible."); Console.WriteLine("You can press again to terminate now (WARNING: you might lose event data)."); closing = true; e.Cancel = true; udpListener.RequestStop(); packetHandler.RequestStop(); grafanaFileWriter.RequestStop(); if (debugListener != null) { debugListener.Close(); } } }
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(); }
public Result Execute( ExternalCommandData commandData, ref string message, ElementSet elements) { UIApplication app = commandData.Application; UIDocument uidoc = app.ActiveUIDocument; Document doc = uidoc.Document; if( ProductType.MEP != app.Application.Product ) { message = "Please run this command in Revit MEP."; return Result.Failed; } SelElementSet sel = uidoc.Selection.Elements; if( 0 == sel.Size ) { message = "Please select some rectangular ducts."; return Result.Failed; } // set up log file: string log = Assembly.GetExecutingAssembly().Location + "." + DateTime.Now.ToString( "yyyyMMdd" ) + ".log"; if( File.Exists( log ) ) { File.Delete( log ); } TraceListener listener = new TextWriterTraceListener( log ); Trace.Listeners.Add( listener ); try { Trace.WriteLine( "Begin" ); // loop over all selected ducts: foreach( Duct duct in sel ) { if( null == duct ) { Trace.TraceError( "The selection is not a duct!" ); } else { // process each duct: Trace.WriteLine( "========================" ); Trace.WriteLine( "Duct: Id = " + duct.Id.IntegerValue ); AnalyseDuct( duct ); } } } catch( Exception ex ) { Trace.WriteLine( ex.ToString() ); } finally { Trace.Flush(); listener.Close(); Trace.Close(); Trace.Listeners.Remove( listener ); } return Result.Failed; }
public void TestFilters(string filter, IEnumerable<Product> expected) { var requestUri = this.BaseAddress + "/api/FilterTests/GetProducts?$filter=" + filter; var response = this.Client.GetAsync(requestUri).Result; 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(response.Content.ReadAsStringAsync().Result); Trace.Flush(); Trace.Listeners.Remove(traceListener); traceListener.Close(); Assert.True(false); } var result = response.Content.ReadAsAsync<IEnumerable<Product>>().Result; 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); } }
static void LaunchExample(string type) { try { if (File.Exists("debug.log")) File.Delete("debug.log"); if (File.Exists("trace.log")) File.Delete("trace.log"); } catch (Exception e) { Trace.WriteLine(String.Format("Could not access debug.log", e.ToString())); } ToolkitOptions options = ToolkitOptions.Default; if (type.Contains("GLControl") || type.Contains("Form")) { // SDL does not currently support embedding in foreign windows // such as GLControl. We need to use a native OpenTK.Platform // backend in that case. This hack is specific to the example-browser // architecture - you do not need to do anything like this in your // own code (it will just work). options = new ToolkitOptions { Backend = PlatformBackend.PreferNative }; } using (TextWriterTraceListener dbg = new TextWriterTraceListener("debug.log")) using (Toolkit.Init(options)) { Trace.Listeners.Add(dbg); try { var example = Type.GetType(type); if (example != null) { example.InvokeMember("Main", BindingFlags.InvokeMethod | BindingFlags.Static | BindingFlags.Public | BindingFlags.NonPublic, null, null, null); } } catch (Exception e) { Trace.WriteLine(String.Format("Exception occured in example {0}: {1}", type, e.ToString())); } Trace.Listeners.Remove(dbg); dbg.Flush(); dbg.Close(); } }
private void ThisAddIn_Startup(object sender, System.EventArgs e) { //StreamWriter log; //if (!File.Exists("C:\\cancergridlogfile.txt")) //{ // log = new StreamWriter("C:\\cancergridlogfile.txt"); //} //else //{ // log = File.AppendText("C:\\cancergridlogfile.txt"); //} //log.WriteLine(DateTime.Now); //log.WriteLine("Starting Cancergrid Add-in"); //log.WriteLine(); //Use "Debug" if no log should be generated for release mode. "Trace" generate log on both debug and release mode. FileStream traceLog = new FileStream(@"C:\temp\cancergridlogfile.txt", FileMode.Append); traceListener = new TextWriterTraceListener(traceLog); Trace.Listeners.Add(traceListener); Trace.WriteLine(DateTime.Now + " Starting Cancergrid Add-in"); try { AddUnmapButtonMenuCommand(); } catch (Exception exc) { // Write to the file: //log.WriteLine(DateTime.Now); //log.WriteLine(exc.Message); //log.WriteLine(); Trace.WriteLine(DateTime.Now + " " + exc.Message); // Close the stream: } finally { //log.Close(); traceListener.Close(); if (Trace.Listeners.Contains(traceListener)) { Trace.Listeners.Remove(traceListener); } } }
///<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); } }
/// <summary> /// 保存异常日志 /// </summary> /// <param name="exceptionMsg"></param> private void SaveExceptionInfo(string exceptionMsg) { if (!Directory.Exists(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH))) { Directory.CreateDirectory(Path.GetDirectoryName(CommonInfo.ERRORLOGPATH)); } string fileName = CommonInfo.ERRORLOGPATH + DateTime.Now.ToString("yy-MM-dd") + ".log"; TextWriterTraceListener textWrite = new TextWriterTraceListener(fileName, "ExceptionLog"); textWrite.Flush(); textWrite.WriteLine(DateTime.Now.ToString() + "监控平台出现异常--------------------------------"); textWrite.WriteLine(exceptionMsg); textWrite.Flush(); textWrite.Close(); }
public static void Generate(string pathToSettingsFile, string pathToShapesFile, string pathToConfigurationFile, string pathToOutputFile, int seed) { string pathToDebugFile = System.IO.Directory.GetParent(pathToOutputFile).ToString() + "\\GalaxyGenerationPlugin.log"; #if DEBUG System.IO.File.Delete(pathToDebugFile); System.Diagnostics.TextWriterTraceListener debugFileListener = new System.Diagnostics.TextWriterTraceListener(pathToDebugFile); System.Diagnostics.Trace.Listeners.Add(debugFileListener); System.Diagnostics.Trace.AutoFlush = true; System.Diagnostics.Trace.WriteLine("Using pathToSettingsFile = " + pathToSettingsFile); System.Diagnostics.Trace.WriteLine("Using pathToShapesFile = " + pathToShapesFile); System.Diagnostics.Trace.WriteLine("Using pathToConfigurationFile = " + pathToConfigurationFile); System.Diagnostics.Trace.WriteLine("Using pathToOutputFile = " + pathToOutputFile); System.Diagnostics.Trace.WriteLine("Using seed = " + seed); #endif try { Settings.Load(pathToSettingsFile); ShapeManager.Load(pathToShapesFile); Configuration configuration = new Configuration(pathToConfigurationFile); if (seed != 0) { configuration.seed = seed; } if (configuration.seed == 0) { long ticks = System.DateTime.Now.Ticks; configuration.seed = System.Math.Abs((int)ticks); } GalaxyGeneratorPlugin.random = new System.Random(configuration.seed); do { Galaxy.Release(); System.Diagnostics.Trace.WriteLine("Generating Galaxy..."); Galaxy.Generate(configuration); } while (!Galaxy.Instance.IsValid); System.Diagnostics.Trace.WriteLine("...Galaxy Generation Complete !"); System.Xml.XmlWriterSettings xmlWriterSettings = new System.Xml.XmlWriterSettings() { Encoding = System.Text.Encoding.UTF8, Indent = true, IndentChars = " ", NewLineChars = "\r\n", NewLineHandling = System.Xml.NewLineHandling.Replace, OmitXmlDeclaration = true, }; using (XmlWriter writer = XmlTextWriter.Create(pathToOutputFile, xmlWriterSettings)) { writer.WriteStartDocument(); writer.WriteStartElement("GenerationOutput"); writer.WriteStartElement("GeneratorVersion"); writer.WriteAttributeString("Revision", "105"); writer.WriteAttributeString("Date", "20120612"); writer.WriteEndElement(); configuration.WriteOuterXml(writer); Galaxy.Instance.WriteXml(writer); writer.WriteEndElement(); writer.WriteEndDocument(); writer.Close(); } Galaxy.Release(); } catch (System.Exception exception) { System.Diagnostics.Trace.Write("Exception caught: " + exception.ToString()); throw exception; } finally { #if DEBUG debugFileListener.Close(); System.Diagnostics.Trace.Listeners.Remove(debugFileListener); #endif System.Diagnostics.Trace.Close(); } }
public static void LogToFile(LogFileType logType, string logMessage) { //string LogPath = Environment.CurrentDirectory; var logPath = Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);//@"C:\VNPT-BHXH"; var logDirectory = logPath + @"\" + DateTime.Today.ToString("yyyyMMdd"); string filePath; if (!Directory.Exists(logDirectory)) { Directory.CreateDirectory(logDirectory); switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var filePaths = Directory.GetFiles(logDirectory, "*.log"); if (filePaths.Length == 0) { switch (logType) { case LogFileType.Trace: filePath = logDirectory + @"\TRACE.0.log"; break; case LogFileType.Message: filePath = logDirectory + @"\MESSAGE.0.log"; break; case LogFileType.Exception: filePath = logDirectory + @"\EXCEPTION.0.log"; break; default: filePath = logDirectory + @"\TRACE.0.log"; break; } } else { var fileList = new List<string>(); foreach (var fPath in filePaths) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); if (parts[0].ToUpper() == logType.ToString().ToUpper()) { fileList.Add(fPath); } } var lastestIndex = int.MinValue; var lastestFilePath = ""; if (fileList.Count <= 0) { filePath = logDirectory + @"\" + logType.ToString().ToUpper() + ".0.log"; } else { foreach (var fPath in fileList) { var file = new FileInfo(fPath); var parts = file.Name.Split('.'); //fPath.Split('.'); if (Convert.ToInt32(parts[1]) >= lastestIndex) { lastestIndex = Convert.ToInt32(parts[1]); lastestFilePath = fPath; } } filePath = lastestFilePath; } if (File.Exists(filePath)) { var lastestFile = new FileInfo(filePath); // check if file size be larger than 5MB then create new one if (((lastestFile.Length / 1024f) / 1024f) > 5) { lastestIndex++; filePath = logDirectory + @"\" + logType.ToString().ToUpper() + "." + lastestIndex + ".log"; } } } } logMessage = DateTime.Now.ToString("HH:mm:ss") + " " + logMessage; var listener = new TextWriterTraceListener(filePath); listener.WriteLine(logMessage); listener.Flush(); listener.Close(); }
// static Crc16 _crc16; static void Main(string[] args) { Boolean done; TextWriterTraceListener tl = new TextWriterTraceListener(@"C:\roombalog.txt"); Trace.Listeners.Add(tl); ConsoleKeyInfo cki; //string name; //string message; StringComparer stringComparer = StringComparer.OrdinalIgnoreCase; Thread readThread = new Thread(Read); // Create a new SerialPort object with default settings. _serialPort = new SerialPort(); // Allow the user to set the appropriate properties. _serialPort.PortName = SetPortName(_serialPort.PortName); //_serialPort.BaudRate = SetPortBaudRate(_serialPort.BaudRate); //_serialPort.Parity = SetPortParity(_serialPort.Parity); //_serialPort.DataBits = SetPortDataBits(_serialPort.DataBits); //_serialPort.StopBits = SetPortStopBits(_serialPort.StopBits); //_serialPort.Handshake = SetPortHandshake(_serialPort.Handshake); // Set the read/write timeouts _serialPort.ReadTimeout = 500; _serialPort.WriteTimeout = 500; _serialPort.Open(); _continue = true; readThread.Start(); _serialPort.WriteLine("h"); _serialPort.WriteLine("m"); _serialPort.WriteLine("s"); _serialPort.WriteLine("c15"); _serialPort.WriteLine("m"); // _serialPort.WriteLine(""); // Retrieve the device list from the local machine IList<LivePacketDevice> allDevices = LivePacketDevice.AllLocalMachine; if (allDevices.Count == 0) { Console.WriteLine("No interfaces found! Make sure WinPcap is installed."); return; } // Print the list for (int i = 0; i != allDevices.Count; ++i) { LivePacketDevice device = allDevices[i]; Console.Write((i + 1) + ". " + device.Name); if (device.Description != null) Console.WriteLine(" (" + device.Description + ")"); else Console.WriteLine(" (No description available)"); } int deviceIndex = 0; do { Console.WriteLine("Enter the interface number (1-" + allDevices.Count + "):"); string deviceIndexString = Console.ReadLine(); if (!int.TryParse(deviceIndexString, out deviceIndex) || deviceIndex < 1 || deviceIndex > allDevices.Count) { deviceIndex = 0; } } while (deviceIndex == 0); // Take the selected adapter PacketDevice selectedDevice = allDevices[deviceIndex - 1]; // Open the device using (PacketCommunicator communicator = selectedDevice.Open(65536, // portion of the packet to capture // 65536 guarantees that the whole packet will be captured on all the link layers PacketDeviceOpenAttributes.Promiscuous, // promiscuous mode 1000)) // read timeout { Console.WriteLine("Listening on " + selectedDevice.Description + "..."); Trace.WriteLine("Listening on " + selectedDevice.Description + "..."); // start the capture done = false; do { communicator.ReceivePackets(1, PacketHandler); if (Console.KeyAvailable) { cki = Console.ReadKey(true); if (cki.Key == ConsoleKey.Escape) done = true; } } while (done == false); } tl.Flush(); tl.Close(); readThread.Join(); _serialPort.Close(); }
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()); } }
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")); }