argon argon
argon argon

Reputation: 159

log4j: set different layout for same file

I need to have one single file for the log, but I want to specify two different layouts for this file. I read somewhere that declaring two appenders which write the same file is not advised, so how could do? Thanks in advance.

Upvotes: 3

Views: 469

Answers (1)

Ian Roberts
Ian Roberts

Reputation: 122364

This seems like a rather odd thing to do, as usually you would want all the lines in a single log file to be the same format, both for ease of eyeballing and if you want to do any automated processing of the log later on. But if you must then you are correct in saying that you shouldn't have two different appenders writing to the same file at the same time.

The solution would probably be to implement a custom Layout which can inspect the log event and then delegate to one of two (or more) other layouts to do the actual formatting

public class MultiLayout extends Layout {
  private Layout layout1;
  private Layout layout2;

  public MultiLayout() {
    layout1 = ....;
    layout1.activateOptions();
    layout2 = ....;
    layout2.activateOptions();
  }

  public boolean ignoresThrowable() {
    return layout1.ignoresThrowable();
  }

  public String format(LoggingEvent e) {
    // choose the appropriate layout, e.g. based on logger name
    if(e.getLoggerName().startsWith("com.example.")) {
      return layout1.format(e);
    } else {
      return layout2.format(e);
    }
  }

}

Upvotes: 5

Related Questions