What are the best or most useful configurations for logging with NLog? (These can be simple or complex, as long as they're useful.)

I'm thinking of examples like automatically rolling over log files at a certain size, changing the layout (log message) whether or not there is an exception, escalating the log level once an error has occurred, etc.

There are either too many possible answers, or good answers would be too long for this format. Please add details to narrow the answer set or to isolate an issue that can be answered in a few paragraphs.
If this question can be reworded to fit the rules in the help center, please edit the question.

8

200 upvotes and its closed.. yes i know rules are rules but this just seems wrong...
–
PeterOct 20 '14 at 14:24

Use the common pattern of naming your logger based on the class Logger logger = LogManager.GetCurrentClassLogger(). This gives you a high degree of granularity in your loggers and gives you great flexibility in the configuration of the loggers (control globally, by namespace, by specific logger name, etc).

Use non-classname-based loggers where appropriate. Maybe you have one function for which you really want to control the logging separately. Maybe you have some cross-cutting logging concerns (performance logging).

If you don't use classname-based logging, consider naming your loggers in some kind of hierarchical structure (maybe by functional area) so that you can maintain greater flexibility in your configuration. For example, you might have a "database" functional area, an "analysis" FA, and a "ui" FA. Each of these might have sub-areas. So, you might request loggers like this:

See the NLog help for more info on exactly what each of the options means. Probably the most notable items here are the ability to wildcard logger rules, the concept that multiple logger rules can "execute" for a single logging statement, and that a logger rule can be marked as "final" so subsequent rules will not execute for a given logging statement.

Use the GlobalDiagnosticContext, MappedDiagnosticContext, and NestedDiagnosticContext to add additional context to your output.

Use "variable" in your config file to simplify. For example, you might define variables for your layouts and then reference the variable in the target configuration rather than specify the layout directly.

If you roll your file daily, each file could be named "Monday.log", "Tuesday.log", etc.

Don't be afraid to write your own layout renderer. It is easy and allows you to add your own context information to the log file via configuration. For example, here is a layout renderer (based on NLog 1.x, not 2.0) that can add the Trace.CorrelationManager.ActivityId to the log:

NLog 2.0 adds LayoutRenderer wrappers that allow additional processing to be performed on the output of a layout renderer (such as trimming whitespace, uppercasing, lowercasing, etc).

Don't be afraid to wrap the logger if you want insulate your code from a hard dependency on NLog, but wrap correctly. There are examples of how to wrap in the NLog's github repository. Another reason to wrap might be that you want to automatically add specific context information to each logged message (by putting it into LogEventInfo.Context).

There are pros and cons to wrapping (or abstracting) NLog (or any other logging framework for that matter). With a little effort, you can find plenty of info here on SO presenting both sides.

If you are considering wrapping, consider using Common.Logging. It works pretty well and allows you to easily switch to another logging framework if you desire to do so. Also if you are considering wrapping, think about how you will handle the context objects (GDC, MDC, NDC). Common.Logging does not currently support an abstraction for them, but it is supposedly in the queue of capabilities to add.

can u tell me what to do for remort connection? the thing works for me for localhost but when i have given some ip address in host it is not working!!
–
NeelNov 13 '13 at 10:35

@Neel, you should check the "Security" settings in Growl on the target computer. You have to explicitly enable "LAN" notifications and you might want to setup a password (which you would then need to add to your NLog target). But I didn't like that the remote notifications showed-up in Growl with an "Origin" of "Local Machine"; I'd have to add the host to the log entries to know where notifications originated.
–
Kenny EvittMay 7 '14 at 19:05

Treating exceptions differently

We often want to get more information when there is an exception. The following configuration has two targets, a file and the console, which filter on whether or not there is any exception info. (EDIT: Jarek has posted about a new method of doing this in vNext.)

The key is to have a wrapper target with xsi:type="FilteringWrapper" condition="length('${exception}')>0"

That's pretty cool with the separate target and FilteringWrapper to format the exception. I just answered a question recently from a guy that wanted to include the {exception} layout renderer in his output but he did not want to get the () that is apparently logged if there is NOT an exception. This technique would probably work well for him.
–
wageogheNov 4 '10 at 21:36

+1 Very nice. I've had this bookmarked for a long time, and got referred to "Pat's comment" from another SO question in regards to a conditional layout.
–
eduncan911Feb 27 '12 at 2:36

I just tried it tomorrow in my project, since you set a rule minlevel="Warn" to "file, fileAsException", all logs will be logged first with file target (no filter), and if it is an exception (as filtered by condition) it'll be also logged with fileAsException.
–
Tien DoApr 4 '12 at 4:50

2

@Tiendq Oh, I see. That makes sense, although the exception itself (in full detail) will only be logged once (but its message will be logged twice). You can probably fix that by adding condition="length('${exception}')=0 (or maybe it's ==) to target name="file".
–
PatApr 4 '12 at 17:37

What? Did you know that you can specify the NLog XML directly to NLog from your app, as opposed to having NLog read it from the config file? Well, you can. Let's say that you have a distributed app and you want to use the same configuration everywhere. You could keep a config file in each location and maintain it separately, you could maintain one in a central location and push it out to the satellite locations, or you could probably do a lot of other things. Or, you could store your XML in a database, get it at app startup, and configure NLog directly with that XML (maybe checking back periodically to see if it had changed).

it works very well... except by using this it is no longer possible to dynamically re-configure the logging system. This is especially so if you link to an outside file (include)
–
NewtopianFeb 7 '13 at 19:06

This worked, although I had to write "good" XML by including: <?xml version='1.0' encoding='utf-8' ?><nlog xmlns='http://nlog-project.org/schemas/NLog.xsd' xmlns:xsi='http://www.w3.org/2001/XMLSchema-instance'>
–
GadySep 22 '14 at 18:13

Logging different levels depending on whether or not there is an error

This example allows you to get more information when there is an error in your code. Basically, it buffers messages and only outputs those at a certain log level (e.g. Warn) unless a certain condition is met (e.g. there has been an error, so the log level is >= Error), then it will output more info (e.g. all messages from log levels >= Trace). Because the messages are buffered, this lets you gather trace information about what happened before an Error or ErrorException was logged - very useful!

I adapted this one from an example in the source code. I was thrown at first because I left out the AspNetBufferingWrapper (since mine isn't an ASP app) - it turns out that the PostFilteringWrapper requires some buffered target. Note that the target-ref element used in the above-linked example cannot be used in NLog 1.0 (I am using 1.0 Refresh for a .NET 4.0 app); it is necessary to put your target inside the wrapper block. Also note that the logic syntax (i.e. greater-than or less-than symbols, < and >) has to use the symbols, not the XML escapes for those symbols (i.e. &gt; and &lt;) or else NLog will error.

The question wanted to know how to add a header to the log file. Using config entries like this allow you to define the header format separately from the format of the rest of the log entries. Use a single logger, perhaps called "headerlogger" to log a single message at the start of the application and you get your header:

GlobalDiagnosticsContext.Set("version", "01.00.00.25");
LogManager.GetLogger("headerlogger").Info("It doesn't matter what this is because the header format does not include the message, although it could");

This is largely just another version of the "Treating exceptions differently" idea.

Log each log level with a different layout

Similarly, the poster wanted to know how to change the format per logging level. It wasn't clear to me what the end goal was (and whether it could be achieved in a "better" way), but I was able to provide a configuration that did what he asked:

Based on this post about a log4net Twitter Appender, I thought I would try my hand at writing a NLog Twitter Target (using NLog 1.0 refresh, not 2.0). Alas, so far I have not been able to get a Tweet to actually post successfully. I don't know if it is something wrong in my code, Twitter, our company's internet connection/firewall, or what. I am posting the code here in case someone is interested in trying it out. Note that there are three different "Post" methods. The first one that I tried is PostMessageToTwitter. PostMessageToTwitter is essentially the same as PostLoggingEvent in the orignal post. If I use that I get a 401 exception. PostMessageBasic gets the same exception. PostMessage runs with no errors, but the message still does not make it up to Twitter. PostMessage and PostMessageBasic are based on examples that I found here on SO.

FYI - I just now found a comment by @Jason Diller to an answer in this post that says that twitter is going to turn off basic authentication "next month". This was back in May 2010 and it is now December 2010, so I guess that could be why this is not working.

Reporting to an external website/database

I wanted a way to simply and automatically report errors (since users often don't) from our applications. The easiest solution I could come up with was a public URL - a web page which could take input and store it to a database - that is sent data upon an application error. (The database could then be checked by a dev or a script to know if there are new errors.)

I wrote the web page in PHP and created a mysql database, user, and table to store the data. I decided on four user variables, an id, and a timestamp. The possible variables (either included in the URL or as POST data) are:

app (application name)

msg (message - e.g. Exception occurred ...)

dev (developer - e.g. Pat)

src (source - this would come from a variable pertaining to the machine on which the app was running, e.g. Environment.MachineName or some such)

log (a log file or verbose message)

(All of the variables are optional, but nothing is reported if none of them are set - so if you just visit the website URL nothing is sent to the db.)

To send the data to the URL, I used NLog's WebService target. (Note, I had a few problems with this target at first. It wasn't until I looked at the source that I figured out that my url could not end with a /.)

All in all, it's not a bad system for keeping tabs on external apps. (Of course, the polite thing to do is to inform your users that you will be reporting possibly sensitive data and to give them a way to opt in/out.)

MySQL stuff

(The db user has only INSERT privileges on this one table in its own database.)

This worked for one project, but in others I have had issues with the url: InnerException: System.InvalidCastException Message=Invalid cast from 'System.String' to 'System.Uri'. Source=mscorlib StackTrace: at System.Convert.DefaultToType(IConvertible value, Type targetType, IFormatProvider provider) at System.String.System.IConvertible.ToType(Type type, IFormatProvider provider) at System.Convert.ChangeType(Object value, Type conversionType, IFormatProvider provider)
–
PatNov 24 '10 at 18:19

I have fooled around with writing a NLog TwitterTarget but have not had success actually getting a Tweet posted. I have posted the code as an answer. Feel free to try it out if you would like.
–
wageogheDec 1 '10 at 20:38

When using NLog with Silverlight you can send the trace to the server side via the provided web service. You can also write to a local file in the Isolated Storage, which come in handy if the web server is unavailable. See here for details, i.e. use something like this to make yourself a target: