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 chapters.migrationFromLog4j;
15  
16  import java.io.IOException;
17  
18  import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
19  import ch.qos.logback.classic.spi.ILoggingEvent;
20  import ch.qos.logback.core.AppenderBase;
21  
22  public class TrivialLogbackAppender extends AppenderBase<ILoggingEvent> {
23  
24    PatternLayoutEncoder encoder;
25    
26    public PatternLayoutEncoder getEncoder() {
27      return encoder;
28    }
29  
30    public void setEncoder(PatternLayoutEncoder encoder) {
31      this.encoder = encoder;
32    }
33  
34    @Override
35    public void start() {
36      if (this.encoder == null) {
37        addError("No encoder set for the appender named [" + name + "].");
38        return;
39      }
40      try {
41        encoder.init(System.out);
42      } catch (IOException e) {
43      }
44      super.start();
45    }
46  
47    @Override
48    protected void append(ILoggingEvent loggingevent) {
49      // note that AppenderBase.doAppend will invoke this method only if
50      // this appender was successfully started.
51      try {
52        this.encoder.doEncode(loggingevent);
53      } catch (IOException e) {
54        // we can't do much with the exception except halting
55        super.stop();
56        addError("Failed to write to the console");
57      }
58    }
59  
60  }