I want to log the SMTP
protocol of System.Net.Mail.SmtpClient
as System.Net.Mail.SmtpClient
does not provide any mean of doing so, I looked for a way to log the underlying System.Net.Sockets
requests and found this stackoverflow answer which gives a way of doing so by inserting the following directives in the .config file of the application.
<system.diagnostics>
<sources>
<source name="System.Net">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
<source name="System.Net.Sockets">
<listeners>
<add name="TraceFile"/>
</listeners>
</source>
</sources>
<sharedListeners>
<add
name="TraceFile"
type="System.Diagnostics.TextWriterTraceListener"
initializeData="trace.log"
/>
</sharedListeners>
<switches>
<add name="System.Net" value="Verbose"/>
<add name="System.Net.Sockets" value="Verbose"/>
</switches>
<trace autoflush="true" />
</system.diagnostics>
unfortunately, as I don’t have the opportunity to modify powershell.exe.config
, I looked for a way of starting the trace on the fly in my script and found this stackoverflow answer which gives a way,
$id = [Environment]::TickCount
$fileName = "${PSScriptRoot}Powershell.log.${id}.txt"
$listener1 = [System.Diagnostics.TextWriterTraceListener]::New($fileName, "text_listener")
$listener2 = [System.Diagnostics.ConsoleTraceListener]::New()
$listener2.Name = "console_listener"
[System.Diagnostics.Trace]::AutoFlush = $true
[System.Diagnostics.Trace]::Listeners.Add($listener1) | out-null
[System.Diagnostics.Trace]::Listeners.Add($listener2) | out-null
# Use reflection to enable and hook up the TraceSource
$logging = [System.Net.Sockets.Socket].Assembly.GetType("System.Net.Logging")
$flags = [System.Reflection.BindingFlags]::NonPublic -bor [System.Reflection.BindingFlags]::Static
$logging.GetField("s_LoggingEnabled", $flags).SetValue($null, $true)
$webTracing = $logging.GetProperty("Web", $flags)
$webTraceSource = [System.Diagnostics.Tracesource]$webTracing.GetValue($null, $null);
$webTraceSource.Switch.Level = [System.Diagnostics.SourceLevels]::Information
$webTracesource.Listeners.Add($listener1) | out-null
$webTracesource.Listeners.Add($listener2) | out-null
[System.Diagnostics.Trace]::TraceInformation("About to do net stuff")
[System.Net.FtpWebRequest]::Create("ftp://www.google.com") | out-null
[System.Diagnostics.Trace]::TraceInformation("Finished doing net stuff")
#get rid of the listeners
[System.Diagnostics.Trace]::Listeners.Clear()
$webTraceSource.Listeners.Clear()
$listener1.Dispose()
$listener2.Dispose()
but I am not able to adapt it to my needs.
I tried to replace Web
by Sockets
in
$webTracing = $logging.GetProperty("Web", $flags)
and do some system.net.mail
stuff in place of
[System.Net.FtpWebRequest]::Create("ftp://www.google.com") | out-null
but with no success.
can you teach me how to adapt the above example to make it start traces as described in the XML
.config?