Question

I'm relatively new to log4j (v2), but I believe I've exhausted my resources, so I come to ask my question here.

I have a working log4j configuration, which I will append to the end of my question. The application is run every x minutes using a cronjob.

The log4j behaviour I'd like to see is the following:

  1. All INFO (and up) logging is done to file A
  2. All ERROR (and up) logging is done to file B
  3. In case of an ERROR (or up), a mail is sent containing the DEBUG (and up) lines of the given execution.

I have achieved 1 and 2 using the configuration below. Is number 3 also possible using log4j (if not, why not?) and if so, how?

The current configuration:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="INFO">
  <Appenders>
    <Console name="Console" target="SYSTEM_OUT">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </Console>
    <RandomAccessFile name="LogFile" fileName="/var/log/fileA.log">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </RandomAccessFile>
    <RandomAccessFile name="ErrorLogFile" fileName="/var/log/fileB.log">
      <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
    </RandomAccessFile>
    <SMTP name="MailError" subject="Error occurred" to="a@b.com" smtpHost="mail.foo.bar" from="b@c.net"/>
    <Async name="Async">
      <AppenderRef ref="LogFile"/>
    </Async>
    <Async name="Errors">
      <AppenderRef ref="ErrorLogFile"/>
      <AppenderRef ref="MailError"/>
    </Async>
  </Appenders>
  <Loggers>
    <Root level="DEBUG">
      <AppenderRef ref="Console" level="INFO"/>
      <AppenderRef ref="Async" level="INFO"/>
      <AppenderRef ref="Errors" level="ERROR"/>
    </Root>
  </Loggers>
</Configuration>
Was it helpful?

Solution

I think you should be able to achieve this with a ThresholdFilter. Make your root logger level TRACE so that it sends all events to all appenders, then put different threshold filters on each appender. The log4j2 manual contains an example.


(EDIT) After understanding the requirements better, I think the SMTP Appender already does what you need: it internally keeps a buffer of the events (512 by default) that preceded the ERROR event that triggered the email. These preceding events will be included in the email.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top