View Javadoc

1   /**
2    * Logback: the reliable, generic, fast and flexible logging framework.
3    * Copyright (C) 1999-2011, QOS.ch. All rights reserved.
4    *
5    * This program and the accompanying materials are dual-licensed under
6    * either the terms of the Eclipse Public License v1.0 as published by
7    * the Eclipse Foundation
8    *
9    *   or (per the licensee's choosing)
10   *
11   * under the terms of the GNU Lesser General Public License version 2.1
12   * as published by the Free Software Foundation.
13   */
14  package ch.qos.logback.core.pattern;
15  
16  abstract public class FormattingConverter<E> extends Converter<E> {
17  
18    static final int INITIAL_BUF_SIZE = 256;
19    static final int MAX_CAPACITY = 1024;
20  
21    
22    FormatInfo formattingInfo;
23  
24    final public FormatInfo getFormattingInfo() {
25      return formattingInfo;
26    }
27  
28    final public void setFormattingInfo(FormatInfo formattingInfo) {
29      if (this.formattingInfo != null) {
30        throw new IllegalStateException("FormattingInfo has been already set");
31      }
32      this.formattingInfo = formattingInfo;
33    }
34  
35    @Override
36    final public void write(StringBuilder buf, E event) {
37      String s = convert(event);
38      
39      if(formattingInfo == null) {
40        buf.append(s);
41        return;
42      }
43      
44      int min = formattingInfo.getMin();
45      int max = formattingInfo.getMax();
46  
47  
48      if (s == null) {
49        if (0 < min)
50          SpacePadder.spacePad(buf, min);
51        return;
52      }
53  
54      int len = s.length();
55  
56      if (len > max) {
57        if(formattingInfo.isLeftTruncate()) {
58          buf.append(s.substring(len - max));
59        } else {
60          buf.append(s.substring(0, max));
61        }
62      } else if (len < min) {
63        if (formattingInfo.isLeftPad()) {
64         SpacePadder.leftPad(buf, s, min);
65        } else {
66          SpacePadder.rightPad(buf, s, min);
67        }
68      } else {
69        buf.append(s);
70      }
71    }
72  }