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?
The recommendations are as follows:
_logger.Info("test");
_logger.Info("test with {0}", "value");
_logger.Info(() => expensiveOperation);
or _logger.Info(() => {expensiveOperation()});
_logger.IsInfoEnabled
etc. before writingIf 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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With