gpt4 book ai didi

logging - 如何在 groovy 中为类/方法名称配置 java.util.logging?

转载 作者:行者123 更新时间:2023-12-02 14:07:26 25 4
gpt4 key购买 nike

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

测试日志.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

如何为类/方法名称配置groovy而不是“java_util_logging_Logger$info call”?

最佳答案

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")
}
}

关于logging - 如何在 groovy 中为类/方法名称配置 java.util.logging?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21201305/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com