Question about Log4jAppender - java

i have started learning something about log4j as so far its working fine here is the code from the log4j.property file
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1,xml
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d [%t] %-5p %c - %m%n
# ${applicationRoot}/logs/xml.log
log4j.appender.xml=org.apache.log4j.RollingFileAppender
log4j.appender.xml.File=G:/TESTGEN/logs/xmlimpex.log
log4j.appender.xml.MaxFileSize=2MB
log4j.appender.xml.MaxBackupIndex=2
log4j.appender.xml.layout = org.apache.log4j.PatternLayout
log4j.appender.xml.layout.ConversionPattern=%p %t %c - %m%n
and its working perfectly fine printing on the console as well logging to the file.I am wondering is it possible to do something as follow
i want that i should be able to log everything on the console which what this log4j file is doing
but on the same time i want that in the log file which i have configured using RollingFileAppender should log entries only for warning and errors.
Please suggest me how i can do this
Thanks in advance
Umesh

log4j.rootLogger=DEBUG,A1
log4j.newlogger=WARN, XML
Log4j works in this way: You can create multiple loggers which fit in a hiearchy where the Root logger is always at the top. Loggers can inherit levels and appenders (if the additivity flag is on) from parent loggers.
In the example I gave you, the new logger that you created is triggered at a WARN level. It has as appenders XML but also A1 (which it inherited from the Root logger).
Note that if we hadn't set the level of newLogger, it would have inherited the level DEBUG.
Hiearchies in log4j work like in java packages (using dots) and rely on the logger names. Logger X is the parent of logger X.Y which is the parent of logger X.Y.Z. Logger X is always the child of the Root logger.
You can read more about this in the Log4j introduction

In the documentation of Log4net it says somewhere that you can set which levels to be handled from the appender.

Related

How to filter log4j logs besides log levels?

