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.spi;
15  
16  import ch.qos.logback.core.Context;
17  import ch.qos.logback.core.status.ErrorStatus;
18  import ch.qos.logback.core.status.InfoStatus;
19  import ch.qos.logback.core.status.Status;
20  import ch.qos.logback.core.status.StatusManager;
21  import ch.qos.logback.core.status.WarnStatus;
22  
23  
24  /**
25   * A helper class that implements ContextAware methods. Use this class to
26   * implement the ContextAware interface by composition.
27   * 
28   * @author Ceki Gülcü
29   */
30  public class ContextAwareImpl implements ContextAware {
31  
32    private int noContextWarning = 0;
33    protected Context context;
34    final Object origin;
35    
36    public ContextAwareImpl(Object origin) {
37      this.origin = origin;
38    }
39    
40    protected Object getOrigin() {
41      return origin;
42    }
43    
44    public void setContext(Context context) {
45      if (this.context == null) {
46        this.context = context;
47      } else if (this.context != context) {
48        throw new IllegalStateException("Context has been already set");
49      }
50    }
51  
52    public Context getContext() {
53      return this.context;
54    }
55  
56    public StatusManager getStatusManager() {
57      if (context == null) {
58        return null;
59      }
60      return context.getStatusManager();
61    }
62  
63    public void addStatus(Status status) {
64      if (context == null) {
65        if (noContextWarning++ == 0) {
66          System.out.println("LOGBACK: No context given for " + this);
67        }
68        return;
69      }
70      StatusManager sm = context.getStatusManager();
71      if (sm != null) {
72        sm.add(status);
73      }
74    }
75  
76    public void addInfo(String msg) {
77      addStatus(new InfoStatus(msg, getOrigin()));
78    }
79  
80    public void addInfo(String msg, Throwable ex) {
81      addStatus(new InfoStatus(msg, getOrigin(), ex));
82    }
83  
84    public void addWarn(String msg) {
85      addStatus(new WarnStatus(msg, getOrigin()));
86    }
87  
88    public void addWarn(String msg, Throwable ex) {
89      addStatus(new WarnStatus(msg, getOrigin(), ex));
90    }
91  
92    public void addError(String msg) {
93      addStatus(new ErrorStatus(msg, getOrigin()));
94    }
95  
96    public void addError(String msg, Throwable ex) {
97      addStatus(new ErrorStatus(msg, getOrigin(), ex));
98    }
99  
100 }