KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > com > tonbeller > wcf > log > LogHandler


1 /*
2  * ====================================================================
3  * This software is subject to the terms of the Common Public License
4  * Agreement, available at the following URL:
5  * http://www.opensource.org/licenses/cpl.html .
6  * Copyright (C) 2003-2004 TONBELLER AG.
7  * All Rights Reserved.
8  * You must accept the terms of that agreement to use this software.
9  * ====================================================================
10  *
11  *
12  */

13 package com.tonbeller.wcf.log;
14
15 import java.io.File JavaDoc;
16 import java.io.FileInputStream JavaDoc;
17 import java.io.FileOutputStream JavaDoc;
18 import java.io.FilenameFilter JavaDoc;
19 import java.io.IOException JavaDoc;
20 import java.io.InputStream JavaDoc;
21 import java.net.URL JavaDoc;
22 import java.util.Iterator JavaDoc;
23 import java.util.Locale JavaDoc;
24 import java.util.Map JavaDoc;
25 import java.util.Properties JavaDoc;
26 import java.util.TreeMap JavaDoc;
27
28 import org.apache.log4j.LogManager;
29 import org.apache.log4j.Logger;
30 import org.apache.log4j.PropertyConfigurator;
31
32 import com.tonbeller.tbutils.res.Resources;
33
34 public class LogHandler {
35
36   private static Logger logger = Logger.getLogger(LogHandler.class);
37
38   public static final String JavaDoc DEFAULT = "default";
39   public static final String JavaDoc NOLOG = "nolog";
40   public static final String JavaDoc DEBUG_FILE = "debug-file";
41   public static final String JavaDoc DEBUG_STDOUT = "debug-stdout";
42   public static final String JavaDoc ERROR_FILE = "error-file";
43   public static final String JavaDoc ERROR_STDOUT = "error-stdout";
44
45   private Map JavaDoc configs = new TreeMap JavaDoc();
46   private Map JavaDoc labels = new TreeMap JavaDoc();
47   private String JavaDoc context;
48   private File JavaDoc logFile;
49   private File JavaDoc logDir;
50
51   public LogHandler(String JavaDoc logDirName, Locale JavaDoc locale, String JavaDoc context) throws IOException JavaDoc {
52     this.context = context;
53     this.logDir = initLogDir(logDirName);
54     this.logFile = new File JavaDoc(logDir, context + ".log");
55
56     createDefConfigs();
57     addConfigs();
58
59   }
60
61   private void createDefConfigs() throws IOException JavaDoc {
62     createDefConfig(DEBUG_FILE);
63     createDefConfig(DEBUG_STDOUT);
64     createDefConfig(ERROR_FILE);
65     createDefConfig(ERROR_STDOUT);
66     createDefConfig(NOLOG);
67   }
68
69   private void createDefConfig(String JavaDoc name) throws IOException JavaDoc {
70     String JavaDoc resName = "/com/tonbeller/wcf/log/" + name + ".properties";
71
72     File JavaDoc file = new File JavaDoc(logDir, name + ".properties");
73     if (!file.exists())
74       copyRes(resName, file);
75   }
76
77   private void addConfigs() {
78     File JavaDoc files[] = logDir.listFiles(new FilenameFilter JavaDoc() {
79       public boolean accept(File JavaDoc f, String JavaDoc name) {
80         return name.endsWith(".properties");
81       }
82     });
83
84     for (int i = 0; i < files.length; i++) {
85       String JavaDoc fname = files[i].getName();
86       String JavaDoc name = fname.substring(0, fname.lastIndexOf(".properties"));
87
88       configs.put(name, files[i]);
89     }
90   }
91
92   /**
93    * adds a log4j configuration to the list of predefined configs
94    * @param resourceName name of the resource, ".properties" will be appended.
95    * Example: "/my/package/log4jdebug"
96    * @param label will be presented to the user
97    */

98   public void addConfig(String JavaDoc resourceName, String JavaDoc label) throws IOException JavaDoc {
99     // copy file if not already there
100
String JavaDoc name = resourceName;
101     int pos = name.lastIndexOf('/');
102     if (pos >= 0)
103       name = name.substring(pos + 1);
104     File JavaDoc file = new File JavaDoc(logDir, name + ".properties");
105     if (!file.exists())
106       copyRes(resourceName + ".properties", file);
107     
108     // add to config
109
configs.put(name, file);
110     labels.put(name, label);
111   }
112
113   /**
114    * Legt das Logging Verzeichnis im User.Home oder im Temp-Verzeichnis an.
115    * Unter Unix darf der Dummy-User im User.Home Verzeichnis (Tomcat) keine
116    * Verzeichnisse anlegen
117    */

118   private File JavaDoc initLogDir(String JavaDoc dir) {
119     File JavaDoc baseDir = Resources.instance().getHomeDir();
120     File JavaDoc dirObj = logDir(dir, baseDir);
121     if (dirObj == null)
122       dirObj = logDir(dir, new File JavaDoc("java.io.tmpdir"));
123     if (dirObj == null)
124       throw new IllegalArgumentException JavaDoc("Not available: " + dirObj);
125     return dirObj;
126   }
127
128   private File JavaDoc logDir(String JavaDoc dir, File JavaDoc baseDir) {
129     File JavaDoc dirObj = new File JavaDoc(dir);
130     if (!dirObj.isAbsolute())
131       dirObj = new File JavaDoc(baseDir, dir);
132
133     if (dirObj.exists()) {
134       if (!dirObj.isDirectory())
135         return null;
136       return dirObj;
137     }
138
139     // Log Directory erzeugen
140
if (dirObj.mkdirs())
141       return dirObj;
142     return null;
143   }
144
145   private void copyRes(String JavaDoc resName, File JavaDoc file) throws IOException JavaDoc {
146     InputStream JavaDoc is = null;
147     try {
148       is = getClass().getResourceAsStream(resName);
149       if (is == null)
150         throw new IllegalArgumentException JavaDoc("Resource " + resName + " not found");
151       FileOutputStream JavaDoc os = null;
152       try {
153         os = new FileOutputStream JavaDoc(file);
154         byte[] buf = new byte[1024];
155         int len;
156         while ((len = is.read(buf)) > 0)
157           os.write(buf, 0, len);
158       } finally {
159         if (os != null)
160           os.close();
161       }
162     } finally {
163       if (is != null)
164         is.close();
165     }
166   }
167
168   public String JavaDoc[] getConfigNames() {
169     String JavaDoc[] names = new String JavaDoc[configs.keySet().size() + 1];
170     names[0] = DEFAULT;
171
172     Iterator JavaDoc it = configs.keySet().iterator();
173     int idx = 1;
174     while (it.hasNext())
175       names[idx++] = (String JavaDoc) it.next();
176
177     return names;
178   }
179   
180   /**
181    * returns null or the label of the config name
182    * @param configName
183    * @return
184    */

185   public String JavaDoc getLabel(String JavaDoc configName) {
186     return (String JavaDoc)labels.get(configName);
187   }
188
189   public void applyConfig(String JavaDoc name) throws IOException JavaDoc {
190
191     Properties JavaDoc logProps;
192
193     if (DEFAULT.equals(name))
194       logProps = loadDefaultConfig();
195     else
196       logProps = loadConfig(name);
197
198     LogManager.resetConfiguration();
199     PropertyConfigurator.configure(logProps);
200
201     System.out.println("--- Applied new logging configuration ---");
202     logger.error("Test error message");
203     logger.debug("Test debug message");
204   }
205
206   /**
207    * Method loadDefaultConfig.
208    * @return Properties
209    */

210   private Properties JavaDoc loadDefaultConfig() throws IOException JavaDoc {
211     return loadProperties(getClass().getResource("/log4j.properties"));
212   }
213
214   private Properties JavaDoc loadConfig(String JavaDoc name) throws IOException JavaDoc {
215     Properties JavaDoc logProps;
216     File JavaDoc file = (File JavaDoc) configs.get(name);
217     if (file == null)
218       throw new IllegalArgumentException JavaDoc("Log configuration " + name + " not found");
219
220     // try to apply the configuration
221
logProps = loadProperties(file);
222
223     if (logProps.get("context") == null)
224       logProps.put("context", context);
225     if (logProps.get("logfile") == null)
226       logProps.put("logfile", logFile.getAbsolutePath());
227     return logProps;
228   }
229
230   private Properties JavaDoc loadProperties(File JavaDoc file) throws IOException JavaDoc {
231     Properties JavaDoc props = new Properties JavaDoc();
232
233     FileInputStream JavaDoc in = null;
234     try {
235       in = new FileInputStream JavaDoc(file);
236       props.load(in);
237
238       return props;
239     } finally {
240       if (in != null)
241         in.close();
242     }
243   }
244
245   private Properties JavaDoc loadProperties(URL JavaDoc url) throws IOException JavaDoc {
246     Properties JavaDoc props = new Properties JavaDoc();
247
248     InputStream JavaDoc in = null;
249     try {
250       in = url.openStream();
251       props.load(in);
252
253       return props;
254     } finally {
255       if (in != null)
256         in.close();
257     }
258   }
259
260   public String JavaDoc version() {
261     Package JavaDoc p = LogManager.class.getPackage();
262     StringBuffer JavaDoc version = new StringBuffer JavaDoc();
263     version.append(p.getImplementationVendor());
264     version.append(' ');
265     version.append(p.getImplementationTitle());
266     version.append(' ');
267     version.append(p.getImplementationVersion());
268
269     return version.toString();
270   }
271
272   /**
273    * Returns the logFile.
274    * @return File
275    */

276   public File JavaDoc getLogFile() {
277     return logFile;
278   }
279
280   /**
281    * Sets the logFile.
282    * @param logFile The logFile to set
283    */

284   public void setLogFile(File JavaDoc logFile) {
285     this.logFile = logFile;
286   }
287
288   /**
289    * Method getDefault.
290    * @return String
291    */

292   public static String JavaDoc getDefault() {
293     return DEFAULT;
294   }
295
296   /**
297    * which level is set for the root logger. May be empty
298    */

299   public String JavaDoc getRootLoggerLevel() {
300     Logger logger = Logger.getRootLogger();
301
302     if (logger.getLevel() != null)
303       return logger.getLevel().toString();
304     return "";
305   }
306 }
307
Popular Tags