2013-07-11 77 views
0

其中log4j2.xml應放置在applet中使用?它可以記錄到Java控制檯和用戶計算機上的文件嗎?配置log4j2以供小程序使用

+0

*「可以它既登錄到Java控制檯和**文件用戶的電腦嗎?」 ***只有當代碼進行數字簽名由你,並由最終用戶信任。 –

+0

是的,它已經簽署。我怎樣才能將log4j2.xml傳遞給applet?用戶磁盤上的什麼位置會顯示日誌? – YuriR

回答

0

我放置在小程序資源conf/log4j2.xml中並從小程序讀取它。 applet裝入它不正確的,所以我從固定applet代碼的字段:

public static Logger getLogger(Class className) { 

    //get logger configuration 
    LoggerContext loggerContext = Configurator.initialize("client", className.getClassLoader(), className.getClassLoader().getResource("conf/log4j2.xml").getFile()); 
    Configuration configuration = loggerContext.getConfiguration(); 

    //set root logger to desired level 
    LoggerConfig loggerConfig = configuration.getLoggerConfig(""); 
    loggerConfig.setLevel(Level.INFO); 

    //obtain appender 
    Appender appender = obtainAppender(configuration); 

    //get logger for required class 
    org.apache.logging.log4j.core.Logger loggerForClass = loggerContext.getLogger(className.getName()); 

    //associate logger for required class with just created appender 
    configuration.addLoggerAppender(loggerForClass, appender); 

    return loggerForClass; 
} 

private static Appender obtainAppender(Configuration configuration) { 

    //create appender 
    TriggeringPolicy[] triggeringPolicies = {OnStartupTriggeringPolicy.createPolicy(), TimeBasedTriggeringPolicy.createPolicy("5", "true"), SizeBasedTriggeringPolicy.createPolicy("5 MB")}; 
    TriggeringPolicy triggeringPolicy = CompositeTriggeringPolicy.createPolicy(triggeringPolicies); 
    return RollingFileAppender.createAppender(CLIENT_LOG_PATH + FileUtils.FILE_SEPARATOR + "my_client.log", 
      CLIENT_LOG_PATH + FileUtils.FILE_SEPARATOR + "/$${date:yyyy-MM}/my_client-%d{MM-dd-yyyy-HH-mm}-%i.log", 
      "", APPLET_APPENDER, 
      "true", "true", 
      triggeringPolicy, null, 
      PatternLayout.createLayout("%d{dd/MM/yyyy HH:mm:ss} %-5p [%t] [%c{1}] %m%n", configuration, null, "UTF-8"), 
      null, "true", configuration); 
}