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.status;
15  
16  import ch.qos.logback.core.spi.ContextAwareBase;
17  import ch.qos.logback.core.spi.LifeCycle;
18  import ch.qos.logback.core.util.StatusPrinter;
19  
20  import java.util.List;
21  
22  /**
23   * Print all new incoming status messages on the console.
24   *
25   * @author Ceki Gülcü
26   */
27  public class OnConsoleStatusListener extends ContextAwareBase implements StatusListener, LifeCycle {
28  
29  
30    static final long DEFAULT_RESTROSPECTIVE = 300;
31    boolean isStarted = false;
32    long retrospective = DEFAULT_RESTROSPECTIVE;
33  
34    private void print(Status status) {
35      StringBuilder sb = new StringBuilder();
36      StatusPrinter.buildStr(sb, "", status);
37      System.out.print(sb);
38    }
39  
40    public void addStatusEvent(Status status) {
41      if (!isStarted)
42        return;
43      print(status);
44    }
45  
46    /**
47     * Print status messages retrospectively
48     */
49    private void retrospectivePrint() {
50      long now = System.currentTimeMillis();
51      StatusManager sm = context.getStatusManager();
52      List<Status> statusList = sm.getCopyOfStatusList();
53      for (Status status : statusList) {
54        long timestamp = status.getDate();
55        if (now - timestamp < retrospective) {
56          print(status);
57        }
58      }
59    }
60  
61    public void start() {
62      isStarted = true;
63      if (retrospective > 0) {
64        retrospectivePrint();
65      }
66    }
67  
68    public void setRetrospective(long retrospective) {
69      this.retrospective = retrospective;
70    }
71  
72    public long getRetrospective() {
73      return retrospective;
74    }
75  
76    public void stop() {
77      isStarted = false;
78    }
79  
80    public boolean isStarted() {
81      return isStarted;
82    }
83  }