Logging from your code - MikeHanson/NLog.Mvc GitHub Wiki
Hopefully by now you have NLog.Mvc setup and configured, if not please visit [Setting up the database](Setting up the database) and [Configuring the NLog target](Configuring the NLog target) before trying anything shown here.
NLog.Mvc includes a utility Logger class that can be instantiated directly or injected into your components using an IoC container.
NLog supports five levels that can be applied to log entries, Trace, Debug, Info, Warn and Error. The NLog.Mvc.Logger provides methods for each level and there are three overloads of each method. So given an instance of the logger you simply call a method corresponding to the level applicable to the entry, something like this:
logger.Trace(...);
logger.Debug(...);
logger.Information(...);
logger.Warning(...);
logger.Error(...);
Whether a call to one of these methods actually generates a log entry is controlled through configuration, so you can safely put as much logging in your code as you feel appropriate then control what actually gets written to the database by setting level related attributes of <logger>
element in the NLog configuration. For more information about controlling logging see NLog Rules.
Each of these level methods has three overloads:
logger.Method(string message);
logger.Method(Func<string> messageGenerator);
logger.Method(string message, Exception exception);
The first allows you to log a simple message. For complex messages you can use the second overload passing a delegate that builds the message, perhaps based on inputs. The last is specifically for logging Exceptions and is used in the NLogMvcHandleErrorAttribute covered in a separate [page](Using the NLogMvcHandleErrorAttribute).
As mentioned previously you can inject the logger as a dependency of any component using an IoC container. For an example of doing this with AutoFac see Bootstrapper.cs
in the NLog.Mvc.4.Web project.