Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use the NLog LogMessageGenerator delegate?

Tags:

c#

nlog

If I want to achieve best possible performance with NLog is there anything I should do in my code to achieve this?

(Of course I have async enabled in the NLog.config.)

What about using the delegate to write log messages?

_logger.Info(() => { return "test" });

Unfortunately I couldn't figure out how to use this "properly". Is this even documented?

_logger.Info(() => { return string.Format("msg", myParams); }); // Is that the way to go?
like image 966
lapsus Avatar asked Aug 04 '16 08:08

lapsus


2 Answers

The recommendations are as follows:

  • For a plain string, just pass it _logger.Info("test");
  • For a string with parameters, use the overloads _logger.Info("test with {0}", "value");
  • For an expensive operation, use _logger.Info(() => expensiveOperation); or _logger.Info(() => {expensiveOperation()});
  • When writing extensions/wrappers etc. You can also check _logger.IsInfoEnabled etc. before writing
like image 63
Julian Avatar answered Nov 11 '22 12:11

Julian


If I want to achieve best possible performance with NLog

The purpose of overloads, which accept LogMessageGenerator, is to defer log message construction.

This could be useful for cases, when logger is being called from thread, which need to be highly responsible (UI thread or HTTP request threads are good examples), and you know, that building of particular log message is time consuming.

Using these overloads and asynchronous logging, NLog will return control to caller ASAP, and will execute passed delegate later on background thread.

That's all.
I mean, that passing delegates here and there will not make your or NLog code faster. Moreover, this:

_logger.Info(() => { return "test" });

will be slower, comparing to:

_logger.Info("test");

because of method call overhead instead of using existing string literal.

P.S.

Note, that lambda expressions, used to construct delegates, could be written in more simple way:

_logger.Info(() => "test");
_logger.Info(() => string.Format("msg", myParams));

Again, this isn't about performance, but about readability.

like image 3
Dennis Avatar answered Nov 11 '22 10:11

Dennis