0
votes

I have a log4j configuration XML which has multilple file appenders. As I am building a new module for my application, I want to include one more file appender and use only that file. Is there anyway to do it?

I tried using Logger.getLogger("MyAppender"); But in the log file, I should get the class name.. With this I am getting only the appender name in the log file.

My appender configuration is somethig like this.

" "

The log shows as below.. 31 Oct 2013 10:58:46,032 INFO MyAppender Hello World

But I need

31 Oct 2013 10:58:46,032 INFO MyClass Hello World

1
Has the new module a unique java root package?Paul Vargas

1 Answers

0
votes

I would say your requirement is to use a different logger for your new package structure (the one in your new module).

For eg:- if the package structure used in your new module is a.b.*, then the below property file will fit for your purpose.

# Root logger option
log4j.rootLogger=INFO,stdout

# Direct log messages to stdout
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

# Direct log messages to your file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
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

#Package logger option
log4j.logger.a.b=INFO,file (see note 1)
log4j.additivity.a.b=false (see note 2)

Note 1:- Define a new logger for the new package. Any class defined under this package or under sub-packages would use this logger. Read here to know more about Named Hierarchy. In your java, you can use

Logger logger = Logger.getLogger(yourClass)

Note 2:- Switch off the additivity so that, the log will be printed only in the appender added to logger a.b.Read here to know more about additivity.