View Javadoc

1   /*
2    * GridUser.java
3    *
4    * Created on August 20, 2008, 4:00 PM
5    */
6   
7   package gov.bnl.gums.util;
8   
9   import java.util.Collections;
10  import java.util.Iterator;
11  import java.util.SortedMap;
12  import java.util.TreeMap;
13  
14  import org.apache.log4j.Logger;
15  
16  /** 
17   * Represent a Logger than only logs the first time (optional) a certain message
18   * is passed to it or when warn is invoked, which can be done at an appropriate
19   * interval of time.  This is particularly useful for limiting number of emails
20   * when log4j is set up to email logs.
21   *
22   * @author  Gabriele Carcassi, Jay Packard
23   */
24  public class QuietLog {
25  	Logger log;
26  	SortedMap<String, String> messages = Collections.synchronizedSortedMap(new TreeMap<String, String>());
27  	
28  	public QuietLog(String logName) {
29  		log = Logger.getLogger(logName);
30  	}
31  	
32  	public void logMessages() {
33  		log.warn(createMessage());
34  		messages.clear();
35  	}
36  	
37  	/*
38  	 * If this is the first type of this error, log it immediately,
39  	 * otherwise just add it to messages to be logged later
40  	 */
41  	public void put(String key, String message, boolean logImmediately) {
42  		if (!messages.containsKey(key) && logImmediately)
43  			log.error(message);
44  		messages.put(key, message);
45  	}
46  	
47  	public boolean hasMessages() {
48  		return messages.size()>0;
49  	}
50  	
51  	private String createMessage() {
52  		synchronized(messages) {
53  			Iterator<String> it = messages.values().iterator();
54  			StringBuffer buffer = new StringBuffer();
55  			while (it.hasNext()) {
56  				buffer.append((String)it.next());
57  				buffer.append("\n");
58  			}
59  			return buffer.toString();
60  		}
61  	}
62  }