KickJava   Java API By Example, From Geeks To Geeks.

Java > Open Source Codes > org > apache > log4j > helpers > SyslogWriter


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

16
17 package org.apache.log4j.helpers;
18
19
20 import java.io.Writer JavaDoc;
21 import java.net.DatagramSocket JavaDoc;
22 import java.net.InetAddress JavaDoc;
23 import java.net.DatagramPacket JavaDoc;
24 import java.net.UnknownHostException JavaDoc;
25 import java.net.SocketException JavaDoc;
26 import java.io.IOException JavaDoc;
27
28 /**
29    SyslogWriter is a wrapper around the java.net.DatagramSocket class
30    so that it behaves like a java.io.Writer.
31
32    @since 0.7.3
33 */

34 public class SyslogWriter extends Writer JavaDoc {
35
36   final int SYSLOG_PORT = 514;
37   static String JavaDoc syslogHost;
38   
39   private InetAddress JavaDoc address;
40   private DatagramSocket JavaDoc ds;
41
42   public
43   SyslogWriter(String JavaDoc syslogHost) {
44     this.syslogHost = syslogHost;
45
46     try {
47       this.address = InetAddress.getByName(syslogHost);
48     }
49     catch (UnknownHostException JavaDoc e) {
50       LogLog.error("Could not find " + syslogHost +
51              ". All logging will FAIL.", e);
52     }
53
54     try {
55       this.ds = new DatagramSocket JavaDoc();
56     }
57     catch (SocketException JavaDoc e) {
58       e.printStackTrace();
59       LogLog.error("Could not instantiate DatagramSocket to " + syslogHost +
60              ". All logging will FAIL.", e);
61     }
62   }
63
64
65   public
66   void write(char[] buf, int off, int len) throws IOException JavaDoc {
67     this.write(new String JavaDoc(buf, off, len));
68   }
69   
70   public
71   void write(String JavaDoc string) throws IOException JavaDoc {
72     byte[] bytes = string.getBytes();
73     DatagramPacket JavaDoc packet = new DatagramPacket JavaDoc(bytes, bytes.length,
74                            address, SYSLOG_PORT);
75
76     if(this.ds != null)
77       ds.send(packet);
78     
79   }
80
81   public
82   void flush() {}
83
84   public
85   void close() {}
86 }
87
Popular Tags