Merge pull request #167 from konrad-kruczynski/send_async_fix
[mono.git] / mcs / class / System.ServiceModel / System.ServiceModel / Logger.cs
1 //
2 // Author:
3 //      Atsushi Enomoto <atsushi@ximian.com>
4 //
5 // Copyright (C) 2011 Novell, Inc.  http://www.novell.com
6 // Copyright 2011 Xamarin Inc (http://www.xamarin.com).
7 //
8 // Permission is hereby granted, free of charge, to any person obtaining
9 // a copy of this software and associated documentation files (the
10 // "Software"), to deal in the Software without restriction, including
11 // without limitation the rights to use, copy, modify, merge, publish,
12 // distribute, sublicense, and/or sell copies of the Software, and to
13 // permit persons to whom the Software is furnished to do so, subject to
14 // the following conditions:
15 // 
16 // The above copyright notice and this permission notice shall be
17 // included in all copies or substantial portions of the Software.
18 // 
19 // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
20 // EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
21 // MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
22 // NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE
23 // LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION
24 // OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
25 // WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
26 //
27 using System;
28 using System.Collections.Generic;
29 using System.Configuration;
30 using System.Diagnostics;
31 using System.IO;
32 using System.ServiceModel;
33 using System.ServiceModel.Channels;
34 using System.ServiceModel.Configuration;
35 using System.ServiceModel.Diagnostics;
36 using System.Threading;
37 using System.Xml;
38 #if !MOONLIGHT
39 using System.Xml.XPath;
40 #endif
41
42 namespace System.ServiceModel
43 {
44         internal enum MessageLogSourceKind
45         {
46                 TransportSend,
47                 TransportReceive,
48                 ServiceLevelReceiveDatagram,
49                 ServiceLevelSendDatagram,
50                 // more, maybe for clients?
51         }
52
53         internal static class Logger
54         {
55 #if NET_2_1
56                 enum TraceEventType // dummy
57                 {
58                         Critical,
59                         Error,
60                         Warning,
61                         Information,
62                         Verbose,
63                         Start,
64                         Stop,
65                         Suspend,
66                         Resume,
67                         Transfer
68                 }
69 #endif
70
71                 const string xmlns = "http://schemas.microsoft.com/2004/06/ServiceModel/Management/MessageTrace";
72                 static MessageLoggingSettings settings = new MessageLoggingSettings ();
73                 static int event_id;
74                 static TextWriter log_writer = TextWriter.Null;
75                 static XmlWriter xml_writer;
76 #if !NET_2_1
77                 static readonly TraceSource source = new TraceSource ("System.ServiceModel");
78                 static readonly TraceSource message_source = new TraceSource ("System.ServiceModel.MessageLogging");
79 #endif
80
81                 static Logger ()
82                 {
83                         var env =
84                                 Environment.GetEnvironmentVariable ("MOON_WCF_TRACE") ??
85                                 Environment.GetEnvironmentVariable ("MONO_WCF_TRACE");
86
87                         switch (env) {
88                         case "stdout":
89                                 log_writer = Console.Out;
90                                 break;
91                         case "stderr":
92                                 log_writer = Console.Error;
93                                 break;
94 #if !NET_2_1
95                         default:
96                                 try {
97                                         if (!String.IsNullOrEmpty (env))
98                                                 log_writer = File.CreateText (env);
99                                 } catch (Exception ex) {
100                                         Console.Error.WriteLine ("WARNING: WCF trace environment variable points to non-creatable file name: " + env);
101                                 }
102                                 break;
103 #endif
104                         }
105                         xml_writer = XmlWriter.Create (log_writer, new XmlWriterSettings () { OmitXmlDeclaration = true });
106
107 #if !NET_2_1
108                         message_source.Switch.Level = SourceLevels.Information;
109 #endif
110                 }
111
112                 #region logger methods
113
114                 public static void Critical (string message, params object [] args)
115                 {
116                         Log (TraceEventType.Critical, message, args);
117                 }
118
119                 public static void Error (string message, params object [] args)
120                 {
121                         Log (TraceEventType.Error, message, args);
122                 }
123                 
124                 public static void Warning (string message, params object [] args)
125                 {
126                         Log (TraceEventType.Warning, message, args);
127                 }
128                 
129                 public static void Info (string message, params object [] args)
130                 {
131                         Log (TraceEventType.Information, message, args);
132                 }
133                 
134                 public static void Verbose (string message, params object [] args)
135                 {
136                         Log (TraceEventType.Verbose, message, args);
137                 }
138                 
139                 // FIXME: do we need more?
140
141                 static void Log (TraceEventType eventType, string message, params object [] args)
142                 {
143                         event_id++;
144 #if NET_2_1
145                         log_writer.Write ("[{0}] ", event_id);
146 #endif
147                         TraceCore (TraceEventType.Information, event_id,
148                                 false, Guid.Empty, // FIXME
149                                 message, args);
150                         log_writer.WriteLine (message, args);
151                         log_writer.Flush ();
152 #if !NET_2_1
153                         source.TraceEvent (eventType, event_id, message, args);
154 #endif
155                 }
156                 
157                 #endregion
158                 
159                 #region message logging
160                 
161                 static readonly XmlWriterSettings xws = new XmlWriterSettings () { OmitXmlDeclaration = true };
162                 
163                 public static void LogMessage (MessageLogSourceKind sourceKind, ref Message msg, long maxMessageSize)
164                 {
165                         if (maxMessageSize > int.MaxValue)
166                                 throw new ArgumentOutOfRangeException ("maxMessageSize");
167                         var mb = msg.CreateBufferedCopy ((int) maxMessageSize);
168                         msg = mb.CreateMessage ();
169                         LogMessage (new MessageLogTraceRecord (sourceKind, msg.GetType (), mb));
170                 }
171                 
172                 public static void LogMessage (MessageLogTraceRecord log)
173                 {
174                         var sw = new StringWriter ();
175 #if NET_2_1
176                         var xw = XmlWriter.Create (sw, xws);
177 #else
178                         var doc = new XmlDocument ();
179                         var xw = doc.CreateNavigator ().AppendChild ();
180 #endif
181                         xw.WriteStartElement ("MessageLogTraceRecord", xmlns);
182                         xw.WriteStartAttribute ("Time");
183                         xw.WriteValue (log.Time);
184                         xw.WriteEndAttribute ();
185                         xw.WriteAttributeString ("Source", log.Source.ToString ());
186                         xw.WriteAttributeString ("Type", log.Type.FullName);
187                         var msg = log.Message.CreateMessage ();
188                         if (!msg.IsEmpty)
189                                 msg.WriteMessage (xw);
190                         xw.WriteEndElement ();
191                         xw.Close ();
192
193                         event_id++;
194
195 #if NET_2_1
196                         log_writer.Write ("[{0}] ", event_id);
197
198                         TraceCore (TraceEventType.Information, event_id, /*FIXME*/false, /*FIXME*/Guid.Empty, sw);
199 #else
200                         TraceCore (TraceEventType.Information, event_id, /*FIXME*/false, /*FIXME*/Guid.Empty, doc.CreateNavigator ());
201
202                         message_source.TraceData (TraceEventType.Information, event_id, doc.CreateNavigator ());
203 #endif
204
205                         log_writer.Flush ();
206                 }
207
208                 #endregion
209
210                 #region XmlWriterTraceListener compatibility
211                 static void TraceCore (//TraceEventCache eventCache,
212                         /*string source,*/ TraceEventType eventType, int id,
213                         bool hasRelatedActivity, Guid relatedActivity,
214                         /*int level, bool wrapData, */params object [] data)
215                 {
216                         string source = "mono(dummy)";
217                         int level = 2;
218                         bool wrapData = true;
219                         var w = xml_writer;
220
221                         w.WriteStartElement ("E2ETraceEvent", e2e_ns);
222
223                         // <System>
224                         w.WriteStartElement ("System", sys_ns);
225                         w.WriteStartElement ("EventID", sys_ns);
226                         w.WriteString (XmlConvert.ToString (id));
227                         w.WriteEndElement ();
228                         w.WriteStartElement ("Type", sys_ns);
229                         // ...what to write here?
230                         w.WriteString ("3");
231                         w.WriteEndElement ();
232                         w.WriteStartElement ("SubType", sys_ns);
233                         // FIXME: it does not seem always to match eventType value ...
234                         w.WriteAttributeString ("Name", eventType.ToString ());
235                         // ...what to write here?
236                         w.WriteString ("0");
237                         w.WriteEndElement ();
238                         // ...what to write here?
239                         w.WriteStartElement ("Level", sys_ns);
240                         w.WriteString (level.ToString ());
241                         w.WriteEndElement ();
242                         w.WriteStartElement ("TimeCreated", sys_ns);
243                         w.WriteAttributeString ("SystemTime", XmlConvert.ToString (DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
244                         w.WriteEndElement ();
245                         w.WriteStartElement ("Source", sys_ns);
246                         w.WriteAttributeString ("Name", source);
247                         w.WriteEndElement ();
248                         w.WriteStartElement ("Correlation", sys_ns);
249                         w.WriteAttributeString ("ActivityID", String.Concat ("{", Guid.Empty, "}"));
250                         w.WriteEndElement ();
251                         w.WriteStartElement ("Execution", sys_ns);
252                         w.WriteAttributeString ("ProcessName", "mono (dummy)");
253                         w.WriteAttributeString ("ProcessID", "0");
254                         w.WriteAttributeString ("ThreadID", Thread.CurrentThread.ManagedThreadId.ToString ());
255                         w.WriteEndElement ();
256                         w.WriteStartElement ("Channel", sys_ns);
257                         // ...what to write here?
258                         w.WriteEndElement ();
259                         w.WriteStartElement ("Computer");
260                         w.WriteString ("localhost(dummy)");
261                         w.WriteEndElement ();
262
263                         w.WriteEndElement ();
264
265                         // <ApplicationData>
266                         w.WriteStartElement ("ApplicationData", e2e_ns);
267                         w.WriteStartElement ("TraceData", e2e_ns);
268                         foreach (object o in data) {
269                                 if (wrapData)
270                                         w.WriteStartElement ("DataItem", e2e_ns);
271 #if MOONLIGHT
272                                 // in moonlight we don't have XPathNavigator, so just use raw string...
273                                 if (o != null)
274                                         w.WriteString (o.ToString ());
275 #else
276                                 if (o is XPathNavigator)
277                                         // the output ignores xmlns difference between the parent (E2ETraceEvent and the content node).
278                                         // To clone such behavior, I took this approach.
279                                         w.WriteRaw (XPathNavigatorToString ((XPathNavigator) o));
280                                 else if (o != null)
281                                         w.WriteString (o.ToString ());
282 #endif
283                                 if (wrapData)
284                                         w.WriteEndElement ();
285                         }
286                         w.WriteEndElement ();
287                         w.WriteEndElement ();
288
289                         w.WriteEndElement ();
290
291                         w.Flush (); // for XmlWriter
292                         log_writer.WriteLine ();
293                         log_writer.Flush (); // for TextWriter
294                 }
295
296                 static readonly XmlWriterSettings xml_writer_settings = new XmlWriterSettings () { OmitXmlDeclaration = true };
297
298 #if !MOONLIGHT
299                 // I avoided OuterXml which includes indentation.
300                 static string XPathNavigatorToString (XPathNavigator nav)
301                 {
302                         var sw = new StringWriter ();
303                         using (var xw = XmlWriter.Create (sw, xml_writer_settings))
304                                 nav.WriteSubtree (xw);
305                         return sw.ToString ();
306                 }
307 #endif
308
309                 static readonly string e2e_ns = "http://schemas.microsoft.com/2004/06/E2ETraceEvent";
310                 static readonly string sys_ns = "http://schemas.microsoft.com/2004/06/windows/eventlog/system";
311                 #endregion
312         }
313 }