View Javadoc

1   /**
2    * Logback: the generic, reliable, fast and flexible logging framework.
3    * 
4    * Copyright (C) 2000-2009, QOS.ch
5    * 
6    * This library is free software, you can redistribute it and/or modify it under
7    * the terms of the GNU Lesser General Public License as published by the Free
8    * Software Foundation.
9    */
10  package ch.qos.logback.core;
11  
12  import ch.qos.logback.core.status.Status;
13  import ch.qos.logback.core.status.WarnStatus;
14  
15  
16  /**
17   * ConsoleAppender appends log events to <code>System.out</code> or
18   * <code>System.err</code> using a layout specified by the user. The default
19   * target is <code>System.out</code>.
20   *
21   * For more information about this appender, please refer to the online manual at
22   * http://logback.qos.ch/manual/appenders.html#ConsoleAppender
23   *
24   * @author Ceki G&uuml;lc&uuml;
25   */
26  
27  public class ConsoleAppender<E> extends WriterAppender<E> {
28  
29      public static final String SYSTEM_OUT = "System.out";
30      public static final String SYSTEM_ERR = "System.err";
31      protected String target = SYSTEM_OUT;
32  
33      /**
34       * As in most logback components, the default constructor does nothing.
35       */
36      public ConsoleAppender() {
37      }
38  
39      /**
40       * Sets the value of the <b>Target</b> option. Recognized values are
41       * "System.out" and "System.err". Any other value will be ignored.
42       */
43      public void setTarget(String value) {
44        String v = value.trim();
45  
46        if (SYSTEM_OUT.equalsIgnoreCase(v)) {
47          target = SYSTEM_OUT;
48        } else if (SYSTEM_ERR.equalsIgnoreCase(v)) {
49          target = SYSTEM_ERR;
50        } else {
51          targetWarn(value);
52        }
53      }
54  
55      /**
56       * Returns the current value of the <b>Target</b> property. The default
57       * value of the option is "System.out".
58       * 
59       * See also {@link #setTarget}.
60       */
61      public String getTarget() {
62        return target;
63      }
64  
65      void targetWarn(String val) {
66        Status status = new WarnStatus("["+val+" should be System.out or System.err.", this);
67        status.add(new WarnStatus("Using previously set target, System.out by default.", this));
68        addStatus(status);
69      }
70  
71      public void start() {
72        if (target.equals(SYSTEM_OUT)) {
73          setWriter(createWriter(System.out));
74        } else {
75          setWriter(createWriter(System.err));
76        }
77        super.start();
78      }
79  
80      /**
81       * This method overrides the parent {@link WriterAppender#closeWriter}
82       * implementation  because the console stream is not ours to close.
83       */
84      protected final void closeWriter() {
85        writeFooter();
86      }
87    }
88  
89