View Javadoc

1   package com.atlassian.logging.log4j;
2   
3   import org.apache.log4j.helpers.FormattingInfo;
4   import org.apache.log4j.helpers.PatternConverter;
5   import org.apache.log4j.spi.LoggingEvent;
6   
7   /**
8    * PatternParser that will suffix newline characters with a custom separator (default four spaces ). This is
9    * to better highlight that log messages are being injected when logging user entered information.
10   *
11   * @since v1.2
12   */
13  public class NewLineLogMessagePatternParser extends CategoryCollapsingPatternParser
14  {
15      // Line ending combos include UNIX and MAC = \n, WINDOWS = \r\n, MAC pre OSX = \r the next major OS will need to choose \n\r
16      private String lineIndent;
17  
18      public NewLineLogMessagePatternParser(final String pattern, final String lineIndent, final int fqNameCollapsePrecision)
19      {
20          super(pattern, fqNameCollapsePrecision);
21          this.lineIndent = lineIndent;
22      }
23  
24      @Override
25      protected void finalizeConverter(final char c)
26      {
27          switch(c)
28          {
29              // m is the character the log4j 1.2 uses to represent the log message passed along with
30              // with the logging event
31              case 'm':
32                  addConverter(new LineEndingStrippingPatternConverter(formattingInfo, lineIndent));
33                  break;
34              default:
35                  super.finalizeConverter(c);
36                  break;
37          }
38      }
39  
40      /**
41       * Append an indent to \r, \n, \r\n combination whilst preserving the original character
42       */
43      protected static class LineEndingStrippingPatternConverter extends PatternConverter
44      {
45          private final String lineIndent;
46  
47          LineEndingStrippingPatternConverter(final FormattingInfo info, final String lineIndent)
48          {
49              super(info);
50              this.lineIndent = lineIndent;
51          }
52  
53          @Override
54          public String convert(LoggingEvent event)
55          {
56              return LogMessageUtil.appendLineIndent(event.getRenderedMessage(), lineIndent);
57          }
58      }
59  }