|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||
|
Announcements
Chapters
Services
Feature Zones
|
IntroductionOnce upon a time, when there were no debuggers in the world and software was mostly console-based, programmers used to output tracing messages using We've all written code similar to the following: static void Main()
{
Console.WriteLine("SuperApp started.");
DoSomething();
Console.WriteLine("SuperApp finished.");
}
After giving the application some testing, we tend to remove the tracing code in order to improve performance (tracing can take a lot of time). Tracing instructions are usually commented out so that they can be re-enabled in the future. Unfortunately, this requires our program to be recompiled. Some time later, after removing hundreds of comments and putting them back for the nth time, we get the feeling that our tracing solution is not perfect and we could benefit from:
It may seem that in the age of graphical debuggers, the usefulness of tracing-based solutions is limited. Sometimes, tracing turns out to be the only tool available, which can be used to locate bug in a mission-critical system that cannot be switched off for a single minute. What is NLog?NLog is a .NET library which enables you to add sophisticated tracing code to your application, delivering the functionality mentioned above and much, much more. NLog lets you write rules which control the flow of diagnostic traces from their sources to targets, which could be:
In addition, each tracing message can be augmented with pieces of contextual information, which will be sent with it to the target. The contextual information can include:
Each tracing message is associated with a log level which describes its severity. NLog supports the following levels:
NLog is an open source library distributed at no cost under the terms of the BSD license, which permits commercial usage with almost no obligation. You can download the NLog binary and source code releases from its website. A graphical installer is also provided, which lets you install NLog in a preferred place, and enables integration with Visual Studio 2005 (Express editions are also supported), including:
Our first NLog-enabled applicationLet's create our first application that uses NLog, using Visual Studio 2005. We'll start with a simple example that only logs to the console, and we'll be adding features that demonstrate how easy it is to control logging configuration in NLog. The first step is to create a Visual Studio project (in this example, we'll be using C#), and to add an NLog configuration file using the "Add New Item..." dialog. Let's add an "Empty NLog Configuration File" and save it as "NLog.config":
Notice how a reference to the NLog.dll was automatically added to our project. The contents of the NLog.config file, which we'll be modifying in this tutorial, are: <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<targets>
</targets>
<rules>
</rules>
</nlog>
You only need to do one more thing: change the "Copy To Output Directory" option for this file to "Copy always". This way, our configuration file will be placed in the same directory as the *.exe file, and NLog will be able to pick it up without any special configuration.
It's time to configure the log output. In the <targets>
<target name="console" xsi:type="Console"
layout="${longdate}|${level}|${message}" />
</targets>
Notice how Visual Studio suggests the possible XML element names and attribute names/values. Once we type xsi:, we get a list of available log targets.
In the <rules>
<logger name="*" minlevel="Debug" writeTo="console" />
</rules>
In order to send a diagnostic message, we use a Let's modify the wizard-generated C# file by adding a " using System;
using System.Collections.Generic;
using System.Text;
using NLog;
namespace NLogExample
{
class Program
{
private static Logger logger = LogManager.GetCurrentClassLogger();
static void Main(string[] args)
{
logger.Debug("Hello World!");
}
}
}
The result of running this program is a message written to the console which includes the current date, log level ( Let's see how we achieved this:
A more advanced logging scenarioLet's record our log messages, along with some contextual information such as the the current stack trace, to both a file and the console. To do this, we need to define another target of type "File" and tell the <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
<targets>
<target name="console" xsi:type="ColoredConsole"
layout="${date:format=HH\:mm\:ss}|${level}|${stacktrace}|${message}" />
<target name="file" xsi:type="File" fileName="${basedir}/file.txt"
layout="${stacktrace} ${message}" />
</targets>
<rules>
<logger name="*" minlevel="Trace" writeTo="console,file" />
</rules>
</nlog>
Here's the C# source code that emits some more log messages; additional methods are introduced here to observe the stack trace feature. static void C()
{
logger.Info("Info CCC");
}
static void B()
{
logger.Trace("Trace BBB");
logger.Debug("Debug BBB");
logger.Info("Info BBB");
C();
logger.Warn("Warn BBB");
logger.Error("Error BBB");
logger.Fatal("Fatal BBB");
}
static void A()
{
logger.Trace("Trace AAA");
logger.Debug("Debug AAA");
logger.Info("Info AAA");
B();
logger.Warn("Warn AAA");
logger.Error("Error AAA");
logger.Fatal("Fatal AAA");
}
static void Main(string[] args)
{
logger.Trace("This is a Trace message");
logger.Debug("This is a Debug message");
logger.Info("This is an Info message");
A();
logger.Warn("This is a Warn message");
logger.Error("This is an Error message");
logger.Fatal("This is a Fatal error message");
}
When we run the program, the following information will be written to the "file.txt" in the application directory: Program.Main This is a Trace message
Program.Main This is a Debug message
Program.Main This is an Info message
Program.Main => Program.A Trace AAA
Program.Main => Program.A Debug AAA
Program.Main => Program.A Info AAA
Program.Main => Program.A => Program.B Trace BBB
Program.Main => Program.A => Program.B Debug BBB
Program.Main => Program.A => Program.B Info BBB
Program.A => Program.B => Program.C Info CCC
Program.Main => Program.A => Program.B Warn BBB
Program.Main => Program.A => Program.B Error BBB
Program.Main => Program.A => Program.B Fatal BBB
Program.Main => Program.A Warn AAA
Program.Main => Program.A Error AAA
Program.Main => Program.A Fatal AAA
Program.Main This is a Warn message
Program.Main This is an Error message
Program.Main This is a Fatal error message
At the same time, we get this fancy colored output on the console:
Now, let's modify our configuration a bit. The typical requirement is to have a different level of detail depending on the output. For example, we only want messages whose level is <rules>
<logger name="*" minlevel="Info" writeTo="console" />
<logger name="*" minlevel="Trace" writeTo="file" />
</rules>
After running the program, we find that Logging configurationIt's now time to describe the NLog configuration mechanism. Unlike other tools, NLog attempts to automatically configure itself on startup, by looking for the configuration files in some standard places. The following locations will be searched when executing a standalone *.exe application:
In the case of an ASP.NET application, the following files are searched:
The .NET Compact Framework doesn't recognize application configuration files (*.exe.config) nor environmental variables, so NLog only looks in these locations:
Configuration file formatNLog supports two configuration file formats:
In the first variant, we use a standard <?xml version="1.0" encoding="utf-8" ?>
<configuration>
<configSections>
<section name="nlog" type="NLog.Config.ConfigSectionHandler, NLog" />
</configSections>
<nlog>
</nlog>
</configuration>
The simplified format is the pure XML having the <?xml version="1.0" encoding="utf-8" ?>
<nlog xmlns="http://www.nlog-project.org/schemas/NLog.xsd"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" >
</nlog>
Note that NLog config files are case-insensitive when not using namespaces, and are case-sensitive when you use them. Intellisense only works with case-sensitive configurations. Configuration elementsYou can use the following elements as children to
TargetsThe
In addition to these, targets usually accept other parameters, which influence the way diagnostic traces are written. Each target has a different set of parameters, they are described in detail on the project's homepage, and context-sensitive Intellisense is also available in Visual Studio. For example - the " NLog provides many predefined targets. They are described on the project's homepage. It's actually very easy to create your own target - it requires about 15-20 lines of code and is described in the documentation. RulesLog routing rules are defined in the Each routing table entry is a
Some examples:
In the simplest cases, the entire logging configuration consists of a single Contextual informationOne of NLog's strongest assets is the ability to use layouts. They include pieces of text surrounded by a pair of "${" (dollar sign + left curly brace) and "}" (right curly brace). The markup denotes "layout renderers" which can be used to insert pieces of contextual information into the text. Layouts can be used in many places. For example, they can control the format of information written on the screen or sent to a file, but also control the file names themselves. This is very powerful, which we'll see in a moment. Let's assume that we want to augment each message written to the console with:
This is very easy: <target name="c" xsi:type="Console"
layout="${longdate} ${callsite} ${level} ${message}" />
We can make each message for each logger go to a separate file, as in the following example: <target name="f" xsi:type="File" fileName="${logger}.txt" />
As you can see, the
It's a frequent requirement to be able to keep log files for each day separate. This is trivial, too, thanks to the <target name="f" xsi:type="File" filename="${shortdate}.txt" />
How about giving each employee their own log file? The <target name="f" xsi:type="File"
filename="${windows-identity:domain=false}.txt" />
Thanks to this simple setting, NLog will create a set of files named after our employees' logins:
More complex cases are, of course, possible. The following sample demonstrates the way of creating a distinct log file for each person per day. Log files for each day are stored in a separate directory: <target name="f" xsi:type="File"
filename="${shortdate}/${windows-identity:domain=false}.txt" />
This creates the following files:
NLog provides many predefined layout renderers. They are described on the website. It's very easy to create your own layout renderer. It just takes 15-20 lines of code, and is described in the documentation section of the project website. Include filesIt's sometimes desired to split the configuration file into many smaller ones. NLog provides an include file mechanism for that. To include an external file, you simply use the following code. It is worth noting that the <nlog>
...
<include file="${basedir}/${machinename}.config" />
...
</nlog>
Variables let us write complex or repeatable expressions (such as file names) in a concise manner. To define a variable, we use the <nlog>
<variable name="logDirectory" value="${basedir}/logs/${shortdate}" />
<targets>
<target name="file1" xsi:type="File" filename="${logDirectory}/file1.txt" />
<target name="file2" xsi:type="File" filename="${logDirectory}/file2.txt" />
</targets>
</nlog>
Automatic reconfigurationThe configuration file is read automatically at program startup. In a long running process (such as a Windows service or an ASP.NET application), it's sometimes desirable to temporarily increase the log level without stopping the application. NLog can monitor logging configuration files and re-read them each time they are modified. To enable this mechanism, you simply set Troubleshooting loggingSometimes our application doesn't write anything to the log files, even though we have supposedly configured logging properly. There can be many reasons for logs not being written. The most common problem is permissions, usually in an ASP.NET process, where the aspnet_wp.exe or the w3wp.exe process may not have write access to the directory where we want to store logs. NLog is designed to swallow run-time exceptions that may result from logging. The following settings can change this behavior and/or redirect these messages.
Asynchronous processing, wrappers, and compound targetsNLog provides wrappers and compound targets which modify other targets' behaviour, by adding features like:
To define a wrapper or compound target in the configuration file, simply nest a <targets>
<target name="n" xsi:type="AsyncWrapper">
<target xsi:type="RetryingWrapper">
<target xsi:type="File" fileName="${file}.txt" />
</target>
</target>
</targets>
Because asynchronous processing is a common scenario, NLog supports a shorthand notation to enable it for all targets without the need to specify explicit wrappers. You simply set Programmatic configurationIn certain cases, you may choose not to use a configuration file, but to configure NLog using the provided API. The full description of this feature is beyond the scope of this article, so let's just outline the steps necessary to make it work. To configure NLog in your code, you need to:
This sample demonstrates the programmatic creation of two targets: one is a colored console, and the other is a file and rules that send messages to them for messages whose level is using NLog;
using NLog.Targets;
using NLog.Config;
using NLog.Win32.Targets;
class Example
{
static void Main(string[] args)
{
// Step 1. Create configuration object
LoggingConfiguration config = new LoggingConfiguration();
// Step 2. Create targets and add them to the configuration
ColoredConsoleTarget consoleTarget = new ColoredConsoleTarget();
config.AddTarget("console", consoleTarget);
FileTarget fileTarget = new FileTarget();
config.AddTarget("file", fileTarget);
// Step 3. Set target properties
consoleTarget.Layout = "${date:format=HH\\:MM\\:ss} ${logger} ${message}";
fileTarget.FileName = "${basedir}/file.txt";
fileTarget.Layout = "${message}";
// Step 4. Define rules
LoggingRule rule1 = new LoggingRule("*", LogLevel.Debug, consoleTarget);
config.LoggingRules.Add(rule1);
LoggingRule rule2 = new LoggingRule("*", LogLevel.Debug, fileTarget);
config.LoggingRules.Add(rule2);
// Step 5. Activate the configuration
LogManager.Configuration = config;
// Example usage
Logger logger = LogManager.GetLogger("Example");
logger.Trace("trace log message");
logger.Debug("debug log message");
logger.Info("info log message");
logger.Warn("warn log message");
logger.Error("error log message");
logger.Fatal("fatal log message");
}
}
What else is possible with NLog?NLog supports some more logging scenarios, which couldn't be fully described here. See the links below for more information:
More informationAdditional information about NLog can be found in the project homepage. Developers are welcome to join the project. There's a mailing list available, to which you can subscribe. History
| |||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||