<?xml version="1.0" encoding="UTF-8" ?>
<?xml-stylesheet type="text/xsl" href="style.xsl" ?>
<content lang="en" id="howto" subid="howto_optimize_performance">
<h1>How to optimize logging performance</h1>
<h4>Overview</h4>
<p>Logging can take a considerable amount of time. This document helps you understand why it happens so
and provides some performance tips that can speed up your logging.
</p>
<h4>Logging process described</h4>
<p>
Every time you use log a message several things need to be done to check if the message is
to be logged, and where to write the output to. Each call to <code>Debug, Info, Warn, Error,
Fatal</code> or the generic <code>Log</code> incolves the following operations:
</p>
<ol>
<li>The logging parameters are prepared. This is the job of a CLI runtime (.NET/Mono) and may introduce some considerable overhead - in most cases related to boxing or hidden array construction.</li>
<li>The appropriate logging method (<code>Debug(), Info(), Warn(), Error(), Fatal()</code> or <code>Log()</code>) is called with the prepared parameters.</li>
<li>The logging method roughly checks if the output is enabled for the specified logger at
the specified level. This is done very quickly (a single comparison) because of the data structures used.</li>
<li>If the previous check succeeded, there's still a chance that the message will not get logged
- in this step <a href="filters.html">filters</a> are evaluated and they have a chance to reject the method.
Note that filters can be expensive in terms of the time of execution.</li>
<li>After the message is qualified to be logged - the log message is formatted based on message and parameters
passed to the logging function. This can be pretty slow because the <code>String.Format</code>
isn't very fast.</li>
<li>The last step is passing the log event to one or more targets so that they can
to write the event to output. This is usually the most time-consuming part of the process because
targets are typically some kind of persistent storage (file, database) and it takes time
to write to such outputs.</li>
</ol>
<p>
"<i>This is bad news...</i>", you might think, but fortunately NLog provides many mechanisms that help
speed up your logging.
</p>
<h3>Performance Tips</h3>
<h4>Cache your logger instance</h4>
<p>Once you get your logger from <code>LogManager.GetLogger()</code> it's advised to store the reference
somewhere and reuse it without calling <code>LogManager.GetLogger()</code> again. A static member to your
class is quite a good idea. The following example describes it:
</p>
<cs src="examples/Performance.cs" />
<p style="class: red">TODO: add more tips here</p>
</content>