Matteo Ceccarello
Matteo Ceccarello

Reputation: 231

log4j not logging messages from classes other than main

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.

Upvotes: 4

Views: 6041

Answers (2)

Ryan Stewart
Ryan Stewart

Reputation: 128829

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.

Upvotes: 2

Jeshurun
Jeshurun

Reputation: 23186

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.

Upvotes: 1

Related Questions