testlog.java:
import java.util.logging.Logger;
public class testlog {
private final static Logger log = Logger.getLogger(testlog.class.getName());
public static void main(String[] args) {
System.setProperty("java.util.logging.SimpleFormatter.format","[%1$tF %1$tT]:%4$s:(%2$s): %5$s%n");
log.info("logging test");
}
}
执行:
$ java testlog
[2014-01-18 11:08:51]:INFO:(testlog main): logging test
testlog.groovy:
import java.util.logging.Logger;
public class testlog {
private final static Logger log = Logger.getLogger("testlog");
public static void main(String[] args) {
System.setProperty("java.util.logging.SimpleFormatter.format",'[%1$tF %1$tT]:%4$s:(%2$s): %5$s%n');
log.info("logging test");
}
}
执行:
$ groovy testlog
[2014-01-18 11:11:23]:INFO:(java_util_logging_Logger$info call): logging test
如何为类/方法名称而不是“java_util_logging_Logger $ info call”配置groovy?
答案 0 :(得分:3)
Groovy通常在字节码中使用CallSite
。上面提到的Groovy代码将编译为以下格式的字节码:
import groovy.lang.GroovyObject;
import groovy.lang.MetaClass;
import java.util.logging.Logger;
import org.codehaus.groovy.runtime.ScriptBytecodeAdapter;
import org.codehaus.groovy.runtime.callsite.CallSite;
public class testlog
implements GroovyObject
{
private static final Logger log;
static
{
__$swapInit();long l1 = 0L;__timeStamp__239_neverHappen1390064566496 = l1;
long l2 =
1390064566495L;__timeStamp = l2;
Object localObject =
$getCallSiteArray()
[2].call(Logger.class, "testlog");log =
(Logger)ScriptBytecodeAdapter.castToType(localObject, Logger.class);
}
public static void main(String... args)
{
CallSite[] arrayOfCallSite =
$getCallSiteArray();arrayOfCallSite[0].call(System.class,
"java.util.logging.SimpleFormatter.format",
"[%1$tF %1$tT]:%4$s:(%2$s): %5$s%n");
arrayOfCallSite[1].call(log, "logging test");
}
public testlog()
{
testlog this;
CallSite[] arrayOfCallSite = $getCallSiteArray();
MetaClass localMetaClass = $getStaticMetaClass();
this.metaClass = localMetaClass;
}
}
因此,当从格式化程序引用时,它引用Log
类。要解决这个问题,您可以在类级别使用CompileStatic
注释,它将源代码转换为普通Java约定中的字节码。
以下是脚本的外观(注意: - 类名是CamelCase):
import java.util.logging.Logger
import groovy.transform.CompileStatic
@CompileStatic
public class Testlog {
private final static Logger log = Logger.getLogger("testlog")
public static void main(String[] args) {
System.setProperty("java.util.logging.SimpleFormatter.format",
'[%1$tF %1$tT]:%4$s:(%2$s): %5$s%n')
log.info("logging test")
}
}