Why Log4j2 doesn’t write logs to a file?

Tags: ,



This is my configuration log4j2.xml with path to filesrc/com/tarasiuk/task_01/log/dataLogger.log:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">

    <Properties>
        <Property name="FORMAT_MESSAGE">
            %d{YYYY-MM-dd HH:mm:ss} [%t] Level:%-7p Class:%c{1}:%-5L - %msg%n
        </Property>

        <Property name="LOG_FILE">
            src/com/tarasiuk/task_01/log/dataLogger.log
        </Property>
    </Properties>

    <Appenders>
        <Console name="Console" target="SYSTEM_OUT">
            <PatternLayout pattern="${FORMAT_MESSAGE}" />
        </Console>

        <File name="File" fileName="${LOG_FILE}" append="false">
            <PatternLayout pattern="${FORMAT_MESSAGE}" />
        </File>
    </Appenders>

    <Loggers>
        <Logger name="org.apache.logging.log4j.test2" level="debug" additivity="false">
            <AppenderRef ref="File" />
        </Logger>

        <Root level="info">
            <AppenderRef ref="Console" />
        </Root>
    </Loggers>
</Configuration>

Structure of my project:
enter image description here

What I do:

  1. change path to log file from src/com/tarasiuk/task_01/log/dataLogger.log to com/tarasiuk/task_01/log/dataLogger.log – no result.
  2. change level in <Logger> from debug to info – no result.

Logs are output to the console – that ok. But why Log4j2 doesn’t write logs to a file?

Answer

Try with below appender.

May be in your case it is not able to get path from property, so i had provided only name. So automatically it will create file on same path as your application is.

<Appenders>
    <File name="dataLogger" fileName="dataLogger.log" append="false">
       <PatternLayout pattern="%level - %m%n"/>
    </File>
    <Console name="STDOUT" target="SYSTEM_OUT">
      <PatternLayout pattern="%level - %m%n"/>
    </Console>
  </Appenders>

This will help you.



Source: stackoverflow