# Deploying NLog configuration files

25 Sep 2010

Some of the targets supported by NLog require installation to be performed on the machine before the target can be used. For example, when logging to a database, a DBA needs to create the necessary tables, when logging to event log or performance counter, administrator of the machine must create them before the application can write to them.

NLog 2.0 comes with a new tool and APIs that lets you manage installation and uninstallation of objects which support logging.

Say you want to write logs to:

• local SQLEXPRESS database
• Event Log on the local machine
• increase performance counter each time log message occurs.

With NLog 2.0, you can embed installation/uninstallations steps directly in the log configuration file, like in the following example:

In order to deploy the database, event log and performance counter, you can use simply use InstallNLogConfig.exe tool that comes with NLog. Open elevated command prompt and run the following command:

> InstallNLogConfig.exe c:\path\to\NLog.config
Installing 'Database Target[db]'
Finished installing 'Database Target[db]'.
Installing 'EventLog Target[eventLog]'
Finished installing 'EventLog Target[eventLog]'.
Installing 'PerfCounter Target[pc1]'
Finished installing 'PerfCounter Target[pc1]'.


Uninstalling is equally easy:

> InstallNLogConfig.exe" -u c:\path\to\NLog.config
Uninstalling 'Database Target[db]'
Finished uninstalling 'Database Target[db]'.
Uninstalling 'EventLog Target[eventLog]'
Finished uninstalling 'EventLog Target[eventLog]'.
Uninstalling 'PerfCounter Target[pc1]'
Finished uninstalling 'PerfCounter Target[pc1]'.


## Passing parameters to installation

Sometimes there is a need to pass parameters to the installation routing, which should not be normally visible in the NLog.config file. One example might be DBA username and password for connecting to the database. You can pass parameters on the command line by using –p NAME=VALUE option:

> InstallNLogConfig.exe" –p ADMIN_USER=sa –p ADMIN_PASSWORD=megaSecret1234 c:\path\to\NLog.config


The parameters are accessible using \${install-context} layout renderer. For example, we can easily modify the above example to use SQL authentication where user name and password are passed from command line:

## Installation API

In order to install logging configuration, you can simply use Install() and Uninstall() methods on LoggingConfiguration object. They both take InstallationContext arguments, which can be used pass parameters and specify logging and other options:

Typical installation code will look like this:

In order to support custom installation in your target or any other configuration item (such as layout, filter, etc.), you simply need to implement IIinstallable interface:

See DatabaseTarget sources for example implementation.