1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23 package org.talika.tarsis.log;
24
25 import java.io.FileOutputStream;
26 import java.io.IOException;
27 import java.io.PrintStream;
28
29 import org.talika.tarsis.context.Context;
30 import org.talika.tarsis.service.ServiceException;
31
32 /**
33 * Implementation of <code>Logger</code> interface that writes messages to a given
34 * file.
35 *
36 * @author Jose M. Palomar
37 * @version $Revision: 124 $
38 */
39 public final class FileLogger extends LoggerService {
40
41
42
43
44 /**
45 * File print stream.
46 */
47 private PrintStream out;
48
49 /**
50 * Log file.
51 */
52 private String logFileName;
53
54
55 /**
56 * Creates a new <code>FileLogger</code>.
57 */
58 public FileLogger() {
59 }
60
61
62 /**
63 * Called by the framework to indicate that is being placed into service.<br>
64 * <br>
65 * Opens existing log file or creates a new one.
66 *
67 * @param context Context context that initialized service.
68 * @throws ServiceException if an exception has occurred that interferes with the
69 * services's normal operation
70 * @see org.talika.tarsis.service.Service#init(Context)
71 */
72 public void init(Context context) throws ServiceException {
73
74 if (out != null) {
75 return;
76 }
77
78 super.init(context);
79 try {
80 String fileName = context.getRealPath(logFileName);
81 this.out = new PrintStream(new FileOutputStream(fileName, true));
82 }
83 catch (IOException ioe) {
84 ioe.printStackTrace();
85
86 }
87
88 }
89
90 /**
91 * Called by the framework to indicate that is being placed out of service.<br>
92 * <br>
93 * Closes log file.
94 *
95 * @see org.talika.tarsis.service.Service#destroy()
96 */
97 public void destroy() {
98 if (out != null) {
99 out.close();
100 out = null;
101 }
102 super.destroy();
103 }
104
105 /**
106 * Returns name of service.
107 *
108 * @return String name of service.
109 * @see org.talika.tarsis.service.Service#getName()
110 */
111 public String getName() {
112 return "FileLoggerService";
113 }
114
115 /**
116 * Sets log file name parameter.
117 *
118 * @param logFileName String file name parameter.
119 */
120 public void setLogFileName(String logFileName) {
121 this.logFileName = logFileName;
122 }
123
124 /**
125 * Returns log file name parameter.
126 *
127 * @return String file name parameter.
128 */
129 public String getLogFileName() {
130 return logFileName;
131 }
132
133 /**
134 * Writes a log message to log file.
135 *
136 * @param level int log level.
137 * @param msg String message.
138 */
139 protected void writeLog(int level, String msg) {
140 if (out != null) {
141 out.print(msg);
142 }
143 }
144
145 /**
146 * Writes an error log message to log file.
147 *
148 * @param level int log level.
149 * @param msg String message.
150 * @param t Throwable a <code>Throwable</code> object.
151 */
152 protected void writeLog(int level, String msg, Throwable t) {
153 if (out != null) {
154 out.print(msg);
155 t.printStackTrace(out);
156 }
157 }
158
159 }