Configuring the nlog target - MikeHanson/NLog.Mvc GitHub Wiki
NLog uses targets specfied and configured via code or configuration file to control where log entries are written. NLog.Mvc provides the custom DbContextTarget, which uses a DbContext to write log entries to a database. You must configure DbContextTarget with a connection string name. There are two steps to configuring the target, first you declare the NLog section and section handler then you create the NLog section.
The following steps assume you have installed the NuGet package, which includes a dependency on Entity Framework. This dependency will ensure that you have a <configSections>
element in your config file.
- Add the following section declaration to the
<configSections>
element of your web.config file:
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog"/>
- Add the following
nlog
section to the top level of your web.config file
<nlog>
<extensions>
<add assembly="NLog.Mvc"/>
</extensions>
<targets>
<target name="NLogMvcLogger"
type="DbContextTarget"
ConnectionStringName="LoggingContext"
layout="${longdate}|${level}|${logger}|${message}${onexception:|${exception:format=type}${exception:format=method}exception:format=message}|${exception:format=stacktrace}}" />
</targets>
<rules>
<logger name="*" minLevel="Trace" appendTo="NLogMvcLogger"/>
</rules>
</nlog>
- The root of this section must match name in the declaration added in step 1
- Within the
<extensions>
element we add an entry for the NLog.Mvc assembly. This tells NLog where to find the custom target - Within the
<targets>
element we add a declaration for the custom target. You can change the name if you wish as long as you also change the reference to in in the rules.- The type attribute references the type name of the custom target in the referenced assembly
- The ConnectionStringName is required and must match an existing connection string at run time
- I recommend leaving the layout attribute as is, but if you are not going to use the custom HandleErrorAttribute included with NLog.Mvc or any of the logging methods that accept an exception you can remove it and rely on the default.
- The layout attribute specifies the format for building a message string from an EventInfo instance that is passed to the DbContextTarget.
- DbContextTarget depends on receiving a pipe delimited set of values and will throw an 'InvalidLayoutException' if the layout value is invalid.
- Within the
<rules>
element we define a single rule that all log entries are handled by the target named in the appendTo attribute- We also specify the minimum level of entry that will actually be written to the database. Here we have set the minumum level to Trace so everything will be written. In a production system you are likely to set this Warn or Error.
Thats it you are now ready to log to a database using NLog.Mvc