KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log > output > io > SafeFileTarget


1 /*
2  * Copyright 1999-2004 The Apache Software Foundation
3  * Licensed under the Apache License, Version 2.0 (the "License");
4  * you may not use this file except in compliance with the License.
5  * You may obtain a copy of the License at
6  *
7  * http://www.apache.org/licenses/LICENSE-2.0
8  *
9  * Unless required by applicable law or agreed to in writing, software
10  * distributed under the License is distributed on an "AS IS" BASIS,
11  * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
12  * implied.
13  *
14  * See the License for the specific language governing permissions and
15  * limitations under the License.
16  */

17 package org.apache.log.output.io;
18
19 import java.io.File JavaDoc;
20 import java.io.FileOutputStream JavaDoc;
21 import java.io.IOException JavaDoc;
22 import org.apache.log.LogEvent;
23 import org.apache.log.format.Formatter;
24
25 /**
26  * A target that will open and close a file for each logevent.
27  * This is slow but a more reliable form of logging on some
28  * filesystems/OSes. It should only be used when there is a
29  * small number of log events.
30  *
31  * @author Peter Donald
32  */

33 public class SafeFileTarget
34     extends FileTarget
35 {
36     /**
37      * Construct file target to write to a file with a formatter.
38      *
39      * @param file the file to write to
40      * @param append true if file is to be appended to, false otherwise
41      * @param formatter the Formatter
42      * @exception IOException if an error occurs
43      */

44     public SafeFileTarget( final File JavaDoc file, final boolean append, final Formatter formatter )
45         throws IOException JavaDoc
46     {
47         super( file, append, formatter );
48         shutdownStream();
49     }
50
51     /**
52      * Process a log event, via formatting and outputting it.
53      *
54      * @param event the log event
55      */

56     public synchronized void processEvent( final LogEvent event )
57     {
58         if( !isOpen() )
59         {
60             getErrorHandler().error( "Writing event to closed stream.", null, event );
61             return;
62         }
63
64         try
65         {
66             final FileOutputStream JavaDoc outputStream =
67                 new FileOutputStream JavaDoc( getFile().getPath(), true );
68             setOutputStream( outputStream );
69         }
70         catch( final Throwable JavaDoc throwable )
71         {
72             getErrorHandler().error( "Unable to open file to write log event.", throwable, event );
73             return;
74         }
75
76         //write out event
77
super.processEvent( event );
78
79         shutdownStream();
80     }
81 }
82
Popular Tags