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:
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:
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: