I got a pecurliar behaviour when we stop a war in Weblogic 12c and then start it again. For some reason beyond my understanding Log4j2 stops writing to the log. It creates a new logfile but no entries are written.
I have debugged and sees that Log4jServletContainerInitializer and Log4jServletContextListener gets called just like they do when installing the war. I didn't notice any differences (unfortunally thats only a test of my attention span).
So do you have any idea of what might differ between install and start in regards of Log4J2 in Weblogic 12c and perhaps where to look for errors?
Your problem:
For some reason beyond my understanding Log4j2 stops writing to the log. It creates a new logfile but no entries are written.
Root Cause Analysis:
It is actually happen for some issues.
If your configuration for log4j is not correctly done in
log4j.properties file.
If your append properties are not made true.
If you use two loggers like Log4J and JUL, which uses the same
appneder(Stdout).
If your log4j jar file is not properly set to your classpath.
Solution:
Ans-1:
In your classpath, there is a setting of library that intercepts Log4J calls and converts them to JUL calls. Then it may cause this issue. So specify correctly that which importing is actually needed. java.util.logging.Logger or org.apache.log4j.Logger
Ans-2:
Properties are case sensitive. so your file name would be same with appender. and don't forget to make the appender to true.
log4j.appender.mainAppender.File=yourLogFile.log
log4j.appender.mainAppender.Append=true
Ans-3:
for Hibernate in particular, include slf4j in order to ensure that all the loggers co-operate with it.
Ans-4:
Sometimes this problem occurs for tomcat. If tomcat security enabled, and there were several permissions missing from the policy files, then this type of issue occurs. After giving permissions, it will work fine.
What Log4J does actually?
Log4J will only print messages which are info and up, and it will print them to both console and file. You can change this behaviour by changing INFO to ALL in log4j.rootLogger. If that doesn't work, add -Dlog4j.debug=true to your JVM arguments - that will make Log4J emit debug messages about itself (to System.out), so you can see what's going on.
Credit goes to #Isaac
Resource Link:
Log4J creates log file but does not write to it
Issue with log4j log not writing to file
UPDATE for log4j2:
Thanks a lot to rgoers for pointing the issue for log4j2. I am updating.
Root cause analysis from P.O.V of wilkinsona
When a restart is triggered, DevTools runs and then clears all registered shutdown hooks. One such hook is Log4J2's DefaultShutdownCallbackRegistry. Log4jContextFactory maintains a reference to the DefaultShutdownCallbackRegistry and LogManager holds a static reference to Log4jContextFactory. Log4J2's classes are loaded by the app classloader which means that there's a single LogManager, Log4jContextFactory, and DefaultShutdownCallbackRegistry shared across restarts.
When DefaultShutdownCallbackRegistry is run as part of a restart it stops the LoggerContext and sets its own state to STOPPED. As the restart proceeds a new LoggerContext is created and an attempt is made to register a shutdown callback for it with the registry. This fails as the registry's state is still STOPPED.
Solution:
Wilkinsona offered a hack method to solve the issue. That is given below. Try to cope with it.
Clearing out the callbacks in the registry before the Restarter runs the JVM's shutdown hooks is better. It prevents the exception from occurring, and logging continues to work after a restart.
private void prepareLog4J2ForRestart() throws Exception {
if (ClassUtils.isPresent("org.apache.logging.log4j.LogManager",
getClass().getClassLoader())) {
LoggerContextFactory factory = LogManager.getFactory();
Field field = ReflectionUtils.findField(factory.getClass(),
"shutdownCallbackRegistry");
ReflectionUtils.makeAccessible(field);
ShutdownCallbackRegistry shutdownCallbackRegistry = (ShutdownCallbackRegistry) ReflectionUtils
.getField(field, factory);
Field hooksField = ReflectionUtils
.findField(shutdownCallbackRegistry.getClass(), "hooks");
ReflectionUtils.makeAccessible(hooksField);
#SuppressWarnings("unchecked")
Collection<Cancellable> state = (Collection<Cancellable>) ReflectionUtils
.getField(hooksField, shutdownCallbackRegistry);
state.clear();
}
}
Resource Link:
Log4j 2.4 breaks rc1 devtools
Call context.close() rather than shutdown hook in DevTools restart
UPDATE2:
What kind of listener to add to my JEE application, to get the
expected behaviour?
For writing a listener, you can follow the tutorials
ServletContextListener Example
Writing a Listener Class
Servlet Listener Example – ServletContextListener,
HttpSessionListener and ServletRequestListener
Related
I am using JULI logging framework in current Tomcat 7, providing a webapp specific logging.properties in my WEB-INF/classes folder.
Now I am looking for a way to change the log level of a logger at runtime.
I found several sources saying that changing the level of a logger at runtime might be possible via MBean Server. Unfortunately the appropriate MBean "java.util.logging.Logging" does not list my webapp specific logger, so I cannot execute the method "setLoggerLevel".
Does anyone know how to accomplish this? Thanks for any hints - excluding those suggesting to use log4j, that is... ;-)
Connecting JConsole to Tomcat and using the MBean tab to change the logger level is the ideal way. One issue is that the logger names don't exist unless the code has triggered the creation of a logger. You can't use the MBean to create a logger ahead of the code running. You should use JConsole to double check that the MBean itself doesn't exist.
Tomcat installs a custom LogManager that filters by the current class loader. JMX would be using the system class loader so it is possible that ClassLoaderLogManager won't return the logger names because the current classloader is not the web app classloader.
You could always create a servlet/jsp form or webservice deployed with the application to get the logger and set the level. You might have to pin each modified logger in memory to keep your logger level active. You can free the logger once the level is set back to null. You'll have to deal with security concerns with including such a page.
I wouldn't do this on a production server but you can configure a WatchedResource in tomcat that points to your logging.properties. Then any time that file is updated the web app is redeployed with the new settings. Watch out for ClassLoader leaks going that route.
My application is using Spring to handle the interaction with database (Sql Server)
And commons-logging-1.1.1.jar, log4j-1.2.17.jar, slf4j-api-1.6.3.jar and slf4j-log4j12-1.7.6.jar are put into build path for the logging framework of the application.
The last two logging jar (slf4j-api and slf4j-log4j12) are for another component inside the application to use log4j.
Here is my questions:
When Spring-Jdbc runtime excecption happens, the exception is only showed in the console of eclipse with the font color red. The exception is NOT logged into the log file. But the normal log (like log.info(...)) are all in the log file. Why can't the run-time exception be in the log file and how to solve this problem.
When I use SimpleJdbcCall to call the stored procedure with parameters in MapSqlParameterSource, the following log shows up:
14:43:30 [INFO ] Added default SqlReturnUpdateCount parameter named #update-count-1
14:43:30 [INFO ] Added default SqlReturnUpdateCount parameter named #update-count-1
......
It's really annoying because the number of this message is so large. I want to turn off this particular log message without affecting another logging with the same level (INFO)
And my log4j.xml is fine I think because the logging are basically fine except the above issues.
Spring is using commons-logging internally that's why you can see the messages in your eclipse console. To redirect commons-logging to slf4j/log4j you need to remove commons-logging-1.1.1.jar from your classpath and add jcl-over-slf4j.jar from your slf4j version. To get rid of the dublicate red eclipse messages (jul and jcl) you can set the logging level in logging.properties for the console handler to warning:
java.util.logging.ConsoleHandler.level = WARNING
Second issue was solved here.
As per Spring Doc API http://docs.spring.io/spring-framework/docs/current/javadoc-api/index.html?org/springframework/web/context/ContextLoaderListener.html -
This (ContextLoaderListener) listener should be registered after Log4jConfigListener in web.xml
I am not getting why Log4jConfigListener is to be registered first?
The documentation does not dive into details regarding their stated preference for this order. I would assume this order is recommended so that logging is property configured prior to registration of the ContextLoaderListener, which would allow debug messages to be logged appropriately during registration.
When using a custom log4j configuration (per application log4j-app.xml for instance) this needs to be bootstrapped BEFORE anything else. If not log4j will be bootstrapped using the global log4j.xml (or defaults) instead of the custom file.
The ContextLoaderListener (or many other classes) will trigger bootstrapping log4j, in which case you could endup with a different configuration as you expected. Also with an added risk of the Log4jConfigListener at application shutdown trying to destroy/close the global log4j system... (This can be the case if you don't ship log4j in your app but rely on your app-servers shipped log4j version).
I have a server I made in Java that needs to use a database, I chose HSQLDB.
So I have a lot of entries in my server like:
Logger.getLogger(getClass().getName()). severe or info ("Some important information");
When I run my server it goes to System.out which I think its the default configuration of java.util.logging?, so far its ok for me, and later I will make it go to a file ...
But, the problem is, when I start hsqldb it messes up with the default configuration and I can´t read my log entries on System.out anymore..
I already tried to change hsqldb.log_data=false, but it still messes up the default configuration.
Can someone help me??
I dont want to log hsqldb events, just my server ones.
Thanks
This issue was reported and fixed in the latest version 2.2.0 released today.
Basically, you set a system property hsqldb.reconfig_logging to the
string value false.
A system property is normally set with the -D option in the Java startup command for your application:
java -Dhsqldb.reconfig_logging=false ....
See below for details of the change:
http://sourceforge.net/tracker/?func=detail&aid=3195462&group_id=23316&atid=378131
In addition, when you use a fremework logger for your application, you should configure it directly to choose which levels of log to accept and which ones to ignore.
The hsqldb.applog setting does not affect framework logging and only controls the file log.
The hsqldb.log_data=false is for turning off internal data change logging and should not be used for normal databases. Its usage for bulk imports is explained in the Guide.
Try setting hsqldb.applog to 0, that shuts off application logging to the *.app.log file.
Start your server with a property pointing to the location of a dedicated properties file:
-Djava.util.logging.config.file=/location/of/your/hsqldblog.properties"
Which contains the following line to change Java logging for Hsqldb.
# Change hsqldb logging level
org.hsqldb.persist = WARNING
Side note, you can choose from the following levels:
SEVERE WARNING INFO CONFIG FINE FINER FINEST
Enviroment: JSF 2.0, RichFaces 3.3.3, Facelets 1.1.15B1, Spring Framework 3.x, WebFlow 2.1, MyBatis 3.0.1, Oracle 10/11 g backend, SLF4j into Log4j. Well thats probably TMI since my issue is only a logging problem but better to be too thorough than not.
Anyways... I just setup SLF4j & log4j so now all of the internal facelets log msgs are being dumped into log4j & I can actually see them. In addition I setup Tomcat to also dump to log4j instead of it's custom version of JULI. Upon doing this everything appeared to be working great.... until i shut down the app.
Midway through the shutdown process my app started barfing up errors left 'n right because (which makes sense) Tomcat is trying to grab a logger instance AFTER spring has already cleaned up the logger bean.
Anyone familiar with this? I imagine it must be a common problem for anyone who has Tomcat using the non-standard logging mechanism. What is the best way around this?
I thought maybe if I just raised the log level then Tomcat wouldn't even try to log msgs because of the level req.s but the problem occurs when tomcat is trying to retrieve a logger instance so that didn't work.
I would move the Logger higher in the food chain.
I personally never configured log4j with spring relying on its own configuration mechanism (and hunting for where the heck it finds the properties file it is using in the process).
If you can you can opt to completely remove log4j from your war and rely on the log4j in the common tomcat library classpath. Then of course you are at the mercy of the tomcat configuration and you cannot access the log from inside your app, but it is always there during the complete lifecycle of your app.