2014-01-18 53 views
2

testlog.java:如何在類/方法名稱的groovy中配置java.util.logging?

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 

如何配置常規類/米ethod名稱而不是「java_util_logging_Logger $ info call」?

+0

感謝我展示我所需要的格式! –

回答

1

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約定中的源代碼轉換爲字節碼。

這裏是腳本應該如何看(注: - 類名是駝峯):

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

當然,它的工作方式...但恕我直言,這太多了。 @CompileStatic對我不好。 Tnx,現在我明白了爲什麼它以這種方式工作,我會嘗試寫我自己的格式化程序。 –

相關問題