Add locking around the ServiceModel.Logger, fixes a race reported on the mono-devel...
[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                         lock (log_writer){
144                                 event_id++;
145 #if NET_2_1
146                                 log_writer.Write ("[{0}] ", event_id);
147 #endif
148                                 TraceCore (TraceEventType.Information, event_id,
149                                         false, Guid.Empty, // FIXME
150                                         message, args);
151                                 log_writer.WriteLine (message, args);
152                                 log_writer.Flush ();
153 #if !NET_2_1
154                                 source.TraceEvent (eventType, event_id, message, args);
155 #endif
156                         }
157                 }
158                 
159                 #endregion
160                 
161                 #region message logging
162                 
163                 static readonly XmlWriterSettings xws = new XmlWriterSettings () { OmitXmlDeclaration = true };
164                 
165                 public static void LogMessage (MessageLogSourceKind sourceKind, ref Message msg, long maxMessageSize)
166                 {
167                         if (maxMessageSize > int.MaxValue)
168                                 throw new ArgumentOutOfRangeException ("maxMessageSize");
169                         var mb = msg.CreateBufferedCopy ((int) maxMessageSize);
170                         msg = mb.CreateMessage ();
171                         LogMessage (new MessageLogTraceRecord (sourceKind, msg.GetType (), mb));
172                 }
173                 
174                 public static void LogMessage (MessageLogTraceRecord log)
175                 {
176                         var sw = new StringWriter ();
177 #if NET_2_1
178                         var xw = XmlWriter.Create (sw, xws);
179 #else
180                         var doc = new XmlDocument ();
181                         var xw = doc.CreateNavigator ().AppendChild ();
182 #endif
183                         xw.WriteStartElement ("MessageLogTraceRecord", xmlns);
184                         xw.WriteStartAttribute ("Time");
185                         xw.WriteValue (log.Time);
186                         xw.WriteEndAttribute ();
187                         xw.WriteAttributeString ("Source", log.Source.ToString ());
188                         xw.WriteAttributeString ("Type", log.Type.FullName);
189                         var msg = log.Message.CreateMessage ();
190                         if (!msg.IsEmpty)
191                                 msg.WriteMessage (xw);
192                         xw.WriteEndElement ();
193                         xw.Close ();
194
195                         event_id++;
196                         lock (log_writer){
197 #if NET_2_1
198                                 log_writer.Write ("[{0}] ", event_id);
199
200                                 TraceCore (TraceEventType.Information, event_id, /*FIXME*/false, /*FIXME*/Guid.Empty, sw);
201 #else
202                                 TraceCore (TraceEventType.Information, event_id, /*FIXME*/false, /*FIXME*/Guid.Empty, doc.CreateNavigator ());
203
204                                 message_source.TraceData (TraceEventType.Information, event_id, doc.CreateNavigator ());
205 #endif
206                                 log_writer.Flush ();
207                         }
208                 }
209
210                 #endregion
211
212                 #region XmlWriterTraceListener compatibility
213                 static void TraceCore (//TraceEventCache eventCache,
214                         /*string source,*/ TraceEventType eventType, int id,
215                         bool hasRelatedActivity, Guid relatedActivity,
216                         /*int level, bool wrapData, */params object [] data)
217                 {
218                         string source = "mono(dummy)";
219                         int level = 2;
220                         bool wrapData = true;
221                         var w = xml_writer;
222
223                         w.WriteStartElement ("E2ETraceEvent", e2e_ns);
224
225                         // <System>
226                         w.WriteStartElement ("System", sys_ns);
227                         w.WriteStartElement ("EventID", sys_ns);
228                         w.WriteString (XmlConvert.ToString (id));
229                         w.WriteEndElement ();
230                         w.WriteStartElement ("Type", sys_ns);
231                         // ...what to write here?
232                         w.WriteString ("3");
233                         w.WriteEndElement ();
234                         w.WriteStartElement ("SubType", sys_ns);
235                         // FIXME: it does not seem always to match eventType value ...
236                         w.WriteAttributeString ("Name", eventType.ToString ());
237                         // ...what to write here?
238                         w.WriteString ("0");
239                         w.WriteEndElement ();
240                         // ...what to write here?
241                         w.WriteStartElement ("Level", sys_ns);
242                         w.WriteString (level.ToString ());
243                         w.WriteEndElement ();
244                         w.WriteStartElement ("TimeCreated", sys_ns);
245                         w.WriteAttributeString ("SystemTime", XmlConvert.ToString (DateTime.Now, XmlDateTimeSerializationMode.RoundtripKind));
246                         w.WriteEndElement ();
247                         w.WriteStartElement ("Source", sys_ns);
248                         w.WriteAttributeString ("Name", source);
249                         w.WriteEndElement ();
250                         w.WriteStartElement ("Correlation", sys_ns);
251                         w.WriteAttributeString ("ActivityID", String.Concat ("{", Guid.Empty, "}"));
252                         w.WriteEndElement ();
253                         w.WriteStartElement ("Execution", sys_ns);
254                         w.WriteAttributeString ("ProcessName", "mono (dummy)");
255                         w.WriteAttributeString ("ProcessID", "0");
256                         w.WriteAttributeString ("ThreadID", Thread.CurrentThread.ManagedThreadId.ToString ());
257                         w.WriteEndElement ();
258                         w.WriteStartElement ("Channel", sys_ns);
259                         // ...what to write here?
260                         w.WriteEndElement ();
261                         w.WriteStartElement ("Computer");
262                         w.WriteString ("localhost(dummy)");
263                         w.WriteEndElement ();
264
265                         w.WriteEndElement ();
266
267                         // <ApplicationData>
268                         w.WriteStartElement ("ApplicationData", e2e_ns);
269                         w.WriteStartElement ("TraceData", e2e_ns);
270                         foreach (object o in data) {
271                                 if (wrapData)
272                                         w.WriteStartElement ("DataItem", e2e_ns);
273 #if MOONLIGHT
274                                 // in moonlight we don't have XPathNavigator, so just use raw string...
275                                 if (o != null)
276                                         w.WriteString (o.ToString ());
277 #else
278                                 if (o is XPathNavigator)
279                                         // the output ignores xmlns difference between the parent (E2ETraceEvent and the content node).
280                                         // To clone such behavior, I took this approach.
281                                         w.WriteRaw (XPathNavigatorToString ((XPathNavigator) o));
282                                 else if (o != null)
283                                         w.WriteString (o.ToString ());
284 #endif
285                                 if (wrapData)
286                                         w.WriteEndElement ();
287                         }
288                         w.WriteEndElement ();
289                         w.WriteEndElement ();
290
291                         w.WriteEndElement ();
292
293                         w.Flush (); // for XmlWriter
294                         log_writer.WriteLine ();
295                         log_writer.Flush (); // for TextWriter
296                 }
297
298                 static readonly XmlWriterSettings xml_writer_settings = new XmlWriterSettings () { OmitXmlDeclaration = true };
299
300 #if !MOONLIGHT
301                 // I avoided OuterXml which includes indentation.
302                 static string XPathNavigatorToString (XPathNavigator nav)
303                 {
304                         var sw = new StringWriter ();
305                         using (var xw = XmlWriter.Create (sw, xml_writer_settings))
306                                 nav.WriteSubtree (xw);
307                         return sw.ToString ();
308                 }
309 #endif
310
311                 static readonly string e2e_ns = "http://schemas.microsoft.com/2004/06/E2ETraceEvent";
312                 static readonly string sys_ns = "http://schemas.microsoft.com/2004/06/windows/eventlog/system";
313                 #endregion
314         }
315 }