/*
* $Id: SyslogHandler.html,v 1.2 2003/08/26 17:04:38 suhrin Exp $
*
* Copyright (c) 1999-2003 Gnome Ltd. All Rights Reserved.
*
* This software is the confidential and proprietary information of
* Gnome Ltd. You shall not disclose such Confidential
* Information and shall use it only in accordance with the terms
* of the license agreement you entered into with Gnome Ltd.
*/
package SK.gnome.dwarf.sample;
import java.net.*;
import SK.gnome.dwarf.log.*;
import SK.gnome.dwarf.tcpip.*;
/**
* Sample syslog handler.
*
* <p>This handler parses the received UDP packets in format used by the Unix syslog service
* and forwards them to its {@link #log(String, LogLevel, String)} method. Thus the remote log
* events are translated to the internal log events as if they were generated directly by the
* Dwarf-based application, and can be further processed in the standard way.
*
* The handler may be directly used to implement a syslog server, which will route the log
* events to the Dwarf-based loggers. In order to do it, it must be added to a {@link TCPIPServer}
* instance together with an {@link UDPListener} instance.
*/
public class SyslogHandler extends UDPHandler
{
// syslog-defined facilities
private static final String[] FACILITIES = {"kern", "user", "mail", "daemon", "auth", "syslog",
"lpr", "news", "uucp", "cron", "authpriv", "ftp",
"ntp", "security", "security", "cron", "local0",
"local1", "local2", "local3", "local4", "local5",
"local6", "local7", "unknown"};
private static int PRI_MASK = 0x0007;
private static int FAC_MASK = 0x03f8;
/**
* Creates a new <tt>SyslogHandler</tt>.
*/
public SyslogHandler(String name)
{ super(name);
}
/**
* Handles the UDP syslog packet.
*/
protected void handle(DatagramPacket packet)
{
// check the maximum packet length
int length = packet.getLength();
length = length > 1024 ? 1024 : length;
String msg = new String(packet.getData(), packet.getOffset(), length);
// parse the UDP packet
int priority = 13;
if (msg.charAt(0) == '<')
{ int index = msg.indexOf('>', 2);
if (index > 0)
{ priority = Integer.parseInt(msg.substring(1, index));
msg = msg.substring(index+1);
}
}
// adjust the facility to map the numerical value to String
int facility = (priority & FAC_MASK) >> 3;
if (facility >= FACILITIES.length)
facility = FACILITIES.length - 1;
// map the priority to a Dwarf logging level
int severity = priority & PRI_MASK;
LogLevel level;
switch (severity)
{ case 0: // Emergency
level = LOG_FATAL;
break;
case 1: // Alert
case 2: // Critical
case 3: // Error
level = LOG_ERROR;
break;
case 4: // Warning
level = LOG_WARN;
break;
case 5: // Notice
case 6: // Informational
level = LOG_INFO;
break;
case 7: // Debug
level = LOG_DEBUG;
break;
default:
level = LOG_INFO;
}
// forward the log message to the logging subsystem
log(FACILITIES[facility], level, msg.trim());
}
}
|