9

I know I can enable .NET tracing by adding <system.diagnostics> element to App config (powershell.exe.config) in PowerShell installation folder. This is covered in System.Net tracing in PowerShell.

In fact, I too want to log System.Net tracing source (e.g. FtpWebRequest).

But is there a way to enable tracing locally? Like in the code itself? Or possibly using some command-line switch? Or can I at least have the App config file in a local folder, not to have to modify the system-wide settings?

Martin Prikryl
  • 188,800
  • 56
  • 490
  • 992

2 Answers2

15

Just enabling the default trace sources (Trace.Information etc.) in code (and therefore in Powershell) is relatively easy.

Doing so for the System.Net trace sources is more complicated because they are not publicly accessible.

I have previously seen that in C#, calling a System.Net method e.g. Dns.Resolve was necessary in order to get the TraceSource to be created but this doesn't seem to be needed in Powershell.

So not a great solution... but it depends what your alternatives are I guess:

$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();
mhu
  • 17,720
  • 10
  • 62
  • 93
Peter Wishart
  • 11,600
  • 1
  • 26
  • 45
-2

Yes you can write tracing in code.

Trace.Write("Hello world");

If you want something more advanced try Log4Net which generates a config file.