I have a java application with log4j2 configured in order to log to console and to file.
When i start my application from ecplise, all the log are ok (console and file).
When i start the jar of the application from CMD or Powershell (as admin), only the console log works.
If i start the jar by only double click, the file log works (but no console is displayed).
This my log4j2.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
<Appenders>
<File name="file_all" fileName="logs/ALL.log">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</File>
<File name="file_error" fileName="logs/ERROR.log">
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</File>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="trace">
<AppenderRef ref="file_all" level="INFO"/>
<AppenderRef ref="file_error" level="ERROR"/>
<AppenderRef ref="STDOUT" level="INFO"/>
</Root>
</Loggers>
</Configuration>
Your log4j2.xml config file starts with <configuration status="off" ... (or perhaps WARN or ERROR, you haven't shown the full config).
To investigate, switch on log4j's internal status logging by changing this to <configuration status="trace" ...
This will show output on the console. (You can redirect this to a file with java -jar myjar.jar > out.log.)
I hope this will give us more info on what is going on. Please paste that output into your question.
EDIT: the status output looks good; no errors or anything. Could it be that double-clicking a jar file is associated with javaw (not java), so there is no console? You mention that when starting the application from a CMD prompt or Powershell, you cannot find the log file. The line "Starting FileManager logs/ALL.log" in the status log tells me that log4j2 successfully created an output stream. However, this is a relative path, and the status log does not mention the absolute path. I think it is relative to the current directory, so what is the current directory of the CMD prompt or Powershell?
Related
I try to use Windows 10 command line to print colored messages on console, but with no success. According to the Log4j 2 documentation, I should add the Jansi jar to my print application and set property log4j.skipJansi to false for enabling ANSI support on Windows. Could you, please, check and say what I did wrong:
Following code is my current work:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class LoggerTest {
private static final Logger logger = LogManager.getLogger();
public static void main(String[] args) throws Exception {
logger.info("Hello!");
}
}
Following code is Log4j 2 configuration file:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration>
<Properties>
<Property name="log4j.skipJansi" value="false"/>
</Properties>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout>
<disableAnsi>false</disableAnsi>
<Pattern>%style{%d [%t] %c %p: %m}{yellow}%n%ex</Pattern>
</PatternLayout>
</Console>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="ConsoleAppender"/>
</Root>
</Loggers>
</Configuration>
The contents of \lib directory:
log4j-core-2.12.1.jar
log4j-api-2.12.1.jar
jansi-1.18.jar
And the Windows compileAndRun.bat file:
#echo off
javac -cp lib\*;. LoggerTest.java
java -cp lib\*;. LoggerTest
pause
exit
However, the output in the command line is still not coloured. This is what I see:
So, the message contains ANSI escape codes, but they are not interpreted by command line. Though, if I try to copy/paste this output and echo it directly using another bat-file, then I see the coloured message.
It worked for when I add disableAnsi="false" propriety to <PatternLayout>
<Appenders>
<Console name="ConsoleAppender" target="SYSTEM_OUT">
<PatternLayout
pattern="%highlight{%p} %logger{-2} - %m{FATAL=red blink,ERROR=red, WARN=yellow bold, INFO=green, DEBUG=green bold}%n" disableAnsi="false"/>
</Console>
</Appenders>
This is answer how to enable colors with latest log4j on windows 7:
openjdk 14
log4j 2.14.1
jansi 1.18
Configuration:
<?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] %highlight{%-5level}{FATAL=red blink, ERROR=red bold, WARN=yellow bold, INFO=magenta, DEBUG=green, TRACE=blue} %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console"/>
</Root>
</Loggers>
</Configuration>
The key point is to pass -DLOG4J_SKIP_JANSI=false to JVM. Solution was found in this user guide.
Try executing this command: "reg add HKCU\Console /v VirtualTerminalLevel /t REG_DWORD /d 1"
In Java:
Runtime.getRuntime().exec("reg add HKCU\\Console /v VirtualTerminalLevel /t REG_DWORD /d 1");
I had to include both Jansi and Jcabi for cross-OS rendering -
<dependency>
<groupId>org.fusesource.jansi</groupId>
<artifactId>jansi</artifactId>
<version>1.18</version>
<optional>true</optional>
</dependency>
<dependency>
<groupId>com.jcabi</groupId>
<artifactId>jcabi-log</artifactId>
<version>LATEST</version>
<optional>true</optional>
</dependency>
We have WAR deployments running on Tomcat containers which are using log4j 2.5 for logging events. We have now amended the deployments' log4j2.xml configuration to have the log files roll over every 24 hours but, with this new configuration, the rollover of files are not taking place as we would expect.
Sample configuration:
<RollingFile name="file"
fileName="${sys:catalina.base}/logs/${web:contextPath}.log"
filePattern="${sys:catalina.base}/logs/${web:contextPath}-%d{dd-MMM-yyyy}.log"
append="true">
<PatternLayout pattern="%d{dd-MMM-yyyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" >
<header>LOG START DATE=${date:dd-MMM-yyyy HH:mm:ss.SSS} APP=${web:contextPath} TOMCAT=${env:HOSTNAME}:${env:CONNECTOR_PORT}${sys:line.separator}</header>
<footer>LOG END DATE=${date:dd-MMM-yyyy HH:mm:ss.SSS} APP=${web:contextPath} TOMCAT=${env:HOSTNAME}:${env:CONNECTOR_PORT}${sys:line.separator}</footer>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
Any ideas why the rollover is not taking place?
NOTE: The same configuration but with a <CronTriggeringPolicy schedule="0 0 0 * * ?" /> instead of TimeBasedTriggeringPolicy does rollover but, in this case, the rolled over files get created with today's date in the filename and NOT yesterday's date.
NOTE2: We have other deployments with similar configuration that do rollover every 24 hours but those configurations have the filename hardcoded instead of using ${web:contextPath}. Could this lookup have something to do with why RollingFile might not work?
--- EDIT ---
UPDATE: We are able to get TimeBasedTriggeringPolicy to rollover files using above configuration when the Tomcat instance is running on Windows but NOT when the Tomcat instance is running on Linux.
There is nothing wrong with your configuration snippet as I get the desired behaviour of time based rolling.
To test, I changed the dd-MMM-yyyy to dd-MMM-yyyy-HH-mm and my log file rolls every minute.
It must be something else that is preventing you from achieving the desired behaviour.
My setup #1:
Log4j2 v2.8.2
Apache Tomcat 8.5.13
Windows 7 Enterprise SP1
My setup #2:
Log4j2 v2.5
Apache Tomcat 7.0.77
CentOS 7 (1611)
I have the following 3 JARs in WEB-INF/lib:
log4j-api-2.5.jar
log4j-core-2.5.jar
log4j-web-2.5.jar
Here is my complete log4j2.xml for your reference:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
<RollingFile name="RollingFileAppender"
fileName="${sys:catalina.base}/logs/${web:contextPath}.log"
filePattern="${sys:catalina.base}/logs/${web:contextPath}-%d{dd-MMM-yyyy-HH-mm}.log"
append="true">
<PatternLayout pattern="%d{dd-MMM-yyyy HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" >
<header>LOG START DATE=${date:dd-MMM-yyyy HH:mm:ss.SSS} APP=${web:contextPath} TOMCAT=${env:HOSTNAME}:${env:CONNECTOR_PORT}${sys:line.separator}</header>
<footer>LOG END DATE=${date:dd-MMM-yyyy HH:mm:ss.SSS} APP=${web:contextPath} TOMCAT=${env:HOSTNAME}:${env:CONNECTOR_PORT}${sys:line.separator}</footer>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="root" level="debug" additivity="false">
<appender-ref ref="RollingFileAppender" level="debug"/>
</Logger>
<Root level="debug" additivity="false">
<AppenderRef ref="RollingFileAppender"/>
</Root>
</Loggers>
</Configuration>
I have a JAX-RS 2.0 application running on a Tomcat 7 server, and I'm using log4j2 along with SLF4J to record the server logs to a file.
I can't seem to get any logs to show up properly in my log file when running the server in production, although when I run my integration tests, logs are output correctly.
In production, the logs are merely redirected to the console instead.
My log4j2.xml file is located in the WEB-INF/classes folder, and I've included all the necessary dependencies as well.
My configuration file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="trace">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<RollingFile name="file" fileName="log/trace.log" append="true" filePattern="log/trace.%i.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %X %logger{36} - %msg%n"/>
<Policies>
<OnStartupTriggeringPolicy/>
<SizeBasedTriggeringPolicy size="10 MB" />
</Policies>
</RollingFile>
</Appenders>
<Loggers>
<Logger name="my.package" level="TRACE" additivity="false">
<AppenderRef ref="file"/>
</Logger>
<Root level="WARN">
<AppenderRef ref="file"/>
</Root>
</Loggers>
</Configuration>
The web.xml needs no configuration (I'm following the documentation found on the log4j2 website).
EDIT
I've tried setting the Root level to TRACE but everything still gets redirected to console. The file log/trace.log itself is created, it's just never written to. I also tried setting immediateFlush=true but that didn't have any impact either.
I noticed you have status logging (log4j internal logging) set to TRACE. This will dump log4j internal initialization messages to the console. It this what you mean?
Otherwise, the config you provide shows there is no logger that has an appender-ref pointing to the ConsoleAppender.
So, if you are also seeing your application logs being output to the console (in addition to log4j's status log messages), I suspect there is another log4j2.xml (or log4j2-test.xml) config file in the classpath somewhere.
Fortunately log4j's status logs should also show the location of the log4j config file, so you can confirm which config file is actually being loaded.
You can switch off status logging by setting <Configuration status="WARN"> after confirming all works correctly.
I figured it out!
Turns out I was using the gretty plug-in with gradle, which contains it's own logging package (the logback library).
It used it's own internal logback.xml which was redirecting to console. I fixed this by overwriting the internal logback.xml with my own (using logback's configuration) and now everything works as expected!
I am trying to to use Chainsaw to view my application's logger events but there is nothing showing up under the 'Zeroconf' tab in chansaw.
I've followed Scott's guide in log4j2 to chainsaw hello world not working… what am I doing wrong? - but no luck. I was going to comment on that question asking how teryet got it working in the end, but as my reputation is below 50, the site didn't allow me.
Environment
OS: OSX Mavericks
IDE: Netbeans 8.0 (Build 201403101706)
Java: 1.7.0_45; Java HotSpot(TM) 64-Bit Server VM 24.45-b08
log4j: 2.0rc1
Chainsaw: downloaded the latest DMG from http://people.apache.org/~sdeboy/
Things I've made sure
- included jmdns.jar in the classpath of my application
- Used PatternLayout in my config log4j.xml
- Ensure advertiser URL has three slashes
My log4j.xml config file
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="OFF" advertiser="multicastdns">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%date{ABSOLUTE} [%thread] %logger{3}.%style{%method}{Blue}%style{(line%line)}{Red}%X %highlight{%-5level} - %msg%n%xEx"/>
</Console>
<RollingFile name="RollingFile" fileName="../logs/POS.log" filePattern="../logs/$${date:yyyy-MM}/POS-%d{yyyyMMdd-HHmmss}.log">
<PatternLayout pattern="%date{ABSOLUTE} [%thread] %logger{3}.%style{%method}{Blue}%style{(line%line)}{Red}%X %highlight{%-5level} - %msg%n%xEx"/>
<Policies>
<OnStartupTriggeringPolicy/>
<TimeBasedTriggeringPolicy/>
</Policies>
</RollingFile>
<File name="testFile" fileName="../logs/POS2.log" bufferedIO="false" advertiseURI="file:///localhost/Users/arthurhsieh/Documents/NetBeansProjects/AES/logs/POS2.log" advertise="true">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %m%n"/>
</File>
</appenders>
<loggers>
<root level="all"> <!-- <root level="trace"> -->
<appender-ref ref="Console"/>
<appender-ref ref="RollingFile"/>
<appender-ref ref="testFile" />
</root>
</loggers>
</configuration>
I can see logger events in the POS2.log file though.
Thanks in advance for any help/guidances. Cheers.
My issue went away after I restarted my system, i.e., Chainsaw is working and i can view my logs by connecting through the Zeroconf tab.
My guess is this is an Apple OS issue rather than Chainsaw itself.
I'm using log4j 2.0-beta9. I have a question about the SMTP appender. I need to configure the subject, from and to values from properties. I'm logging a MapMessage and my config is as below -
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="DEBUG">
<appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d [%t] %-5p %c - %m%n"/>
</Console>
<SMTP name="Mail" subject="Error Log for ${env:HOSTNAME}" to="${sys:mail.to}" from="${sys:mail.from}"
smtpHost="${sys:mail.host}" smtpPort="${sys:mail.port}" smtpDebug="true" bufferSize="1">
<PatternLayout>
<pattern>%d [%t] %-5p %c - %m%n</pattern>
</PatternLayout>
</SMTP>
<Async name="AsyncMail">
<appender-ref ref="Mail" />
</Async>
</appenders>
<loggers>
<root level="info">
<appender-ref ref="Console"/>
<appender-ref ref="AsyncMail">
<MapFilter onMatch="ACCEPT" onMismatch="DENY">
<KeyValuePair key="throwable.class" value="java.lang.RuntimeException" />
</MapFilter>
</appender-ref>
</root>
</loggers>
</configuration>
// Java Code to log the msg
Throwable throwable; // this is the exception that is thrown by the app.
MapMessage message = new MapMessage();
message.put("throwable.message", throwable.getMessage());
message.put("throwable.class", throwable.getClass().getName());
message.put("throwable.stacktrace", ExceptionUtils.getStackTrace(throwable)); // ExceptionUtils from apache-commons
LOGGER.error(message, throwable); // org.apache.logging.log4j.Logger
The problem is that none of these values are replaced dynamically. Is there any way to do this?
Thanks in advance.
You need to set the mail.to and mail.from System properties. The problem you're having might be that you're running in a Servlet 3.0 environment, in which case the Log4j2.xml file is being processed before your code that sets the properties is executed.
If that is the case, you can create a servlet container initializer that you configure in your web.xml file to load before Log4j2's servlet container initializer is loaded.