Add tracelistener with powershell

In our deployment script we automate the installation and configuration of our product. For Development and Test environment we want to log everything to a file. The powershell script below takes care of adding TextWriterTraceListener to the trace listeners.

$configFile = "YOUR_CONFIG_FILE"
$xml=New-Object XML
$xml.Load($configFile)
# locate the sharedlistener with name TextFileLogListener
$tracelistenernode = $xml.SelectSingleNode("/configuration/system.diagnostics/sharedListeners/add[@name='TextFileLogListener']")
if (!$tracelistenernode)
{
    # filter on eventtype Information
    $filter = $xml.CreateElement("filter")
    $filter.SetAttribute("type", "System.Diagnostics.EventTypeFilter")
    $filter.SetAttribute("initializeData", "Information")
    # TextWriterTraceListener in shared listeners
    $tracelistenernode = $xml.CreateElement("add")
    $tracelistenernode.SetAttribute("name", "TextFileLogListener")
    $tracelistenernode.SetAttribute("type", "System.Diagnostics.TextWriterTraceListener")
    $tracelistenernode.SetAttribute("initializeData", "c:\\log.txt")
    $tracelistenernode.AppendChild($filter)
    $xml.configuration.'system.diagnostics'.sharedListeners.AppendChild($tracelistenernode)
    # TextFileLogListener in tracelistenerd
    $listener = $xml.CreateElement("add")
    $listener.SetAttribute("name", "TextFileLogListener")
    $xml.configuration.'system.diagnostics'.trace.listeners.AppendChild($listener)
    # write the config changes to disk
    $xml.Save($configFile)
}

works-on-my-machine
The filter is set to Information. This means everything is logged and you can end up with a huge file. Feel free to use the script, but you do this on your own risk.

About erictummers

My work as a recruited developer changes almost every month. I like challenges and sharing the solutions with others. On my blog I’ll mostly post about my work, but expect an occasional home project, productivity tip and tooling review.
This entry was posted in Development and tagged , , . Bookmark the permalink.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s