West Side
West Side

Reputation: 182

Why Log4j2 doesn't write logs to a file?

This is my configuration log4j2.xml with path to file - src/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?

Upvotes: 1

Views: 578

Answers (2)

BabaNew
BabaNew

Reputation: 986

I had this error when using relative path on a linux server. I was starting my program using a sh script.

Unlike Windows, that sets the current directory based on where the launching script is placed, Linux sets the current directory as the user home directory (unless specified otherwise).

You can specify otherwise by using the cd command and move to the directory where the sh script is launched

So in my case, log file was created, but in the wrong location (i.e inside the home of the user). If you are having the same problem just prepend a cd command to your sh script.

Upvotes: 0

Sagar Gangwal
Sagar Gangwal

Reputation: 7980

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.

Upvotes: 2

Related Questions