7

I know in log4j you could use multiple appenders by doing something like:

log4j.logger.com.x=DEBUG, append1, append2

but what would the equivalence be in log4j2?

Would it be this:

logger.com.x.level = DEBUG
logger.com.x.appenderRefs = append1, append2

?

2 Answers 2

8

You did not provide in your example, what are the types of appenders append1 and append2, but this is important, when you are using the properties file. Let's say the appenders are defined as following:

appender.console.type = Console
appender.console.name = append1
...
appender.rolling.type = RollingFile
appender.rolling.name = append2
...

Loggers should be something like this:

logger.console.name = com.x
logger.console.level = debug
logger.console.additivity = false
logger.console.appenderRef.console.ref = append1

logger.rolling.name = com.x
logger.rolling.level = debug
logger.rolling.additivity = false
logger.rolling.appenderRef.rolling.ref = append2

I am suggesting this configuration according to the properties file configuration example in the manual. I am not doing this way and prefer the xml format. I recommend you to consider moving to xml format. Most of examples in the log4j2 documentation are for xml configuration format. In case of xml, loggers configuration is much compact and is just like this:

<Loggers>
    <Logger name="com.x" level="debug" additivity="false">
        <appenderRef ref="append1" />
        <appenderRef ref="append2" />
    </Logger>
    ...
</Loggers>
4
  • 1
    I agree that the Log4j 2 XML configuration is much simpler and better documented than Log4j 1.2. Most of the doc examples use XML so it will be much easier to solve problems (find similar configurations, get support) when you use the XML configuration format. Sep 25, 2016 at 1:44
  • ok thank you, so in your middle block you are adding the two appenders to one/the same logger, right? Sep 30, 2016 at 0:46
  • Yes. You can add multiple appenders for the same logger in such manner. You can provide different loglevel to a particular appenderRef.
    – asch
    Sep 30, 2016 at 13:52
  • 1
    The provided properties example is misleading as it will not work as expected. You will actually overwrite the 1st defined logger "logger.console.name = com.x" with the 2nd logger "logger.rolling.name = com.x" so only the 2nd logger will be active. To add the 2nd appender to the logger, just add a new appenderRef property for the initial logger: logger.console.appenderRef.appender2.ref = append2
    – Tudro
    Apr 21, 2021 at 6:15
7

I know this is a quite old question, but I found a solution by using the following syntax (using your example):

logger.com.x.appenderRef.app1.ref = append1
logger.com.x.appenderRef.app2.ref = append2

In this way everything worked fine.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.