According to log4j documentation, if I define a logger config for package com.a.b.c with level ERROR with root logger level set to DEBUG, only ERROR logs should come from classes in com.a.b.c while other classes should print DEBUG logs. Therefore I have the below log4j2-test.xml.
However, in my case INFO level logs from classes in com.a.b.c are still being printed. Did I misunderstand anything? What should I do to make classes in com.a.b.c print ERROR logs while all other classes print INFO logs?
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug" name="PropertiesConfig" packages="org.apache.logging.log4j.test">
<Properties>
<Property name="basePath">target/</Property>
</Properties>
<ThresholdFilter level="trace"/>
<Appenders>
<Console name="consoleLogger" target="SYSTEM_OUT">
<PatternLayout pattern="%d{dd-MM-yyyy HH:mm:ss.SSS} %style{[%t]}{magenta} %highlight{%-5level}{TRACE=cyan, DEBUG=green, INFO=yellow, WARN=blue, ERROR=red} [%-60.60c] : %m%n" />
</Console>
<File name="fileLogger" fileName="${basePath}app.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %level [%t] [%c] [%M] [%l] : %msg%n" />
</File>
</Appenders>
<Loggers>
<Root level="INFO" >
<AppenderRef ref="consoleLogger" />
<AppenderRef ref="fileLogger" />
</Root>
<Logger name="com.a.b.c" level="ERROR" additivity="false">
<AppenderRef ref="consoleLogger" />
<AppenderRef ref="fileLogger" />
</Logger>
</Loggers>
</Configuration>
I figured this out. The class in question is (weirdly) not using its own class name when getting the logger. Typically it is LoggerFactory.getLogger(com.a.b.c) but in my case the class is doing LoggerFactory.getLogger(java.io.Console), thus our logger config <Logger name="com.a.b.c" level="ERROR" additivity="false"> will not apply to logs coming from this class. I had to add a logger config for the class java.io.Console.
Related
My logging code:-
public void run(ApplicationArguments applicationArguments) throws Exception {
logger.debug("Debugging log");
logger.info("Info log");
logger.warn("Hey, Thi s is a warning!");
logger.error("Oops! We have an Error. OK");
logger.fatal("Damn! Fatal error. Please fix me.");
}
My log4j2.xml file:-
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN" monitorInterval="30">
<Properties>
<Property name="LOG_PATTERN">
%d{dd-MM-yyyy HH:mm:ss.SSS} %5p [%t] - (%F:%L) - %m%n
</Property>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT" follow="true">
<PatternLayout pattern="${LOG_PATTERN}"/>
</Console>
<!-- Rolling File Appender -->
<RollingFile name="FileAppender" fileName="logs/currency_exchange.log"
filePattern="logs/currency_exchange-%d{dd-MM-yyyy}-%i.log">
<PatternLayout>
<Pattern>${LOG_PATTERN}</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" />
<SizeBasedTriggeringPolicy size="10MB" />
</Policies>
<DefaultRolloverStrategy max="10"/>
</RollingFile>
</Appenders>
<Loggers>
<AsyncLogger name="com.example.log4j2demo" level="info"
additivity="info">
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="FileAppender" />
</AsyncLogger>
<Root level="info">
<AppenderRef ref="ConsoleAppender" />
<AppenderRef ref="FileAppender" />
</Root>
</Loggers>
</Configuration>
As you can see the output in the console as:-
Also, the log entry is twice in the file. I want only one line of each log. The one with the link as this one:-
09-02-2020 10:36:02.280 INFO [main] -(Log4j2DemoApplication.java:21) - Info log
What is wrong? How to fix it?
You have given a wrong value in the additivity value of both loggers. Setting the additivity value to false will solve the messages duplication issue as it will prevent the logger from inheriting from its ancestor, in this case the root logger.
For the file name issue you mention in your comment: the filePattern property is used to generate the rolled log file name, that's the one on which you no longer write but keep for auditing/troubleshooting purposes, not the currently active one whose name is defined in the "fileName" tag instead.
I have a maven web project which requires logging.
I decided to use log4j2 for that purpose and added the required entries in the pom.xml file
Then I created the log4j2.xml file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<RollingFile name="RollingFile" fileName="${logs.path}/text.log"
filePattern="${logs.path}/%d{YYYYMMdd}-text.%i.log">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} [%t] %-5p %c{1}:%L - %msg%n" />
<Policies>
<SizeBasedTriggeringPolicy size="100 MB" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{YYYY-MM-dd HH:mm:ss} %-5p %c{1}:%L - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="root" level="info" additivity="false">
<appender-ref ref="RollingFile" level="info" />
<appender-ref ref="Console" level="info" />
</Logger>
<Root level="info" additivity="false">
<AppenderRef ref="RollingFile" />
<AppenderRef ref="Console" />
</Root>
</Loggers>
</Configuration>
I'm starting tomcat with -Dlogs.path="C:\mylogs", where C:\mylogs exists and has public read/write access.
The console logger is working fine, I can see the correct output in my console, the issue is that the file isn't being created, so I have no logfile, everything gets logged to catalina.out only, and the tomcat startup logs don't show errors for log4j.
What am I missing? is there some additional configuration I need to do in order to log to file?
I went through the documentation. You must refer to system properties with sys:, and it seems that tomcat properties are seen as system properties, so I replaced ${logs.path} with ${sys:logs.path} and it worked.
To create a log file with the log4j2 config you first need to define your appender. Here's an example:
<RollingFile name="MGMT"
fileName="${logdir}/mgmt.log"
filePattern="${logdir}/mgmt.%d{yyyy-MM-dd}.log">
<PatternLayout pattern="${layout}"/>
<CronTriggeringPolicy schedule="0 0 0 * * ?"/>
<DefaultRolloverStrategy>
<Delete basePath="${logdir}" maxDepth="1">
<IfFileName glob="mgmt.*.log" />
<IfAccumulatedFileCount exceeds="10" />
</Delete>
</DefaultRolloverStrategy>
</RollingFile>
Afterwards you just need to define a logger that will use it:
<Logger name="the package or name that is displayed in the log line"
level="ALL"
additivity="false">
<AppenderRef ref="MGMT"/>
</Logger>
If you have a log that has com.company.test as package set that package as name for the logger. It's important that they match.
The field additivity will define if you want to pass the catched log to its parent ( true ) or just let this logger handle it ( false )
EDIT:
your config file might need this:
<Configuration status="info">
<Properties>
<Property name="logdir">${sys:catalina.base}/logs</Property>
<Property name="layout">%d [%t] %-5p %c- %m%n</Property>
</Properties>
<Appenders>
If you don't want to use this you have to define the path static like <RollingFile name="MGMT"
fileName="C:\path\file.log"
I am using log4j2. But the problem that I am facing is that it logs all logs. I want to ... log from specific package to a specific file & other package to another file. I am using log4j2.xml for configuration.
Please can someone help?
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef level="DEBUG" ref="CONSOLE" />
<AppenderRef level="DEBUG" ref="fileAppender" />
</Root>
<Logger name="com.pkg.test.logging.method" level="DEBUG"
additivity="false">
<Appender-ref ref="fileAppender" level="DEBUG" />
</Logger>
</Loggers>
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n%throwable}" />
</Console>
<RollingFile name="fileAppender" fileName="./log.log"
filePattern="./log-%d{yyyy-MM-dd}.log">
<PatternLayout
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n}" />
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
</Appenders>
Just answered the question.
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Loggers>
<Root level="DEBUG" additivity="false">
<AppenderRef level="DEBUG" ref="CONSOLE" />
</Root>
<Logger name="com.pkg.test.logging.method" level="DEBUG"
additivity="false">
<Appender-ref ref="fileAppender" level="DEBUG" />
</Logger>
</Loggers>
<Appenders>
<Console name="CONSOLE" target="SYSTEM_OUT">
<PatternLayout
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n%throwable}" />
</Console>
<RollingFile name="fileAppender" fileName="./log.log"
filePattern="./log-%d{yyyy-MM-dd}.log">
<PatternLayout
pattern="%highlight{[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} %c{1}: %L - %msg%n}" />
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
</Policies>
</RollingFile>
</Appenders>
Removed the <AppenderRef level="DEBUG" ref="fileAppender" /> from root logger. Thus it started logging logs based on packages.
From Log4J Manual:
Adding a specific logger for a class: (you can refer to packages here too)
<Logger name="org.apache.logging.log4j.test2" level="debug" additivity="false">
<AppenderRef ref="File"/>
</Logger>
Adding a specific appender:
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout">
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</Layout>
</Appender>
The <Loggers> section of the config looks correct. But, if all other logs not belonging to the expected package is also getting logged, it is the Root logger which is responsible for these logs, and not the package level logger. It may not be active because of the way you are creating the logger instance in your code. E.g: If one is using slf4j to create the logger instance, then this is how we would need to create the logger instance:
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
Logger logger = LoggerFactory.getLogger(Test.class);
If one gets the logger instance using - Logger logger = LoggerFactory.getLogger("Test") then, the config will not work as expected.
Also, another answer mentioned that the solution was to remove the fileAppender that the package logger was using from the root logger. This, in fact, is not a problem. You are free to use the same appenders in root and package level logger. My answer in context of log4j-api 2.14.1
I am using log4j 2. I am trying to determine why my log file is not being written to, but my console is. This is the output I have to the console:
2016-04-25 12:26:07,142 INFO [main] helperCode.LogPlus (LogPlus.java:50) -
----------------------------------------------------------------------------
------------ The test is starting now at 2016-04-25-12-26-07-135 -----------
----------------------------------------------------------------------------
2016-04-25 12:26:07,151 INFO [main] helperCode.LogPlus (LogPlus.java:50) -
--------------------------------------------------------------------------
------------ METHOD loginBadPasswordGoodUsername_3 starting: ------------
--------------------------------------------------------------------------
The issues I've considered already:
The output is not repeating itself, so the log output being redirected is not an issue.
I am NOT using java.util.logging.Logger anywhere in my project;
The output of the log file is formatted in log4j style rather than JUL style, so I know that JUL is not overriding it;
Here is my XML config file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<File name="FileLogger" fileName="${sys:logFilePath}" append="false">
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n" />
</File>
<Async name="Async">
<AppenderRef ref="FileLogger" />
</Async>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="automationFramework" level="trace">
<AppenderRef ref="FileLogger" />
</Logger>
<Root level="trace">
<AppenderRef ref="STDOUT" />
</Root>
</Loggers>
</Configuration>
I am directing the output to the file located at the system variable "logFilePath".
I am not sure what is going on, and the config files shown on answers for similar questions are not in XML format, so I am not sure how to commute the config file code to XML.
In your case as mentioned in the comment you do not have the package called applicatiionFramework. So change the name attribute by the package name of the classes where you want to record log events.
<Logger name="your package" level="trace">
<AppenderRef ref="FileLogger" />
<Root level="trace">
<AppenderRef ref="STDOUT" />
</Root>
</Logger>
For more information visit log4j-manual-configuration
Glad the other answer helped. Do you need the named logger though? Why not just have the root logger? Also, you declared an Async Appender but are not using it. Is that on purpose? This is what I would suggest:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Appenders>
<File name="FileLogger" fileName="${sys:logFilePath}" append="false">
<PatternLayout pattern="%d %t %-5p %c{2} - %m%n" />
</File>
<Async name="Async">
<AppenderRef ref="FileLogger" />
</Async>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d %-5p [%t] %C{2} (%F:%L) - %m%n" />
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="STDOUT" level="info" />
<AppenderRef ref="Async" />
</Root>
</Loggers>
</Configuration>
Note that you can also specify a level on the AppenderRef. I made the Console Appender level INFO to illustrate this point.
If you want the log to show location information and use Async loggers or appenders then you need to specify includeLocation="true" on the Async Appender.
For the complete noob, like myself, this line in Unknown's answer above:
<Logger name="your package" level="trace">
is the key. When it says "your package" it really means the "package foo.bar" you declared at the top of the .java file where you created the Logger, not the class name you passed to create the Logger, like:
LOGGER = LogManager.getLogger(MyClass.class.getName());
It took me a ridiculous amount of time today to get my log4j2 output going to a file, playing with various "name" values until the light bulb went on.
following XML configuration is my log4j config, I see the log messages in console but the log file is empty, whats wrong in it ?
I am using log4j-api-2.1
<Properties>
<Property name="log-path">logs</Property>
</Properties>
<Appenders>
<RollingFile name="file-log" fileName="${log-path}/logtile.log/"
filePattern="${log-path}/logtile-%d{yyyy-MM-dd}.log">
<PatternLayout>
<pattern>%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n</pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1"
modulate="true" />
<SizeBasedTriggeringPolicy size="500" />
</Policies>
<DefaultRolloverStrategy max="20" />
</RollingFile>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="mylogger" level="info" additivity="false">
<appender-ref ref="file-log" level="info" />
<appender-ref ref="Console" level="info" />
</Logger>
<Root level="info">
<appender-ref ref="Console" />
</Root>
</Loggers>
How does your code obtain Logger instances? Assuming your code looks something like this:
Logger log = LogManager.getLogger(com.mycompany.MyClass.class);
log.info("Where is my message?");
Note that the fully qualified name of your logger is "com.mycompany.MyClass".
This logger will send messages to the root logger, and all named loggers whose name matches "com.mycompany.MyClass". The following configuration names would match this fully qualified class:
<Logger name="com.mycompany.MyClass" ...>
<Logger name="com.mycompany" ...>
<Logger name="com" ...>
However, the named logger in your configuration only matches "mylogger", so this logger will not receive the "Where is my message?" log event. The root logger will get the event and send it to its appender, the console.