001/** 002 * Logback: the reliable, generic, fast and flexible logging framework. 003 * Copyright (C) 1999-2015, QOS.ch. All rights reserved. 004 * 005 * This program and the accompanying materials are dual-licensed under 006 * either the terms of the Eclipse Public License v1.0 as published by 007 * the Eclipse Foundation 008 * 009 * or (per the licensee's choosing) 010 * 011 * under the terms of the GNU Lesser General Public License version 2.1 012 * as published by the Free Software Foundation. 013 */ 014package ch.qos.logback.core.spi; 015 016import ch.qos.logback.core.Context; 017import ch.qos.logback.core.status.ErrorStatus; 018import ch.qos.logback.core.status.InfoStatus; 019import ch.qos.logback.core.status.Status; 020import ch.qos.logback.core.status.StatusManager; 021import ch.qos.logback.core.status.WarnStatus; 022 023/** 024 * A helper class that implements ContextAware methods. Use this class to 025 * implement the ContextAware interface by composition. 026 * 027 * @author Ceki Gülcü 028 */ 029public class ContextAwareImpl implements ContextAware { 030 031 private int noContextWarning = 0; 032 protected Context context; 033 final Object origin; 034 035 public ContextAwareImpl(Context context, Object origin) { 036 this.context = context; 037 this.origin = origin; 038 039 } 040 041 protected Object getOrigin() { 042 return origin; 043 } 044 045 public void setContext(Context context) { 046 if (this.context == null) { 047 this.context = context; 048 } else if (this.context != context) { 049 throw new IllegalStateException("Context has been already set"); 050 } 051 } 052 053 public Context getContext() { 054 return this.context; 055 } 056 057 public StatusManager getStatusManager() { 058 if (context == null) { 059 return null; 060 } 061 return context.getStatusManager(); 062 } 063 064 public void addStatus(Status status) { 065 if (context == null) { 066 if (noContextWarning++ == 0) { 067 System.out.println("LOGBACK: No context given for " + this); 068 } 069 return; 070 } 071 StatusManager sm = context.getStatusManager(); 072 if (sm != null) { 073 sm.add(status); 074 } 075 } 076 077 public void addInfo(String msg) { 078 addStatus(new InfoStatus(msg, getOrigin())); 079 } 080 081 public void addInfo(String msg, Throwable ex) { 082 addStatus(new InfoStatus(msg, getOrigin(), ex)); 083 } 084 085 public void addWarn(String msg) { 086 addStatus(new WarnStatus(msg, getOrigin())); 087 } 088 089 public void addWarn(String msg, Throwable ex) { 090 addStatus(new WarnStatus(msg, getOrigin(), ex)); 091 } 092 093 public void addError(String msg) { 094 addStatus(new ErrorStatus(msg, getOrigin())); 095 } 096 097 public void addError(String msg, Throwable ex) { 098 addStatus(new ErrorStatus(msg, getOrigin(), ex)); 099 } 100 101}