In some instances, I am interested in deferring the creation of the log message, so it won't be created in the case the log level is not sufficient.
I do it by passing a callback to a logging function, which is called if the logging level is sufficient.
The problem is I can't pass a variable which is not effectively final, because of closure limitations Java has.
What is a cleaner way to do it?
Running code: http://tpcg.io/IspNlN
import java.util.*;
import java.lang.*;
import java.io.*;
import java.util.function.Supplier;
public class StackOverflow
{
private static final int LOG_LEVEL=2;
private static final int TRACE_LEVEL=0;
private static void trace(Supplier<String> messageCallback){
if(TRACE_LEVEL>LOG_LEVEL) return;
System.out.println(messageCallback.get());
}
private static void foo(){
for(int i=0; i<10; i++){
doSomething();
int finalI=i; //I need it because of "Local variable parameterIndex defined in an enclosing scope must be final or effectively final"
trace(()->"FLOW-1: "+getHugeString()+" for i:"+finalI);
}
}
public static void main (String[] args) throws java.lang.Exception
{
foo();
}
private static void doSomething(){
//some operation
}
private static String getHugeString(){
return "A huge string that took much time to create";
}
}
You have three options mentioned in order of preference.
Option 1
Use a proper logging library.
Option 2 as pointed by @Glains
private static boolean isTraceEnabled()
{
return TRACE_LEVEL <= LOG_LEVEL;
}
private static void trace(String msg)
{
if (isTraceEnabled())
{
System.out.println(msg);
}
}
private static void foo()
{
for (int i = 0; i < 10; i++)
{
doSomething();
if (isTraceEnabled())
{
trace("FLOW-1: " + getHugeString() + " for i:" + i);
}
}
}
Option 3 use message format as in jdk logger.
private static void trace(String format, Object... values)
{
if (TRACE_LEVEL > LOG_LEVEL)
{
return;
}
for (int i = 0; i < values.length; i++)
{
Object value = values[i];
if (value instanceof Supplier)
{
values[i] = ((Supplier) value).get();
}
}
System.out.println(new MessageFormat(format).format(values));
}
invocation like
trace("FLOW-1: {0} for i: {1}", (Supplier) (StackOverflow::getHugeString), i);
Common logging frameworks offer methods like isDebugEnabled
or isInfoEnabled
to guard exactly against that case where Strings may take a longer time to be created.
if(LOG.isDebugEnabled()) {
LOG.debug("Some objects toString method called: {}", someObject.toString());
}
Besides that, your method also works, but has the limitations that you pointed out already.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.