Android:使用log4j2创建日志时获取额外的空文件

时间:2016-04-06 06:38:19

标签: java android logging configuration log4j2

当我尝试从log4j2获取日志时,我得到一个额外的空文件。文件名是“$(sys”,它包含绝对没有,但每次我运行我的程序时都会创建它是我记录的java文件:

public static void main(String[] args){

    Logger logger = LogManager.getLogger();

    final Calendar cal = Calendar.getInstance();
    cal.setTimeInMillis(System.currentTimeMillis());
    Date date = cal.getTime();
    int mHour = date.getHours();
    int mMinute = date.getMinutes();

    String filenameWE = String.valueOf(mHour) + "_" + String.valueOf(mMinute)+"_WarErr";
    String filenameFull = String.valueOf(mHour) + "_" + String.valueOf(mMinute)+"_Full_Log";

    System.setProperty("WarErrFilename", filenameWE);
    System.setProperty("FullLogFilename", filenameFull);

    LoggerContext ctx =  (LoggerContext) LogManager.getContext(false);
    ctx.reconfigure();

    logger.debug("Hello world - debug log");
    logger.debug("Hello world - debug log");
    logger.debug("Hello world - debug log");
    logger.info("Hello world - info log");
    logger.info("Hello world - info log");
    logger.info("Hello world - info log");

    logger.warn("Hello world - warn log");        
    logger.warn("I farted!");
    logger.error("Hello world - error log");
    logger.error("Error please insert brain!");
    logger.error("Error cant poop!");
}

我的log4j2.xml

<?xml version="1.0" encoding="UTF-8"?><Configuration status="INFO">
<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
        <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" />
    </Console>

    <File name="MyFile" fileName="logs/${date:yyyy}/${date:MM}/${date:dd}/${sys:WarErrFilename}.log" immediateFlush="false" append="false">
        <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
        <Filters>
            <ThresholdFilter level="error" onMatch="ACCEPT" onMismatch="NEUTRAL" />
            <ThresholdFilter level="warn" onMatch="ACCEPT" onMismatch="NEUTRAL" />
            <ThresholdFilter level="info" onMatch="DENY" onMismatch="DENY" />
        </Filters>
    </File>
    <File name="Technical"
          fileName="logs/${date:yyyy}/${date:MM}/${date:dd}/${sys:FullLogFilename}.log">
        <PatternLayout pattern="%d %p %c{1.} [%t] %m%n" />
    </File>
</Appenders>

<Loggers>
    <Root level="debug">
        <AppenderRef ref="Console" />
        <AppenderRef ref="MyFile"/>
        <AppenderRef ref="Technical"/>
    </Root>
</Loggers>  
</Configuration>

1 个答案:

答案 0 :(得分:2)

您的配置缺少必须嵌套<Configuration><Appenders>的外部<Loggers>元素。请查看手册以获取示例。

另外,为什么不在从LogManager获取Logger之前设置系统属性?