Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

log4j not logging messages from classes other than main

Tags:

java

log4j

I'm trying to figure out how to get log4j working in my project. I have 2 classes, one named testWithMain.TestSectionSplit and the other named search.SectionScanner. In TestSectionSplit I call

Logger log = Logger.getLogger(TestSectionSplit.class);
PropertyConfigurator.configure(FilePaths.LOGGER_CONFIG);

where FilePaths.LOGGER_CONFIG points to a configuration file. In class SectionScanner I simply create a static field

private Logger logger = Logger.getLogger(SectionScanner.class);

The configuration file looks like

# =========================
# appenders configuration
# =========================

# console

log4j.appender.console=org.apache.log4j.ConsoleAppender
log4j.appender.console.threshold=ALL
log4j.appender.console.layout=org.apache.log4j.PatternLayout


# =========================
# loggers configuration
# =========================

log4j.rootLogger=ALL, console

log4j.logger.search.SectionScanner=ALL, console

The problem is that while logging messeges wirtten in TestSectionSplit are correctly logged on console, the messages from SectionScanner aren't printed, giving me this error message

log4j:ERROR Attempted to append to closed appender named [console].

If i comment out the line

log4j.logger.search.SectionScanner=ALL, console

in configuration file, no log messages nor errors are printed. I can't understand what I'm doing wrong.

like image 420
Matteo Ceccarello Avatar asked Oct 15 '25 04:10

Matteo Ceccarello


2 Answers

By calling PropertyConfigurator.configure() in your code, you're reconfiguring log4j after it's already been initialized. Whatever configuration it was initialized with first, it also had an appender named "console". When you reinitialize log4j, that appender gets closed, but some other thread was trying to write to it: hence the error. If this is the configuration you want to use, configure your app to use it from the start instead of reinitializing logging while the app is running.

like image 85
Ryan Stewart Avatar answered Oct 16 '25 16:10

Ryan Stewart


It seems you have the default log4j.properties or log4j.xml file in your classpath as well, or you are loading a different properties file, and the default file also has the log4j.logger.search.SectionScanner appender defined. Try commenting out that line, and see if it logging still works, or make sure you either don't have the default file in your classpath, or have the same appender defined twice in two different properties files.

like image 31
Jeshurun Avatar answered Oct 16 '25 18:10

Jeshurun



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!