Question

In python, logging to syslog is fairly trivial:

syslog.openlog("ident")
syslog.syslog(0, "spilled beer on server")
syslog.closelog()

Is there an equivalently simple way in Java? After quite a bit of googling, I've been unable to find an easy to understand method that doesn't require reconfiguring rsyslogd or syslogd. If there's no equivalent, what is the simplest way to log to syslog?

Was it helpful?

Solution 2

One way to go direct to the log without udp is with syslog4j. I wouldn't necessarily say it's simple, but it doesn't require reconfiguring syslog, at least.

OTHER TIPS

The closest I can think of, would be using Log4J and configuring the SyslogAppender so it writes to syslog. Sorry, that's not as easy as in Python!

This is the simplest client code I could think of:

import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;

// java Syslog localhost "Hello world"
public class Syslog {
  public static void main(String[] args) throws Exception {
    InetAddress address = InetAddress.getByName(args[0]);
    byte[] bytes = args[1].getBytes();
    DatagramSocket socket = new DatagramSocket();
    try {
      DatagramPacket data = new DatagramPacket(bytes, bytes.length, address, 514);
      socket.send(data);
    } finally {
      socket.close();
    }
  }
}

And the server (syslogd):

import java.net.DatagramPacket;
import java.net.DatagramSocket;

// java SyslogD
public class SyslogD {
  public static void main(String[] args) throws Exception {
    DatagramSocket socket = new DatagramSocket(514);
    try {
      for(;;) {
        DatagramPacket data = new DatagramPacket(new byte[4096], 4096);
        socket.receive(data);
        System.out.println("[" + data.getAddress().toString() + "] " + new String(data.getData(),0,data.getLength()));
      }
    } finally {
      socket.close();
    }
  }
}
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top