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
$xml.Load($configFile)
# 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
	$tracelistenernode.AppendChild($filter)
	# You can use "fluent style" navigation
	$xml.configuration.'system.diagnostics'.sharedListeners.AppendChild($tracelistenernode)
	# Now create an entry in the trace listeners to the shared listener
	$listener = $xml.CreateElement("add")
	$listener.SetAttribute("name", "TextFileLogListener")
	$xml.configuration.'system.diagnostics'.trace.listeners.AppendChild($listener)
	# Save the config to disk
	$xml.Save($configFile)
}

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

Working in a DevOps team is the best thing that happened to me. 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:

WordPress.com Logo

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

Facebook photo

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

Connecting to %s

This site uses Akismet to reduce spam. Learn how your comment data is processed.