0

在applet中使用log4j2.xml应该放在哪里?它可以同时记录到 Java 控制台和用户计算机上的文件吗?

4

1 回答 1

0

我把它放在applet 资源conf/log4j2.xml 中,然后从applet 中读取它。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);
}
于 2013-07-18T07:49:44.657 回答