Configuring Log4j Loggers Programmatically

I am trying to use SLF4J (with log4j binding) for the first time.

I would like to configure 3 different named Loggers that can be returned by a LoggerFactory which will log different levels and push the messages to different appenders:

  • Logger 1 “FileLogger” logs DEBUG and appends to DailyRollingFileAppender
  • Logger 2 “TracingLogger” logs TRACE+ and appends to a JmsAppender
  • Logger 3 “ErrorLogger” logs ERROR+ and appends to a different JmsAppender

Furthermore I want them configured programmatically (in Java, as opposed to XML or a log4j.properties file).

I imagine that, normally, I would define these Loggers somewhere in some bootstrapping code, like an init() method. However, because I want to use slf4j-log4j, I’m confused about where I could define loggers and make them available to the classpath.

I don’t believe this is a violation of SLF4J’s underlying purpose (as a facade), because my code using the SLF4J API won’t ever know that these loggers exist. My code just makes normal calls to the SLF4J API, which then forwards them on to the log4j Loggers it finds on the classpath.

But how do I configure those log4j Loggers on the classpath…in Java?!

4 Answers
4

Leave a Comment