Leaving out all the other things you'll need to figure out before this example will be all that useful, all you have to do is modify the log configuration and it will print the class and line for you when you print out a log message.
I hate to say it cause it's trite but RTFM is the best approach here. This page will tell you most all you need to get started:
http://logging.apache.org/log4j/1.2/manual.html
All you need is a specific ConversionPattern config option for your logger and it will log the class name and even line information each time you log a message. Here is an example from that page:
// Import log4j classes. import org.apache.log4j.Logger; import org.apache.log4j.PropertyConfigurator; // log4j.appender.console.layout.ConversionPattern=%d{yyyyMMdd HH.mm.ss} %-5p %C.%M(%L): %m%n class Simple { static Logger logger = Logger.getLogger(Simple.class); protected static void doIt() { logger.info("oh yea, we're doing it!"); logger.error(" f-you! joe Boy, you are done!"); logger.fatal("and the world went to bed"); } public static void main(String[] args) { // BasicConfigurator replaced with PropertyConfigurator. PropertyConfigurator.configure(args[0]); logger.info("Entering application."); doIt(); logger.info("Exiting application."); } }
which, when built and run produces the following:
14:39:56:--> java -classpath log4j-1.2.15.jar:. Simple log4j.properties 20120623 14.41.17 INFO Simple.main(17): Entering application. 20120623 14.41.17 INFO Simple.doIt(24): oh yea, we're doing it! 20120623 14.41.17 ERROR Simple.doIt(25): f-you! joe Boy, you are done! 20120623 14.41.17 FATAL Simple.doIt(26): and the world went to bed 20120623 14.41.17 INFO Simple.main(19): Exiting application.
when you use a conversion pattern like this: %d{yyyyMMdd HH.mm.ss} %-5p %C.%M(%L): %m%n
Here are a few more specifics:
1. get a copy of log4j jar and put it in directory 2. create Simple.java in directory 3. create a file log4j.properties in same directory, put this in file: log4j.rootLogger=DEBUG, A1 log4j.appender.A1=org.apache.log4j.ConsoleAppender log4j.appender.A1.layout=org.apache.log4j.PatternLayout log4j.appender.A1.layout.ConversionPattern=%d{yyyyMMdd HH.mm.ss} %-5p %C.%M(%L): %m%n 4. compile Simple.java with: javac -classpath log4j-1.2.15.jar:. Simple.java 5. run it with this: java -classpath log4j-1.2.15.jar:. Simple log4j.properties