I want to capture certain, but not all, HttpWebRequest traffic in my application for debugging purposes. It's a web service hosted by IIS.
I have read How to: Configure Network Tracing. This works great, but I don't want to direct the trace to a file, due to possible permission problems on the file system, data sensitivity, etc. I would like to capture directly to a something in-memory that I can subsequently inspect or encrypt and email. Preferably, this would not involve any changes to the app.config file.
I tried the following, but obviously I am missing a step to tie the TextWriterTraceListener into System.Net. How can I capture the System.Net traffic into my StringWriter?
StringWriter sw = new StringWriter();
TextWriterTraceListener myListener = new TextWriterTraceListener(sw);
Trace.Listeners.Add(myListener);
HttpWebRequest req = (HttpWebRequest) WebRequest.Create("http://www.microsoft.com");
HttpWebResponse resp = (HttpWebResponse) req.GetResponse();
Stream s = resp.GetResponseStream();
byte[] buf = new byte[4096];
while (s.Read(buf, 0, buf.Length) > 0) ;
s.Close();
myListener.Flush();
sw.Flush();
Edit: Specifically, I want to do the equivalent of this at runtime, except that I don't want output to go to network.log, I want it to go to a string buffer I've set up for this purpose.
<configuration>
<system.diagnostics>
<sources>
<source name="System.Net.Sockets" tracemode="includehex">
<listeners>
<add name="System.Net.Sockets" type="System.Diagnostics.TextWriterTraceListener" initializeData="network.log" />
</listeners>
</source>
</sources>
<switches>
<add name="System.Net.Sockets" value="Verbose"/>
</switches>
<trace autoflush="true" />
</system.diagnostics>
</configuration>