1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21 package org.xnap.util;
22
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.PrintStream;
28 import java.util.Properties;
29
30 import org.apache.log4j.Level;
31 import org.apache.log4j.Logger;
32 import org.apache.log4j.PatternLayout;
33 import org.apache.log4j.PropertyConfigurator;
34 import org.apache.log4j.WriterAppender;
35
36 /***
37 * This class acts as a controller for the log4j logging framework.
38 */
39 public class Debug {
40
41
42
43
44
45 private static File errorFile;
46
47
48
49 /***
50 * Returns the file that is used to log all uncaught exceptions.
51 *
52 * @see #setErrorFile(File)
53 */
54 public static File getErrorFile()
55 {
56 return errorFile;
57 }
58
59 /***
60 * Returns the size of the error file. This might fail on some systems
61 * because the length of open files might always be 0.
62 *
63 * @return 0, if no error file was set; the length, otherwise
64 * @see #getErrorFile()
65 */
66 public static long getErrorFileSize()
67 {
68 return (errorFile != null) ? errorFile.length() : 0;
69 }
70
71 /***
72 * Initializes the debug environment. Should be called as early as
73 * possible.
74 */
75 public static void init(File prefsFile, Level level)
76 {
77 if (level != Level.OFF && prefsFile.canRead()) {
78 FileInputStream in = null;
79 try {
80 in = new FileInputStream(prefsFile);
81 Properties p = new Properties();
82 p.load(in);
83 PropertyConfigurator.configure(p);
84 }
85 catch (IOException e) {
86 System.err.println("Could not initialize logging");
87 e.printStackTrace(System.err);
88 }
89 finally {
90 try {
91 if (in != null) {
92 in.close();
93 }
94 }
95 catch (IOException e) {
96 }
97 }
98 }
99 else {
100
101
102
103
104 WriterAppender ca = new WriterAppender
105 (new PatternLayout("%-5p [%t] %m%n"), System.out);
106 ca.setName("Default");
107 Logger.getRootLogger().addAppender(ca);
108 Logger.getRootLogger().setLevel(level);
109 }
110 }
111
112 /***
113 * Sets the error file.
114 *
115 * @see #getErrorFile()
116 */
117 public static void setErrorFile(File f)
118 {
119 errorFile = f;
120
121 try {
122 System.setErr(new PrintStream(new FileOutputStream(f)));
123 }
124 catch (IOException e) {
125 }
126 }
127
128
129
130
131
132
133
134
135
136
137
138 }
139
140