Setup logging in configuration with powershell

Manipulation of config files with notepad is a burden for every developer / operator. It is the source of many errors.

With DEVOPS we try to automate this process. The result is less prone to errors. See the powershell script below to add a shared listener to a config file.

$configFile = "PATH_TO_YOUR.config"
$xml=New-Object XML
# Load the configuration from disk into memory
# Find the sharedListener named TextFileLogListener
$tracelistenernode = $xml.SelectSingleNode("/configuration/system.diagnostics/sharedListeners/add[@name='TextFileLogListener']")
if (!$tracelistenernode)
	# Create the filter element inside the listener
	$filter = $xml.CreateElement("filter")
	$filter.SetAttribute("type", "System.Diagnostics.EventTypeFilter")
	$filter.SetAttribute("initializeData", "Information")
	# Create the add element to add the shared listener
	$tracelistenernode = $xml.CreateElement("add")
	$tracelistenernode.SetAttribute("name", "TextFileLogListener")
	$tracelistenernode.SetAttribute("type", "System.Diagnostics.TextWriterTraceListener")
	$tracelistenernode.SetAttribute("initializeData", "c:\\log.txt")
	# Here is the filter added
	# You can use "fluent style" navigation
	# Now create an entry in the trace listeners to the shared listener
	$listener = $xml.CreateElement("add")
	$listener.SetAttribute("name", "TextFileLogListener")
	# Save the config to disk

You can run the script above and see the changes it makes to the config file. To prevent errors on multiple runs, the script checks the presence of TextFileLogListener and will only add it once.

This is part of our Automate test environment with Azure Virtual Machines script.

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 Tooling and tagged , , , , , . Bookmark the permalink.

Leave a Reply

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

You are commenting using your 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