I'm using Tomcat 8.0.3 and log4j 2.0-rc1 to deploy a GWT application (servlet 2.5).
I believe I fixed the usual log configuration errors, but still nothing is logged to the console or file.
Head of my web.xml:
<listener>
<listener-class>org.apache.logging.log4j.core.web.Log4jServletContextListener</listener-class>
</listener>
<filter>
<filter-name>log4jServletFilter</filter-name>
<filter-class>org.apache.logging.log4j.core.web.Log4jServletFilter</filter-class>
</filter>
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///C:/Users/name/Desktop/log4j2.xml</param-value>
</context-param>
<filter-mapping>
<filter-name>log4jServletFilter</filter-name>
<url-pattern>/*</url-pattern>
<dispatcher>REQUEST</dispatcher>
<dispatcher>FORWARD</dispatcher>
<dispatcher>INCLUDE</dispatcher>
<dispatcher>ERROR</dispatcher>
</filter-mapping>
This is the log4j2.xml configuration:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="TRACE">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="[%p] %c{1}: %m%n"/>
</Console>
<File name="infoFile" fileName="${sys:catalina.home}/logs/info.log" >
<PatternLayout pattern="[%p] %c{1}: %m%n"/>
</File>
</Appenders>
<Loggers>
<Root level="info">
<Appender-Ref ref="Console"/>
<Appender-Ref ref="infoFile"/>
</Root>
</Loggers>
</Configuration>
I added both the log4j2 api and core to my Maven dependencies and I can see them exploded in WEB-INF\classes\. I've also removed them from the skipJar list in catalina.properties.
When the war is deployed, no errors or warnings are thrown in the localhost or catalina log. This is the localhost log:
INFO ContextListener: contextInitialized()
INFO SessionListener: contextInitialized()
INFO Log4jServletContextListener ensuring that Log4j starts up properly.
INFO Log4jServletFilter initialized.
The strange thing is that the info.log file is created, but never written to.
I'm also using Hibernate whose logs do show up in the console, could this be the problem?
Finally, this is how I'm using the logger:
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
private static final Logger LOG = LogManager.getLogger(MyClass.class.getName());
public void myMethod() {
LOG.info("Logging some message");
}
(The log4j2 config file is temporarily on my desktop because it seems that I can't use spaces in the path)
As far as I can see your configuration is correct and all is set up as described in the log4j2 manual page for web apps.
One thing you could try is putting the log4j2.xml config file in the classpath (under WEB-INF/classes) and removing the log4jConfiguration context-param setting. But since you are seeing an info.log file being created, it is likely that the log4j2.xml file is already discovered correctly, so putting it in the classpath may not help. (Worth a try though.)
Two other reasons I can think of why nothing appears in the log file: log output is buffered and the buffer is not flushed on every event. However, the default for FileAppender is immediateFlush=true, so that would mean a new bug was introduced in rc1. This is possible, but not likely (current trunk source looks correct).
Finally, would it be possible that your method that does the logging (myMethod in your example above) is not called? Is there a way to verify that this method was called?
In my case, I has configured log4j2.xml file correctly, but while actually logging, I mistakenly used the #Slf4j annotation in Lombok. Changing it to #Log4j2 resolved the issue.
Related
I've been banging my head over this one for a few days and can't get it figured out. Log4j2 is backwards compatible if you add the log4j1 compatibility library.
My web-inf\lib has:
slf-api
log4j-1.2-api (backwards compat. library)
log4j-api (log4j2)
log4j-core (log4j2)
log4j-web (auto-wiring for web applications)
My web.xml has:
<!-- log4j2 auto-wiring -->
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///${catalina.base}/conf/log4j2.xml</param-value>
</context-param>
My [tomcat]/conf/log4j2.xml is:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="debug">
<Appenders>
<!-- Appends to CONSOLE -->
<Console name="consoleAppender" target="SYSTEM_OUT">
<ThresholdFilter level="DEBUG" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="%5p (%F:%L) - %m%n" />
</Console>
</Appenders>
<Loggers>
<Logger name="com.mycompany.componentA" level="WARN" />
<Logger name="com.mycompany.componentA.QueryLogger" level="DEBUG" />
<Logger name="com.mycompany.mycode" level="DEBUG" />
<Root level="WARN">
<AppenderRef ref="consoleAppender" />
</Root>
</Loggers>
</Configuration>
I have upgraded code under my control (com.mycompany.mycode) to log4j2 APIs and they work/log flawlessly. Code that is not under my control but was written against log4j1 (com.mycompany.componentA) just simply fails to log at all. No errors, no debugs, nothing.
Something interesting though... when I start the application I get a log4j1 warning about incorrect configurations when the application starts. This also stumps me because there are no log4j1 libraries (except the compatibility API) in the WAR. Warning is:
log4j:WARN No appenders could be found for logger (com.mycompany.componentB)
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
EDIT: I (finally) figured out what's going on. One of my dependencies did a horribly bad thing and BUNDLED the log4j1 classes into it's final jar. So there are no log4j1 jars on the classpath, but there are log4j1 CLASSES on the classpath.
The only way I was able to get this working was to:
Create BOTH a log4j1 and log4j2 XML configuration files (even though the log4j2 configuration contained all the loggers I wanted)
Let Log4j2 auto-wire itself via the 'log4j-web' artifact + 'log4jConfiguration' web.xml parameter
Manually wire log4j1 by calling the deprecated Log4jConfigurer.initLogging(...) API on server startup
This is probably horribly incorrect, but as indicated above, it was the only way I got it working after weeks of fooling around.
My understanding of the lo4j1 bridge is that wiring up log4j2 and including the bridge is all that should be required (e.g. no need to manually wire log4j1). In practice, that does not seem to be occurring.
That error message means you still have the log4j-1.x jar in your application. Look for it in your WEB-INF/lib and remove it and then it should work.
If not in WEB-INF/lib, then perhaps in your web container (Tomcat?) shared lib folder? Ralph is right that this error message is generated by Log4j-1.2, so it is on the classpath somewhere... Try printing the value of System property java.class.path if necessary.
Update: another way to find the location of the Log4j1 jar is by printing the value of org.apache.log4j.AppenderSkeleton.class.getResource("/org/apache/log4j/AppenderSkeleton.class") from your application.
(I originally suggested Category but this also exists in the Log4j 1 bridge, so AppenderSkeleton is better.)
I tried to set up LOG4J according documentation (and related SO questions), but it does not create supposed file, but there is such log in WildFly:
No Log4j context configuration provided. This is very unusual
web.xml
<web-app xmlns="http://java.sun.com/xml/ns/javaee"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd"
version="3.0">
<context-param>
<param-name>log4jConfigLocation</param-name>
<param-value>/WEB-INF/classes/log4j2.xml</param-value>
</context-param>
app.war/WEB-INF/classes/log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<Configuration monitorInterval="30">
<!-- http://logging.apache.org/log4j/2.x/manual/configuration.html -->
<Properties>
<Property name="filename">c:/oauth.log</Property>
</Properties>
<Filter type="ThresholdFilter" level="trace"/>
<Appenders>
<Appender type="File" name="File" fileName="${filename}">
<Layout type="PatternLayout">
<Pattern>%d %p %C{1.} [%t] %m%n</Pattern>
</Layout>
</Appender>
<File name="MyFile" fileName="c:/oauth2.log" immediateFlush="true">
<PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</File>
</Appenders>
<Loggers>
<Logger name="cz.literak.demo" level="debug" additivity="true">
<AppenderRef ref="File"/>
</Logger>
<Root level="error">
<AppenderRef ref="MyFile"/>
</Root>
</Loggers>
</Configuration>
app.war/WEB-INF/lib
commons-logging-1.1.3.jar
json-smart-1.1.1.jar
log4j-api-2.0-rc1.jar
log4j-core-2.0-rc1.jar
log4j-jcl-2.0-rc1.jar
Could you tell me what is wrong? I tried to comment out context param in web.xml and rely on autoconfiguration but there is no change.
EDIT
when I added following code
<context-param>
<param-name>log4jContextName</param-name>
<param-value>oauthDemo</param-value>
</context-param>
it failed differently (I do not have time to investigate now)
07:41:29,269 INFO [io.undertow.servlet] (MSC service thread 1-12) Log4jServletContainerInitializer starting up Log4j in Servlet 3.0+ environment.
07:41:29,644 INFO [stdout] (MSC service thread 1-12) 2014-02-20 07:41:29,643 ERROR FileManager (c:/oauth2.log) java.io.FileNotFoundException: c:\oauth2.log (PĹ™Ăstup byl odepĹ™en)
07:41:29,646 INFO [stdout] (MSC service thread 1-12) 2014-02-20 07:41:29,645 ERROR Unable to invoke method createAppender in class org.apache.logging.log4j.core.appender.FileAppender for element File 07:41:29,647 INFO [stdout] (MSC service thread 1-12) at org.apache.logging.log4j.core.config.BaseConfiguration.createPluginObject(BaseConfiguration.java:913)
As a reference this page describes how to configure Log4j2:
https://logging.apache.org/log4j/2.x/manual/webapp.html#ContextParams
In my case I have not configured any context-param in web.xml. The only thing I had to do was to set the display name:
<display-name>My Admin API</display-name>
I am also using log4j2.yaml instead of xml files and the file is not inside the war. Also notice that in this page https://logging.apache.org/log4j/2.x/manual/webapp.html they say there is a problem with versions of Tomcat < 7.0.43. So either you have to use a newer version of do a specific configuration.
Log4J will look for the log4j2.xml config file in the classpath, unless a location is specified.
Have you tried not specifying the location of the log4j2.xml file (that is, remove the context-param stuff from web.xml), and simply relying on putting the config in the classpath? (app.war/WEB-INF/classes/log4j2.xml looks fine to me)
Note that the file must be named log4j2.xml and not log4j.xml.
I have spent a couple hours now trying to figure this out and am at a complete loss. I find the new configuration process unnecessarily complex.
I have a Servlet with a web.xml file with the following:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>file:///etc/myApp/log4j2.xml</param-value>
</context-param>
It doesn't seem to have any effect. I am using Tomcat 7.0.42, and I have removed all references to log4j*.jar in the catalina.properties file. The logs in my app are still being sent, but they are just being sent to System.out with none of the formatting I specified.
So, I tried to just do it by hand on my own:
InputStream in =
new FileInputStream(new File("/etc/myApp/log4j2.xml"));
ConfigurationSource source = new ConfigurationSource(in);
ConfigurationFactory factory = new XMLConfigurationFactory();
Configuration configuration = factory.getConfiguration(source);
LoggerContext context = (LoggerContext) LogManager.getContext();
context.start(configuration);
context.updateLoggers();
Logger.getLogger("Test").log(Level.INFO, "This is a logging message.");
First, this seems entirely convoluted. Clearly there exists some code that will search for different files and assume file types based on their extensions via the "log4jConfiguration" property, so why isn't there a LogManger.reconfigure(String) that has the same effect?
Second, this has no effect either. Again, the log is printed to System.out, and none of the requested formatting is being done.
Here is the contents of my log4j2.xml:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="DEBUG">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<File name="LogFile" fileName="/var/log/myApp/myApp.log">
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss.SSS} %p %c{1.} [%t] %m%n"/>
</File>
</Appenders>
<Loggers>
<Root level="DEBUG">
<AppenderRef ref="Console" level="DEBUG"/>
<AppenderRef ref="LogFile" level="DEBUG"/>
</Root>
</Loggers>
</Configuration>
The output in both cases comes out something like:
Dec 03, 2013 6:06:45 PM test.Test main
INFO: This is a logging message.
Thanks in advance,
John
EDIT: This is actually working. It appears that I was missing, "log4j-jcl-2.0-beta9.jar". Remko Popma's answer works as well, if the "context-param" above is not working.
There are many possible scenarios with webapp logging, which makes configuration more complex than the ideal. Putting the log4j2 jars and the config file in your webapp's classpath should work. Did you see the manual page for log4j2 use in web apps? If the issue remains, please file a log4j2 jira ticket.
The LoggerContextalready has a method setConfigLocation that takes in a URI as parameter. It baffles me why there isn't a similar method that takes an InputStream as parameter. Instead we have to deal with the most convoluted and messy way of loading our log4j2.xml that is not on the classpath.
I use log4j2 in my project something like this:
logger.log(Level.ERROR, this.logData);
My configuration file looks like this:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="ERROR" DLog4jContextSelector="org.apache.logging.log4j.core.async.AsyncLoggerContextSelector">
<Appenders>
<!-- Async Loggers will auto-flush in batches, so switch off immediateFlush. -->
<RandomAccessFile name="RandomAccessFile" fileName="C:\\logs\\log1.log" immediateFlush="false" append="false">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m %ex%n</Pattern>
</PatternLayout>
</RandomAccessFile>
</Appenders>
<Loggers>
<Root level="error" includeLocation="false">
<AppenderRef ref="RandomAccessFile"/>
</Root>
</Loggers>
It creates my file, I log something to it, but it's still empty. When I trying to delete this file, OS told me that it in use (if app currently working), but even if I stop application, file still empty.
So which settings should I change to make it work correctly?
I suspect that asynchronous logging is not switched on correctly.
As of beta-9 it is not possible to switch on Async Loggers in the XML configuration, you must set the system property Log4jContextSelector to "org.apache.logging.log4j.core.async.AsyncLoggerContextSelector".
The reason you are not seeing anything in the log is that your log messages are still in the buffer and have not been flushed to disk yet. If you switch on Async Loggers the log messages will be flushed to disk automatically.
I share a cleaner and easier solution.
https://stackoverflow.com/a/33467370/3397345
Add a file named log4j2.component.properties to your classpath. This can be done in most maven or gradle projects by saving it in src/main/resources.
Set the value for the context selector by adding the following line to the file.
Log4jContextSelector=org.apache.logging.log4j.core.async.AsyncLoggerContextSelector
Log4j will attempt to read the system property first. If the system property is null, then it will fall back to the values stored in this file by default.
I am trying to configure log4j 2.0 to report logs.
My config is saved as log4j2.xml and this is its content:
<?xml version="1.0" encoding="UTF-8"?>
<configuration name="PRODUCTION" status="OFF">
<appenders>
<RollingFile name="MyFileAppender"
fileName="../Logs/app.log"
filePattern="../Logs/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
<PatternLayout>
<pattern>%d %p %C{1.} [%t] %m%n</pattern>
</PatternLayout>
<Policies>
<OnStartupTriggeringPolicy />
<TimeBasedTriggeringPolicy interval="6" modulate="true"/>
<SizeBasedTriggeringPolicy size="250 MB"/>
</Policies>
</RollingFile>
</appenders>
<loggers>
<root level="trace">
<appender-ref ref="MyFileAppender"/>
</root>
</loggers>
</configuration>
It exists in the classpath of the project and I tried putting it in many other directories..
I created a logger in the code like so:
Logger logger = LogManager.getLogger(MyClass.class.getName());
logger.info("test");
And nothing is written and no file is created.
When I debug the code I see that the logger is the default logger(console).
place log4j2.xml file under src/main/resources. It works
Actually This is a straight forward process. Two main classes of Log4j 2 are as follows that you need to import like this:
import org.apache.logging.log4j.LogManager
import org.apache.logging.log4j.Logger
Now get a Logger instance by using this code.
private static final Logger logger = LogManager.getLogger();
Note I didn't specified the class name to getLogger() method as a parameter. Log4j 2 automatically figures it out.
Now you can use any of the info(), trace(), debug(), warn(), error(), fatal() method from the Logger class. But to get the output from all of these methods you'll need a XML configuration file. By default Log4j 2 only produces output from the error() and fatal() methods.
Configuration file is as follows:
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<File name="MyCustomLogFile" fileName="/home/me/mylogfile.log">
<PatternLayout>
<Pattern>%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
</File>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
</Appenders>
<Loggers>
<Root level="all">
<AppenderRef ref="MyCustomLogFile"/>
<!--<AppenderRef ref="Console"/>-->
</Root>
</Loggers>
</Configuration>
Save this file with any name any where. I use Log4j2.xml as name. Now you'll need this file to be put in classpath, which you can do by passing a system property when running the program as follows:
java -Dlog4j.configurationFile=/path/to/xml/configuration/file/Log4j2.xml MyMainClass
And you've done it. Logging will be right away on your console.
Special Notes:
In XML file I've provided 2 appenders: A file and a console. You can see that you just need to uncomment the commented AppenderRef tag to get output in a file instead of console.
You can also provide an environment variable as a system property. Log4j 2 will read the configuration file from the environment variable first and then in -D argument if not found an environment variable.
Have fun with logging. :-)
you should put your log4j2.xml into the classpath.
or set "log4j.configurationFile" system property to force to use your log4j2.xml
Please refer to: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
It exists in the classpath of the project and I tried putting it in
many other directories.
Where exactly? There is often confusion about where "in the classpath" means. It can't just be anywhere. It has to be at the 'top' or the 'default package'.
src
├── main
│ └── java
│ ├── com
│ │ └── example
│ └── log4j2.xml
A tip for eclipse users:
Right click on the project and click "refresh". Make sure you could see the log4j2.xml file in eclipse.
(This solved my problem.)
To be verbose:
You shouldn't add the file to build path.(If you do, eclipse will warn you about this)
The name of this file doesn't appear in '.classpath' file.
I put my log4j2.xml under src/ directory. It works.
I had similar problem. I put the file under src folder and it worked. I did not mention any package name in the log4j2.xml file.
In the documentation of log4j 2: http://logging.apache.org/log4j/2.x/manual/configuration.html#AutomaticConfiguration
"If a JSON file cannot be located the XML ConfigurationFactory will try to locate log4j2.xml on the classpath."
but it is not working with classpath. Instead if we keep it in src folder, then it is working.
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
similar problem is mentioned here : https://issues.apache.org/jira/browse/LOG4J2-357
I had the problem, I tried some solutions, but only this worked to me:
Go to web.xml, and add this parameter:
<context-param>
<param-name>log4jConfiguration</param-name>
<param-value>log4j2.xml</param-value>
</context-param>
I'm quite sure that you have to write down the full qualified name of the class whose messages you want to be logged - something like com.application.log4jtest.YourClass. If that doesn't work, try fiddling with the log level.
Also - just as a notice - you can also write
Logger logger = LogManager.getLogger(MyClass.class); // omit .getClass()
I also faced the same problem.I kept my log4j2.xml file in System environment variable.
Variable name : sys_logroot Variable value : D:\user\gouse
and no logs are created for me.
use the system variable-Dlog4j.configurationFile=path/to/log4j2.xmlSee here
This solve my problem
I had the same 'ERROR StatusLogger No log4j2 configuration file found. Using default configuration: logging only errors to the console.' message over and over. It made me crazy. The log4j2.xml file was placed correctly at src/main/resources, like i did at thousands of projects before.
The solution in my case was to remove <packaging>pom</packaging> from the root pom.xml. packaging pom causes the content of src/main/resources not to be copied to target/classes.
Happy logging for anyone with the same root cause.
Ok, I solved the problem.
I had to specify in the xml the package="myPackage"