I need to filter some log.info console statements meant for prod maven profile, while I'm in dev.
For example:
log4j.properties
# Root logger option
log4j.rootLogger = INFO,console,file
# Direct log messages to a log file
log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.layout=org.apache.log4j.PatternLayout
log4j.appender.file=org.apache.log4j.DailyRollingFileAppender
log4j.appender.file.File=${catalina.home}/logs/application.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %-5X{username} %c{1}:%L - %m%n
MyClass.java
public class MyClass{
private static final Log log = LogFactory.getLog(MyClass.class);
and then in some place we use log.info writing many info for production. I want to remove this info while developing. Maybe for such production case I could use different logger, turning his output on/off in properties (depending on maven profile).
Thanks
You can use differnt logger and configure log4j to use differnt log levels for them. If you do not want some of them just set NONE as log level.

SLF4J-Log4j logger not logging

I am trying to use SLF4J-Log4j for the first time. In every Java class, I define a logger like so:
private org.slf4j.Logger logger = org.slf4j.LoggerFactory.getLogger(<TheClass>.class);
(And of course, I make sure that the slf4-log4j12-1.6.4.jar JAR is on the classpath!)
But whenever I go to use the logger, like logger.debug("Something interesting happened"); or logger.error("An error occurred");, I don't see their output in my log files. However, no exceptions occur and the app (its actually a WAR deployed to Tomcat) runs fine.
Here is the log4j.properties file included in the project:
# Set the root logger to DEBUG.
log4j.rootLogger=DEBUG
# MonitorLog - used to log messages in the Monitor.log file.
log4j.appender.MonitorAppender=org.apache.log4j.FileAppender
log4j.appender.MonitorAppender.File=${catalina.base}/logs/MyAppMonitor.log
log4j.appender.MonitorAppender.layout=org.apache.log4j.PatternLayout
log4j.appender.MonitorAppender.layout.ConversionPattern= %-4r [%t] %-5p %c %x - %m%n
# Use the MonitorAppender to log all messages.
log4j.logger.*=DEBUG,MonitorAppender
org.quartz.impl.StdSchedulerFactory=DEBUG,MonitorAppender
This WAR uses Quartz to cron a few jobs, which is why you see that last entry.
When I check Tomcat's logs/ directory, I see the MyAppMonitor.log get created, but it has nothing in it (0 bytes). I've scanned all the typical catalina.out, catalina-, and localhost- logs as well, and none of my log statements are seeing the light of day.
I am thinking:
I don't have log4j.properties configured right, or
I don't have slf4j-log4j configured right, or
This is a classpath issue and perhaps the WAR can't find log4j.properties (although I would imagine I would see errors or warnings for this), or
I'm not using (the API itself) SLF4J correctly, or
I never actually created something called MonitorAppender, so I'm wondering if this is the problem; I was just following an example I saw online
Can anybody spot where I'm going awrye, or help me troubleshoot this? Thanks in advance!
Your log4j.properties configuration file is has a number of errors in it. Try with something simple like the following.
log4j.debug=true
log4j.rootLogger=DEBUG, CON
log4j.appender.CON=org.apache.log4j.ConsoleAppender
log4j.appender.CON.layout=org.apache.log4j.PatternLayout
log4j.appender.CON.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
As for the configuration file in your question, the root logger does not have an appender attached. Moreover, the line
log4j.logger.*=DEBUG,MonitorAppender
is not valid as '*' is not supported.

log4j property change not getting reflected in Eclipse

This was the log4j file I used for my project till I checked in my project to a SVN repository. This was working fine and I saw log information on Eclipse's console
log4j.rootLogger=debug, stdout, R
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
# Pattern to output the caller's file name and line number.
log4j.appender.stdout.layout.ConversionPattern=%d - %p %t %C.%M (%F:%L) %m%n
log4j.appender.R=org.apache.log4j.RollingFileAppender
log4j.appender.R.File=x.log
log4j.appender.R.MaxFileSize=100KB
# Keep one backup file
log4j.appender.R.MaxBackupIndex=1
log4j.appender.R.layout=org.apache.log4j.PatternLayout
log4j.appender.R.layout.ConversionPattern=%d - %p %t %C.%M (%F:%L) %m%n
I checked out my project from repository and disabled logging by making this change in my log4j property file.
#log4j.rootLogger=debug, stdout, R
log4j.rootLogger=OFF
But this change didn't work as expected, I still got the log information on Eclipse's console. When I cross checked the same on Terminal, it was fine, I didn't get log info on Terminal. Any problem with Eclipse? I searched a lot on this issue, didn't get any solution. Help me in finding out what's wrong here!!!
There are two possible issues here:
the configuration should say (to tell it no appenders, instead of looking for OFF appender):
log4j.rootLogger=
Eclipse is using an old version of the file, likely because you edited the file outside of Eclipse. Just refresh the file (Right click / Refresh) and it should start working as you expect.
Use the -Dlog4j.debug property to output log4j-internal debugging information and see which logging configuration is really loaded on startup
You will get some information like this (for xml based configuration but I suppose you will get similar informations with property file configurations):
log4j: Trying to find [log4j.xml] using context classloader sun.misc.Launcher$AppClassLoader#11b86e7.
log4j: Using URL [file:/C:/develop/workspace/foobar/target/classes/log4j.xml] for automatic log4j configuration.
log4j: Preferred configurator class: org.apache.log4j.xml.DOMConfigurator
The 'log4j: Using URL ...' line comes from the LogManager class.

Please initialize the log4j system properly. While running web service

Maybe it looks silly to ask this but I am confused. I referred to Configuring Log4j property but it doesn't seem to help.
I have written a simple web service HelloWorld. And while running it I am getting the error something like this :
log4j:WARN No appenders could be found for logger (org.apache.axis.transport.http.AxisServlet).
log4j:WARN Please initialize the log4j system properly.
I am not sure why its happening.
I am generating the web-service using Eclipse and deployed in Tomcat 6.0. I check on Axis Developer's Guide and according to them
log4j.configuration=log4j.properties
Use this system property to specify the name of a Log4J configuration file. If not specified, the default configuration file is log4j.properties. A log4j.properties file is provided in axis.jar.
I didn't find log4j.properties in the axis.jar.
Any help on this?
Those messages are something tricky, enough so that people created this to make it clearer:
https://issues.apache.org/bugzilla/show_bug.cgi?id=25747
What's tricky about them is that the warnings are written if Log4j can't find its log4j.properties (or log4j.xml) file, but also if the file is fine and dandy but its content is not complete from a configuration point of view.
The following paragraph is taken from here:
http://svn.apache.org/repos/asf/logging/log4j/tags/v1_2_9/docs/TROUBLESHOOT.html
Logging output is written to a target by using an appender. If no appenders are attached to a category nor to any of its ancestors, you will get the following message when trying to log:
log4j: No appenders could be found for category (some.category.name).
log4j: Please initialize the log4j system properly.
Log4j does not have a default logging target. It is the user's responsibility to ensure that all categories can inherit an appender. This can be easily achieved by attaching an appender to the root category.
You can find info on how to configure the root logger (log4j.rootLogger) in the log4j documentation, basically adding something as simple as this at the beginning of the file:
log4j.rootLogger=debug, stdout
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
This should clear those WARN messages you get on startup (make sure you don't already have an appender named stdout; also be carefull of what level you give the root logger, debug will be very verbose and every library in your app will start writing stuff to the console).
As about the log4j.properties/log4j.xml, I suggest you place this file in /WEB-INF/classes as it is important to have it exposed for different tweaks (activating/deactivating logs, changing log levels etc). You can have it inside a JAR in the classpath also (as you specified in your comment), but it will be enclosed in the archive (hopefully in the right place inside the archive) and won't be as easy to handle as if it were in /WEB-INF/classes.
You have to create your own log4j.properties in the classpath folder.
Well, if you had already created the log4j.properties you would add its path to the classpath so it would be found during execution. Yes, the thingy will search for this file in the classpath.
Since you said you looked into axis and didnt find one, I am assuming you dont have a log4j.properties, so here's a crude but complete example.
Create it somewhere and add to your classpath. Put it for example, in c:/proj/resources/log4j.properties
In your classpath you simple add .......;c:/proj/resources
# Root logger option
log4j.rootLogger=DEBUG, stdout, file
# Redirect log messages to console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
# Redirect log messages to a log file, support file rolling.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=c:/project/resources/t-output/log4j-application.log
log4j.appender.file.MaxFileSize=5MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
If the below statment is present in your class then your log4j.properties should be in java source(src) folder , if it is jar executable it should be packed in jar not a seperate file.
static Logger log = Logger.getLogger(MyClass.class);
Thanks,
Warning No appenders could be found for logger means that you're using log4j logging system, but you haven't added any Appenders (such as FileAppender, ConsoleAppender, SocketAppender, SyslogAppender, etc.) into your configuration file or the configuration file is missing.
There are three ways to configure log4j: with a properties file (log4j.properties), with an XML file and through Java code (rootLogger.addAppender(new NullAppender());).
If you've property file present (e.g. when installing Solr), you need to place this file within your classpath directory.
classpath
Here are some command suggestions how to determine your classpath value:
$ echo $CLASSPATH
$ ps wuax | grep -i classpath
$ grep -Ri classpath /etc/tomcat? /var/lib/tomcat?/conf
or from Java: System.getProperty("java.class.path").
Tomcat
If you're using Tomcat, you may place your log4j.properties into: /usr/share/tomcat?/lib/ or /var/lib/tomcat?/webapps/*/WEB-INF/lib/ folder.
Solr
For the reference, Solr log4j.properties looks like:
# Logging level
solr.log=logs/
log4j.rootLogger=INFO, file, CONSOLE
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern=%-4r [%t] %-5p %c %x \u2013 %m%n
#- size rotation with log cleanup.
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.MaxFileSize=4MB
log4j.appender.file.MaxBackupIndex=9
#- File to log to and log format
log4j.appender.file.File=${solr.log}/solr.log
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%-5p - %d{yyyy-MM-dd HH:mm:ss.SSS}; %C; %m\n
log4j.logger.org.apache.zookeeper=WARN
log4j.logger.org.apache.hadoop=WARN
# set to INFO to enable infostream log messages
log4j.logger.org.apache.solr.update.LoggingInfoStream=OFF
If you are using Logger.getLogger(ClassName.class) then place your log4j.properties file in your class path:
yourproject/javaresoures/src/log4j.properties (Put inside src folder)
You can configure log4j.properties like above answers, or use org.apache.log4j.BasicConfigurator
public class FooImpl implements Foo {
private static final Logger LOGGER = Logger.getLogger(FooBar.class);
public Object createObject() {
BasicConfigurator.configure();
LOGGER.info("something");
return new Object();
}
}
So under the table, configure do:
configure() {
Logger root = Logger.getRootLogger();
root.addAppender(new ConsoleAppender(
new PatternLayout(PatternLayout.TTCC_CONVERSION_PATTERN)));
}

How to configure log4j.properties for SpringJUnit4ClassRunner?

Suddenly this keeps happening during a JUnit test. Everything was working, I wrote some new tests and this error occured. If I revert it, it won't go away. Why is that?
log4j:WARN No appenders could be found for logger (org.springframework.test.context.junit4.SpringJUnit4ClassRunner).
log4j:WARN Please initialize the log4j system properly.
log4j:WARN See http://logging.apache.org/log4j/1.2/faq.html#noconfig for more info.
The new tests you wrote (directly or indirectly) use classes that log using Log4j.
Log4J needs to be configured for this logging to work properly.
Put a log4j.properties (or log4j.xml) file in the root of your test classpath.
It should have some basic configuration such as
# Set root logger level to DEBUG and its only appender to A1.
log4j.rootLogger=DEBUG, A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
# A1 uses PatternLayout.
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%-4r [%t] %-5p %c %x - %m%n
# An alternative logging format:
# log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n
An appender outputs to the console by default, but you can also explicitly set the target like this:
log4j.appender.A1.Target=System.out
This will redirect all output in a nice format to the console. More info can be found here in the Log4J manual,
Log4J Logging will then be properly configured and this warning will disappear.
If you don't want to bother with a file, you can do something like this in your code:
static
{
Logger rootLogger = Logger.getRootLogger();
rootLogger.setLevel(Level.INFO);
rootLogger.addAppender(new ConsoleAppender(
new PatternLayout("%-6r [%p] %c - %m%n")));
}
Add a log4j.properties(log4j.xml) file with at least one appender in root of your classpath.
The contents of the file(log4j.properties) can be as simple as
log4j.rootLogger=WARN,A1
# A1 is set to be a ConsoleAppender.
log4j.appender.A1=org.apache.log4j.ConsoleAppender
log4j.appender.A1.layout=org.apache.log4j.PatternLayout
log4j.appender.A1.layout.ConversionPattern=%d{ISO8601} [%t] %-5p %c %x - %m%n
This will enable log4j logging with default log level as WARN and use the java console to log the messages.
I have the log4j.properties configured properly. That's not the problem. After a while I discovered that the problem was in Eclipse IDE which had an old build in "cache" and didn't create a new one (Maven dependecy problem). I had to build the project manually and now it works.
I was using Maven in eclipse and I did not want to have an additional copy of the properties file in the root folder. You can do the following in eclipse:
Open run dialog (click the little arrow next to the play button and go to run configurations)
Go to the "classpath" tab
Select the "User Entries" and click the "Advanced" button on the right side.
Now select the "Add External folder" radio button.
Select the resources folder
I know this is old, but I was having trouble too. For Spring 3 using Maven and Eclipse, I needed to put the log4j.xml in src/test/resources for the Unit test to log properly. Placing in in the root of the test did not work for me. Hopefully this helps others.
Because I don't like to have duplicate files (log4j.properties in test and main), and I have quite many test classes, they each runwith SpringJUnit4ClassRunner class, so I have to customize it. This is what I useļ¼š
import java.io.FileNotFoundException;
import org.junit.runners.model.InitializationError;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;
import org.springframework.util.Log4jConfigurer;
public class MySpringJUnit4ClassRunner extends SpringJUnit4ClassRunner {
static {
String log4jLocation = "classpath:log4j-oops.properties";
try {
Log4jConfigurer.initLogging(log4jLocation);
} catch (FileNotFoundException ex) {
System.err.println("Cannot Initialize log4j at location: " + log4jLocation);
}
}
public MySpringJUnit4ClassRunner(Class<?> clazz) throws InitializationError {
super(clazz);
}
}
When you use it, replace SpringJUnit4ClassRunner with MySpringJUnit4ClassRunner
#RunWith(MySpringJUnit4ClassRunner.class)
#ContextConfiguration("classpath:conf/applicationContext.xml")
public class TestOrderController {
private Logger LOG = LoggerFactory.getLogger(this.getClass());
private MockMvc mockMvc;
...
}

Categories

Resources