سؤال

I am looking for some guidelines on using log4Net in a UI application. Will highly appreciate all the pointers on this.

Along with the others you may want to mention, one thing I specifically want to know is - which approach is better - putting multiple log statements or just one long one.

For e.g.

logger.Info("Server Name: " + serverName);
logger.Info("DB Name: " + dbName);
logger.Info("App version: " + appVersion);
etc

Or

logger.Info(string.Format("Server Name: {0}; DB Name: {1}; App version: {2}", 
       serverName, dbName, appVersion));

Mainly looking from the performance point of view (rather than readability).

Thanks.

هل كانت مفيدة؟

المحلول

It really depends on what kind of logging you will have. I personnally don't like the multiple logs approach because they can be separated depending on your appender and logging usage, but that is a personnal preference. Without a unifying token (thread id or whatever) it can be difficult to follow what is related in the logs.

As for the timing, @stuartd is right; the difference would be negligible; don't bother with it now, and time your code if you encounter problems later on; i'm pretty sure more interesting areas than the logging will pop up.

One point though: don't format your string directly as an argument to the logging call. log4net has some *Format methods (DebugFormat, ErrorFormat, etc...) that will execute the formatting only if the message should be logged, so it is arguably more efficient.

Some wrapper around log4net even add deferred evaluation of the logging string in order to avoid wasteful evaluation of the parameters in the case they won't be useful, but that's not vanilla log4net.

نصائح أخرى

From a performance point of view, single log events will definitely have some advantage over multiple calls, but how much depends on where you are logging to. If for example you are using a AdoNetAppender, then log calls are batched so there should be almost no difference, but if you are using a FileAppender and writing from multiple threads, then single log events will require less file locking, so there may be a measurable difference.

However performance should not be an issue unless you are logging too much - in your example, the difference would almost certainly be insignificant. However if you are really concerned about performance in your specific usage scenario, you should profile both approaches.

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top