I want to do two things:
Console logging seems to work just fine but the log file keeps beeing empty.
This is my log4j2.xml
<?xml version="1.0" encoding="UTF-8"?> <configuration status="WARN"> <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/app.log" immediateFlush="true"> <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </File> </appenders> <loggers> <logger name="filelogger" level="error"> <appender-ref ref="MyFile"/> </logger> <root level="info"> <appender-ref ref="Console"/> </root> </loggers> </configuration>
What might be wrong?
You can set a logger's level with the class Configurator from Log4j Core. BUT be aware that the Configurator class is not part of the public API. If you wish to change the root logger level, do something like this : LoggerContext ctx = (LoggerContext) LogManager.
Configuration: the root element of a log4j2 configuration file; the status attribute represents the level at which internal log4j events should be logged. Appenders: this element contains a list of appenders; in our example, an appender corresponding to the System console is defined.
I figured it out! The <Logger>
tag shouldn't be used in this case, see Gaurang Patel's answer for details.
<?xml version="1.0" encoding="UTF-8"?> <configuration status="WARN"> <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/app.log"> <PatternLayout pattern="%d{yyyy-mm-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </File> </appenders> <loggers> <root level="debug"> <appender-ref ref="Console" level="info"/> <appender-ref ref="MyFile" level="error"/> </root> </loggers> </configuration>
Although Daker had put the corrected configuration file but he didn't explain it. I would like to add explanation here. As quoted in Log4j2 Documentation here, usage of <Logger> tag was not required for the given requirement. Further when you should use <Logger> tag? Read below explanation form the documentation,
Perhaps it is desired to eliminate all the TRACE output from everything except com.foo.Bar. Simply changing the log level would not accomplish the task. Instead, the solution is to add a new logger definition to the configuration:
<Loggers> <Logger name="com.foo.Bar" level="TRACE"/> <Root level="ERROR"> <AppenderRef ref="STDOUT"> </Root> ... </Loggers>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With