BindingFlags.Public needed here as Exception.HResult is now public in .NET 4.5. This...
[mono.git] / mcs / class / System / System.Diagnostics / DefaultTraceListener.cs
1 //
2 // System.Diagnostics.DefaultTraceListener.cs
3 //
4 // Authors:
5 //   Jonathan Pryor (jonpryor@vt.edu)
6 //   Atsushi Enomoto (atsushi@ximian.com)
7 //
8 // Comments from John R. Hicks <angryjohn69@nc.rr.com> original implementation 
9 // can be found at: /mcs/docs/apidocs/xml/en/System.Diagnostics
10 //
11 // (C) 2002 Jonathan Pryor
12 // (C) 2007 Novell, Inc.
13 //
14
15 //
16 // Permission is hereby granted, free of charge, to any person obtaining
17 // a copy of this software and associated documentation files (the
18 // "Software"), to deal in the Software without restriction, including
19 // without limitation the rights to use, copy, modify, merge, publish,
20 // distribute, sublicense, and/or sell copies of the Software, and to
21 // permit persons to whom the Software is furnished to do so, subject to
22 // the following conditions:
23 // 
24 // The above copyright notice and this permission notice shall be
25 // included in all copies or substantial portions of the Software.
26 // 
27 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
28 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
29 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
30 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
31 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
32 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
33 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
34 //
35
36 using System;
37 using System.IO;
38 using System.Collections;
39 using System.Diagnostics;
40 using System.Reflection;
41 using System.Runtime.CompilerServices;
42 using System.Runtime.InteropServices;
43 using System.Threading;
44
45 namespace System.Diagnostics {
46 #if NET_2_0
47 #else
48         [ComVisible(false)]
49 #endif
50         public class DefaultTraceListener : TraceListener {
51
52                 private static readonly bool OnWin32;
53
54                 private const string ConsoleOutTrace = "Console.Out";
55                 private const string ConsoleErrorTrace = "Console.Error";
56
57                 private static readonly string MonoTracePrefix;
58                 private static readonly string MonoTraceFile;
59
60                 static DefaultTraceListener ()
61                 {
62                         // Determine what platform we're on.  This impacts how where we send
63                         // messages.  On Win32 platforms (OnWin32 = true), we use the
64                         // `OutputDebugString' api.
65                         //
66                         // On Linux platforms, we use MONO_TRACE_LISTENER to figure things out.  See the
67                         // API documentation for more information on MONO_TRACE_LISTENER.
68                         OnWin32 = (Path.DirectorySeparatorChar == '\\');
69
70                         if (!OnWin32) {
71 #if TARGET_JVM
72                                 string trace = java.lang.System.getProperty("MONO_TRACE");
73 #else
74                                 // If we're running on Unix, we don't have OutputDebugString.
75                                 // Instead, send output to...wherever the MONO_TRACE_LISTENER environment
76                                 // variables says to.
77                                 String trace = Environment.GetEnvironmentVariable("MONO_TRACE_LISTENER");
78 #endif
79
80 #if MOBILE
81                                 if (trace == null)
82                                         trace = ConsoleOutTrace;
83 #endif
84
85                                 if (trace != null) {
86                                         string file = null;
87                                         string prefix = null;
88
89                                         if (trace.StartsWith (ConsoleOutTrace)) {
90                                                 file = ConsoleOutTrace;
91                                                 prefix = GetPrefix (trace, ConsoleOutTrace);
92                                         }
93                                         else if (trace.StartsWith (ConsoleErrorTrace)) {
94                                                 file = ConsoleErrorTrace;
95                                                 prefix = GetPrefix (trace, ConsoleErrorTrace);
96                                         }
97                                         else {
98                                                 file = trace;
99
100                                                 // We can't firgure out what the prefix would be, as ':' is a
101                                                 // valid filename character.  Thus, arbitrary files don't support
102                                                 // prefixes.
103                                                 //
104                                                 // I don't consider this to be a major issue.  Prefixes are useful 
105                                                 // with Console.Out and Console.Error to help separate trace
106                                                 // output from the actual program output.  Writing to an arbitrary
107                                                 // file doesn't introduce issues with disambiguation.
108                                                 prefix = "";
109                                         }
110
111                                         MonoTraceFile = file;
112                                         MonoTracePrefix = prefix;
113                                 }
114                         }
115                 }
116
117                 /**
118                  * Get the prefix for the specified variable.
119                  *
120                  * "Prefixes" are used in the MONO_TRACE_LISTENER variable, and specify text that
121                  * should precede each message printed to the console.  The prefix is
122                  * appended to the console location with a colon (':') separating them.
123                  * For example, if MONO_TRACE_LISTENER is "Console.Out:** my prefix", the prefix is
124                  * "** my prefix".
125                  *
126                  * Everything after the colon, if the colon is present, is used as the
127                  * prefix.
128                  *
129                  * @param       var             The current MONO_TRACE_LISTENER variable
130                  * @param       target  The name of the output location, e.g. "Console.Out"
131                  */
132                 private static string GetPrefix (string var, string target)
133                 {
134                         // actually, we permit any character to separate `target' and the prefix;
135                         // we just skip over target the ':' would be.  This means that a space or
136                         // anything else would suffice, as long as it was only a single
137                         // character.
138                         if (var.Length > target.Length)
139                                 return var.Substring (target.Length + 1);
140                         return "";
141                 }
142
143                 private string logFileName = null;
144
145                 private bool assertUiEnabled = false;
146
147                 public DefaultTraceListener () : base ("Default")
148                 {
149                 }
150
151                 public bool AssertUiEnabled {
152                         get { return assertUiEnabled; }
153                         set { assertUiEnabled = value; }
154                 }
155
156                 [MonoTODO]
157                 public string LogFileName {
158                         get {return logFileName;}
159                         set {logFileName = value;}
160                 }
161
162                 public override void Fail (string message)
163                 {
164                         base.Fail (message);
165                 }
166
167                 public override void Fail (string message, string detailMessage)
168                 {
169                         base.Fail (message, detailMessage);
170                         if (ProcessUI (message, detailMessage) == DialogResult.Abort)
171                                 Thread.CurrentThread.Abort ();
172                         WriteLine (new StackTrace().ToString());
173                 }
174
175                 DialogResult ProcessUI (string message, string detailMessage)
176                 {
177                         
178                         if (!AssertUiEnabled)
179                                 return DialogResult.None;
180
181                         object messageBoxButtonsAbortRetryIgnore;
182                         MethodInfo msgboxShow;
183                         
184                         try {
185                                 Assembly wfAsm = Assembly.Load (Consts.AssemblySystem_Windows_Forms);
186                                 if (wfAsm == null)
187                                     return DialogResult.None;
188                                 
189                                 Type buttons = wfAsm.GetType ("System.Windows.Forms.MessageBoxButtons");
190                                 messageBoxButtonsAbortRetryIgnore = Enum.Parse (buttons, "AbortRetryIgnore");
191                                 msgboxShow = wfAsm.GetType ("System.Windows.Forms.MessageBox").GetMethod (
192                                         "Show",
193                                         new Type [] {typeof (string), typeof (string), buttons});
194                         } catch {
195                                 return DialogResult.None;
196                         }
197
198                         if (msgboxShow == null || messageBoxButtonsAbortRetryIgnore == null)
199                                 return DialogResult.None;
200
201                         string caption = String.Format ("Assertion Failed: {0} to quit, {1} to debug, {2} to continue", "Abort", "Retry", "Ignore");
202                         string msg = String.Format ("{0}{1}{2}{1}{1}{3}", message, Environment.NewLine, detailMessage, new StackTrace ());
203
204                         switch (msgboxShow.Invoke (null, new object [] {msg, caption, messageBoxButtonsAbortRetryIgnore}).ToString ()) {
205                         case "Ignore":
206                                 return DialogResult.Ignore;
207                         case "Abort":
208                                 return DialogResult.Abort;
209                         default:
210                                 return DialogResult.Retry;
211                         }
212                 }
213
214                 enum DialogResult {
215                         None,
216                         Retry,
217                         Ignore,
218                         Abort
219                 }
220
221 #if TARGET_JVM
222                 private void WriteDebugString (string message)
223                 {
224 #else
225                 [MethodImplAttribute(MethodImplOptions.InternalCall)]
226                 private extern static void WriteWindowsDebugString (string message);
227
228                 private void WriteDebugString (string message)
229                 {
230                         if (OnWin32)
231                                 WriteWindowsDebugString (message);
232                         else
233 #endif
234                                 WriteMonoTrace (message);
235                 }
236
237                 private void WriteMonoTrace (string message)
238                 {
239                         switch (MonoTraceFile) {
240                         case ConsoleOutTrace:
241                                 Console.Out.Write (message);
242                                 break;
243                         case ConsoleErrorTrace:
244                                 Console.Error.Write (message);
245                                 break;
246                         default:
247                                 WriteLogFile (message, MonoTraceFile);
248                                 break;
249                         }
250                 }
251
252                 private void WritePrefix ()
253                 {
254                         if (!OnWin32) {
255                                 WriteMonoTrace (MonoTracePrefix);
256                         }
257                 }
258
259                 private void WriteImpl (string message)
260                 {
261                         if (NeedIndent) {
262                                 WriteIndent ();
263                                 WritePrefix ();
264                         }
265
266                         WriteDebugString (message);
267
268                         if (Debugger.IsLogging())
269                                 Debugger.Log (0, null, message);
270
271                         WriteLogFile (message, LogFileName);
272                 }
273
274                 private void WriteLogFile (string message, string logFile)
275                 {
276                         string fname = logFile;
277                         if (fname != null && fname.Length != 0) {
278                                 FileInfo info = new FileInfo (fname);
279                                 StreamWriter sw = null;
280
281                                 // Open the file
282                                 try {
283                                         if (info.Exists)
284                                                 sw = info.AppendText ();
285                                         else
286                                                 sw = info.CreateText ();
287                                 }
288                                 catch {
289                                         // We weren't able to open the file for some reason.
290                                         // We can't write to the log file; so give up.
291                                         return;
292                                 }
293
294                                 using (sw) {
295                                         sw.Write (message);
296                                         sw.Flush ();
297                                 }
298                         }
299                 }
300
301                 public override void Write (string message)
302                 {
303                         WriteImpl (message);
304                 }
305
306                 public override void WriteLine (string message)
307                 {
308                         string msg = message + Environment.NewLine;
309                         WriteImpl (msg);
310
311                         NeedIndent = true;
312                 }
313         }
314 }
315