简体   繁体   中英

How do I set a custom subject in SmtpAppender in log4j2

Our application is deployed as a servlet war to multiple tomcat servers under multiple customer contexts:

customer#application.war

We're using log4j2 as our logging and alert email mechanism. So far, everything is working great and our fatal errors are being sent. However, as we deploy to new contexts, it's becoming less clear which customer is generating the error.

So far, it appears that the subject value is static and set in the config file and the system variables are loaded when the logger is built:

subject="[${applicationname}] Fatal Error ${hostname}:${sys:pwd}"

While it appears that there is a way to ascertain the name of our deployed context via the servlet API, we have yet to determine how to introduce this value in the email subject programmatically and dynamically at run time.

This would greatly reduce the time it takes to research an error. Any tips?

So far we've considered the following:

  1. Custom war file with custom log4j2 config for each customer context (very hackish)
  2. Update all log.fatal calls to include the context info from the servlet (horrid)
  3. Custom SmtpAppender (final and protected so that's out)
  4. Custom SmtpManager and override the subject in the MimeMessage object (seems workable but the documentation does not show how to implement)

TIA!!

Piko

This is actually a known issue in Log4j2 as of 2.9.1. The problem is that a MimeMessage is cached and the subject becomes a fixed value. A simple solution would be to stop caching.

There is an open ticket to address this: Log4j2-1450 . (Related: Log4j2-1192 , which implemented pattern lookups but didn't fix that MimeMessages are cached.)

If you can provide a patch or a pull request it would greatly increase the chances of this being addressed speedily.


Update: looking my old comment in that ticket:

Looks like subject already supports $$ runtime lookups. The following attributes are used for each email that is sent, and it should be possible to support runtime lookups for these attributes: * from * replyto * to * cc * bcc * subject (already a runtime lookup)

It should be possible to configure the subject to be a system properties lookup like this:

subject = "$${sys:email.subject}"

Then you set system property email.subject to a different subject and send an email with a different subject. Can you try this?


Update 2:

If system properties are not suitable, you can also create a custom lookup , this is only a few lines of code.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM