Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    text
    copied!<p>In Python you pass the formatted values as parameters to the logging function. String formatting is only applied if logging is enabled. There's still the overhead of a function call, but that's minuscule compared to formatting.</p> <pre><code>log.info ("a = %s, b = %s", a, b) </code></pre> <p>You can do something like this for any language with variadic arguments (C/C++, C#/Java, etc).</p> <hr> <p>This isn't really intended for when the arguments are difficult to retrieve, but for when formatting them to strings is expensive. For example, if your code already has a list of numbers in it, you might want to log that list for debugging. Executing <code>mylist.toString()</code> will take a while to no benefit, as the result will be thrown away. So you pass <code>mylist</code> as a parameter to the logging function, and let it handle string formatting. That way, formatting will only be performed if needed.</p> <hr> <p>Since the OP's question specifically mentions Java, here's how the above can be used:</p> <blockquote> <p>I must insist that the problem is not 'formatting' related, but 'argument evaluation' related (evaluation that can be very costly to do, just before calling a method which will do nothing)</p> </blockquote> <p>The trick is to have objects that will not perform expensive computations until absolutely needed. This is easy in languages like Smalltalk or Python that support lambdas and closures, but is still doable in Java with a bit of imagination.</p> <p>Say you have a function <code>get_everything()</code>. It will retrieve every object from your database into a list. You don't want to call this if the result will be discarded, obviously. So instead of using a call to that function directly, you define an inner class called <code>LazyGetEverything</code>:</p> <pre><code>public class MainClass { private class LazyGetEverything { @Override public String toString() { return getEverything().toString(); } } private Object getEverything() { /* returns what you want to .toString() in the inner class */ } public void logEverything() { log.info(new LazyGetEverything()); } } </code></pre> <p>In this code, the call to <code>getEverything()</code> is wrapped so that it won't actually be executed until it's needed. The logging function will execute <code>toString()</code> on its parameters only if debugging is enabled. That way, your code will suffer only the overhead of a function call instead of the full <code>getEverything()</code> call.</p>
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload