download RolloverFileLogSink.java
Language: Java
LOC: 230
Project Info
Jetty - Java HTTP Servlet Server(jetty)
Server: SourceForge
Type: cvs
...tyOld\src\com\mortbay\Base\
   Code.java
   CodeException.java
   DateCache.java
   FileLogSink.java
   Frame.java
   Log.java
   LogSink.java
   LogWriter.java
   RolloverFileLogSink.java
   Test.java
   TestHarness.java

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
// ===========================================================================
//	RolloverFileLogSink.java
// ===========================================================================

/*
** (c) Copyright V. Lipovetsky, 1998-2000
** www.fuib.com 
** E-mail: vit@fuib.com, lipov99@yahoo.com
** Modified for use with Jetty by Kent Johnson <KJohnson@transparent.com>
** Multiple log file modification by Jonathon Parker, jparker@transparent.com
*/

package com.mortbay.Base;


/* ------------------------------------------------------------ */
/** Rollover File Log Sink.
 * This implementation of Log Sink writes logs to a file. Files
 * are rolled over every day and old files are deleted.
 *
 * The default constructor looks for these System properties:
 * ROLLOVER_LOG_DIR	    The path to the directory containing the logs
 * ROLLOVER_LOG_RETAIN_DAYS The number of days to retain logs
 * ROLLOVER_LOG_EXTENSION   The file extension for log files
 * ROLLOVER_LOG_STOP_TIMEOUT How long to wait to kill the cleanup thread
 * ROLLOVER_LOG_TIMER_INTERVAL How long the cleanup thread sleeps
 * ROLLOVER_LOG_MULT_DAY If true, Jetty will keep multiple log files for same day,
 *                       if server is halted and restored.  Useful for debugging 
 *                       server crashes.
 *
 * @version 1.0 Tue May 23 2000
 * @author V. Lipovetsky
 * @author Kent Johnson
 */

public class RolloverFileLogSink 
    extends LogSink implements Runnable
{

    // ---------------------------------------------------------------------------
    //		RolloverFileLogSink
    // ---------------------------------------------------------------------------
    public RolloverFileLogSink()
	throws java.io.IOException
    {
    	String logDir = System.getProperty("ROLLOVER_LOG_DIR");
    	if (logDir != null)
	    setLogDir(logDir);
    		
    	Integer retain = Integer.getInteger("ROLLOVER_LOG_RETAIN_DAYS");
    	if (retain != null)
	    setRetainDays(retain.intValue());
    		
    	String extension = System.getProperty("ROLLOVER_LOG_EXTENSION");
    	if (extension != null)
	    setLogExt(extension);
    		
    	Integer stopTimeout = Integer.getInteger("ROLLOVER_LOG_STOP_TIMEOUT");
    	if (stopTimeout != null)
	    setThreadStopTimeout(stopTimeout.intValue());
    		
    	Integer timerInterval = Integer.getInteger("ROLLOVER_LOG_TIMER_INTERVAL");
    	if (timerInterval != null)
	    setTimerInterval(timerInterval.intValue());
    		
	start();
    }


    /* ------------------------------------------------------------ */
    /** Constructor. 
     * @param newLogDir 
     * @param newRetainDays 
     * @param newLogExt 
     * @param newThreadStopTimeout 
     * @param newTimerInterval 
     * @exception java.io.IOException 
     */
    public RolloverFileLogSink(String newLogDir,
			       int newRetainDays , 
			       String newLogExt,
			       long newThreadStopTimeout,
			       long newTimerInterval)
	throws java.io.IOException
    {
    	setLogDir(newLogDir);
    	setRetainDays(newRetainDays);
    	setLogExt(newLogExt);
	setTimerInterval(newTimerInterval);
	setThreadStopTimeout(newThreadStopTimeout);

	start();
    }
	
	
    // ---------------------------------------------------------------------------
    //		start
    // ---------------------------------------------------------------------------
    private void start()
	throws java.io.IOException
    {
	// Set new log file to name of current date
	setLogNameToDate(new java.util.Date());
	clearOldLogFiles(new java.util.Date());
	startClearThread();

      	setCreated(true);
    }//start
    
    
    // ---------------------------------------------------------------------------
    //		stop
    // ---------------------------------------------------------------------------
    public void stop()
    {
    	cleanup();
    }


    // ---------------------------------------------------------------------------
    //		setLogNameToDate
    // ---------------------------------------------------------------------------
    private synchronized void setLogNameToDate(java.util.Date curDate)
    	throws java.io.IOException
    {
	java.io.File newLogFile = 
	    new java.io.File(logDir, fileDateFormat.format(curDate) + logExt);

	//** If new name eq old do nothing
	if (newLogFile.equals(logFile)) return;
            
	// Make sure we start fresh if multDay option not set
	if (!multDay && newLogFile.exists()){
	    newLogFile.delete();
	}
	// Make additional files appended with _num2, _num3, etc.
	else{
	    int num = 1;
	    while (newLogFile.exists()){
		num++;
		newLogFile = new java.io.File(logDir, 
					      fileDateFormat.format(curDate) + "_num" + num + logExt);
	    }
	}
	logFile = newLogFile;

	//** Open new log file
	java.io.PrintWriter newLogWriter = new java.io.PrintWriter(
								   new java.io.FileWriter(logFile.getPath(), true), true);

	long now = System.currentTimeMillis();
	if (logWriter != null) {
	    synchronized (logWriter) {
				//** Close old log file
		logWriter.close();
		logWriter = newLogWriter;
					
		// This is what sets logWriter to get the log output
		super.setWriter(logWriter);
	    }
	}
	else {
	    logWriter = newLogWriter;
	    super.setWriter(logWriter);
	}
			
    }//setLogNameToDate


    // ---------------------------------------------------------------------------
    //		clearOldLogFiles
    // ---------------------------------------------------------------------------
    private synchronized void clearOldLogFiles(java.util.Date curDate)
    {
	String[] logFileList = logDir.list(
					   new java.io.FilenameFilter() {
						   public boolean accept(java.io.File dir, String n) {
						       return n.indexOf(logExt) != -1;
						   }//accept
					       }//FilenameFilter
					   );

	//** Compute Border date
	java.util.Calendar calendar = java.util.Calendar.getInstance();
	calendar.setTime(curDate);
	calendar.add(java.util.Calendar.DAY_OF_MONTH, -retainDays);

	int borderYear = calendar.get(java.util.Calendar.YEAR);
	int borderMonth = calendar.get(java.util.Calendar.MONTH) + 1;
	int borderDay = calendar.get(java.util.Calendar.DAY_OF_MONTH);
			
	for (int i = 0; i < logFileList.length; i++) {
	    java.io.File logFile = new java.io.File(logDir, logFileList[i]);
	    java.util.StringTokenizer st = 
		new java.util.StringTokenizer(logFile.getName(), "_.");
	    int nYear = Integer.parseInt(st.nextToken());
	    int nMonth = Integer.parseInt(st.nextToken());
	    int nDay = Integer.parseInt(st.nextToken());


	    if (nYear < borderYear ||
		(nYear == borderYear && nMonth < borderMonth) ||
		(nYear == borderYear && nMonth == borderMonth && nDay <= borderDay)) {
		logFile.delete();
	    }//if

	}//for
    }
    
    
    // ---------------------------------------------------------------------------
    //		startClearThread
    // ---------------------------------------------------------------------------
    private synchronized void startClearThread()
    {
	if (clearThread == null) {
	    clearThread = new Thread(this);
	    clearThread.setDaemon(true);
	    clearThread.start();
	}//if
    }


    // ---------------------------------------------------------------------------
    //		stopClearThread
    // ---------------------------------------------------------------------------
    private synchronized void stopClearThread(long timeout)
    {
	if (clearThread != null) {
				//** Send signal about exit from program
	    threadEvent.setOn(true);

				//** wait unitl thread is stopped
	    try {
		clearThread.join(timeout);
	    }
	    catch (java.lang.InterruptedException ignored) { Code.ignore(ignored); }
	    //** if timeout is out time let's interrupt thread
	    if (clearThread.isAlive()) {
        	clearThread.interrupt();
	    }//if
	    clearThread = null;
	}//if
    }


    // ---------------------------------------------------------------------------
    //		run
    // ---------------------------------------------------------------------------
    public void run( )
    {
	try {

	    while(true) {

		synchronized(threadEvent) {
		    threadEvent.wait(timerInterval);

		    if (threadEvent.isOn()) {
			break;
		    }//if

		}//synchronized

		//** Get current datetime and store in member variable
		java.util.Date curTime = new java.util.Date();
        	java.util.Calendar calendar = java.util.Calendar.getInstance();
		calendar.setTime(curTime);

		//logWriter.printTimestamp();
		//logWriter.println("thread in run !");

		if (calendar.get(java.util.Calendar.HOUR_OF_DAY) == 0 
		    && calendar.get(java.util.Calendar.MINUTE) == 0) {
		    setLogNameToDate(curTime);
		    clearOldLogFiles(curTime);
		}//if
	    }//while
	} catch(Exception e) {
				//System.out.println(e);
	    e.printStackTrace();
	}//try

    }//run


    /*
      public static void main(String[] args)
      {
      try {
      RolloverFileLogSink errLog = new RolloverFileLogSink();
      errLog.create(args[0], 2, ".LOG", 20*1000, 20*1000);
      errLog.logWriter.println("Hello, World !");
      } catch(Exception e) {
				//System.out.println(e);
				e.printStackTrace();
				}//try
				}//main
    */


    // ---------------------------------------------------------------------------
    //		cleanup
    // ---------------------------------------------------------------------------
    public synchronized void cleanup()
    {
	if (isCreated()) {
	    stopClearThread(threadStopTimeout);
	    logWriter.close();
	    setCreated(false);
	}//if
    }


    // ---------------------------------------------------------------------------
    private java.io.File logDir = new java.io.File("./");

    public void setLogDir(String newValue)
	throws java.io.IOException
    {
        logDir = new java.io.File(newValue);
        logDir.mkdirs();	// Make sure it exists
    }

    private String logExt = ".log";

    public String getLogExt() {
        return logExt;
    }

    public void setLogExt(String newValue) {
        logExt = newValue;
    }
    private int retainDays = 1;

    public int getRetainDays() {
        return retainDays;
    }

    public void setRetainDays(int newValue)
    {
        retainDays = newValue;
    }

    private long threadStopTimeout = 20*1000;

    public long getThreadStopTimeout() {
        return threadStopTimeout;
    }

    public void setThreadStopTimeout(long newValue) {
        threadStopTimeout = newValue;
    }
    
    private long timerInterval = 20*1000;

    public long getTimerInterval() {
        return timerInterval;
    }

    public void setTimerInterval(long newValue)
    {
        timerInterval = newValue;
    }
    /****************************************
     * data members
     ****************************************/

    public boolean isCreated()
    {
  	return created;
    }

    private void setCreated(boolean newValue)
    {
	created = newValue;
    }

    private boolean created = false;
    // add your data members here
    private java.io.PrintWriter logWriter;
    private java.io.File logFile;
    private Thread clearThread;
    private ThreadEvent threadEvent = new ThreadEvent();
    private java.text.SimpleDateFormat fileDateFormat = 
	new java.text.SimpleDateFormat("yyyy_MM_dd");
    private boolean multDay;


    // ---------------------------------------------------------------------------
    //		ThreadEvent
    // ---------------------------------------------------------------------------
    /** A helper class that is used to signal the cleanup thread to stop. */
    static final private class ThreadEvent 
    {
	private boolean on = false;

	public synchronized boolean isOn() {
	    return on;
	}

	public synchronized void setOn(boolean newValue) {
	    on = newValue;
	    if (on) this.notifyAll();
	}
    }
}

About Koders | Resources | Downloads | Support | Black Duck | Submit Project | Terms of Service | DMCA | Privacy Policy | Site Map| Contact Us