配置log4j2以便从applet使用

时间:2013-07-11 15:24:20

标签: java logging applet log4j2

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

1 个答案:

答案 0 :(得分: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);
}