我已经使用程序化配置配置了Log4j2。请在下面找到我的代码。我在jdk1.8上运行此代码。日志文件正确生成但日志文件名未按模式定义正确创建。文件将使用test_28_12_2016_24.log
之类的名称生成
看起来SimpleDateFormat没有得到认可。如果我遗漏任何东西,请告诉我。
public class Test {
public static void main(String args[]){
public final String LOG_FILE_PATTERN = "-%d{dd-MM-yyyy-HH}.%i.log";
public final String MY_LOG_PATTERN_LAYOUT = "%msg%n";
/* Configuring Logger context */
private LoggerContext context = (LoggerContext) LogManager.getContext(false);
final Configuration config = context.getConfiguration();
final Layout<? extends Serializable> layout = PatternLayout.createLayout(MY_LOG_PATTERN_LAYOUT, null, config, null,null,true, true, null, null);
/* Configuring policies */
final TimeBasedTriggeringPolicy timeBasedTriggeringPolicy = TimeBasedTriggeringPolicy.createPolicy(TimeUnit.DAYS.toMillis(1), "true");
final SizeBasedTriggeringPolicy sizeBasedTriggeringPolicy = SizeBasedTriggeringPolicy.createPolicy(1024*1024*10);
final CompositeTriggeringPolicy policy = CompositeTriggeringPolicy.createPolicy(timeBasedTriggeringPolicy,sizeBasedTriggeringPolicy);
final DefaultRolloverStrategy strategy = DefaultRolloverStrategy.createStrategy("50", "1", null,null, null, false, config);
/* Creating appenders */
final Appender appender = RollingFileAppender.createAppender("target/logs/test.log" , LOG_FILE_PATTERN, "true", "log-file-appender", null, null, "true", policy, strategy, layout, null, null, null, null, config);
appender.start();
AppenderRef ref = AppenderRef.createAppenderRef("File", null, null);
AppenderRef[] refs = new AppenderRef[] {ref};
/*Creating loggers*/
LoggerConfig loggerConfig = LoggerConfig.createLogger("true", Level.ERROR, "FILE_LOGGER", "com.*", refs, null, config, null);
loggerConfig.addAppender(appender,null,null);
config.addLogger("logger" , loggerConfig);
context.updateLoggers();
}
public void writelogs() {
Logger logger = context.getLogger("logger");
logger.error("test data");
}
}
答案 0 :(得分:0)
日志文件模式应包含同一目录中多个日志的文件名,但我认为问题在于文件模式中没有正确的目录。它可能正在创建或未能在另一个目录中创建文件。
文件模式应该是这样的。
"target/logs/test-%d{dd-MM-yyyy-HH}.%i.log"