import java.net.SocketAddress;
import org.graylog2.syslog4j.SyslogConstants;
import org.graylog2.syslog4j.server.SyslogServer;
import org.graylog2.syslog4j.server.SyslogServerConfigIF;
import org.graylog2.syslog4j.server.SyslogServerEventIF;
import org.graylog2.syslog4j.server.SyslogServerIF;
import org.graylog2.syslog4j.server.SyslogServerSessionEventHandlerIF;
public class MySyslogServer {
private static final String HOST = "127.0.0.1";
private static final int PORT = 514;
private void receiveSyslogMessage() throws InterruptedException {
SyslogServerIF server = SyslogServer.getInstance(SyslogConstants.UDP);
SyslogServerConfigIF config = server.getConfig();
config.setHost(HOST);
config.setPort(PORT);
config.addEventHandler(new SyslogServerSessionEventHandlerIF() {
@Override
public Object sessionOpened(SyslogServerIF syslogServerIF, SocketAddress socketAddress) {
return null;
}
@Override
public void event(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress,
SyslogServerEventIF syslogServerEventIF) {
System.out.println("receive from:" + socketAddress + "\tmessage" + syslogServerEventIF.getMessage());
}
@Override
public void exception(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress, Exception e) {
}
@Override
public void sessionClosed(Object o, SyslogServerIF syslogServerIF, SocketAddress socketAddress, boolean b) {
}
@Override
public void initialize(SyslogServerIF syslogServerIF) {
}
@Override
public void destroy(SyslogServerIF syslogServerIF) {
}
});
SyslogServer.getThreadedInstance(SyslogConstants.UDP);
Thread.sleep(100000);
}
public static void main(String[] args) throws InterruptedException {
new MySyslogServer().receiveSyslogMessage();
}
}
import java.net.URLDecoder;
import java.util.Date;
import org.graylog2.syslog4j.Syslog;
import org.graylog2.syslog4j.SyslogIF;
public class MySyslogClient {
public static void main(String[] args) {
try {
// 获取syslog的操作类,使用udp协议。syslog支持"udp", "tcp", "unix_syslog", "unix_socket"协议
SyslogIF syslog = Syslog.getInstance("udp");
// 设置syslog服务器端地址
syslog.getConfig().setHost("127.0.0.1");
// 设置syslog接收端口,默认514
syslog.getConfig().setPort(514);
// 拼接syslog日志,这个日志是自己定义的,通常我们定义成符合公司规范的格式就行,方便查询。例如 操作时间:2014年8月1日 操作者ID:张三
// 等。信息就是一个字符串。
StringBuffer buffer = new StringBuffer();
buffer.append("操作时间:" + new Date().toString().substring(4, 20) + ";");
buffer.append("操作者ID:" + "张三" + ";");
buffer.append("操作时间:" + new Date() + ";");
buffer.append("日志类别:" + "22" + ";");
buffer.append("执行动作:" + "动作" + ";");
buffer.append("备注:" + "备注");
/*
* 发送信息到服务器,2表示日志级别 范围为0~7的数字编码,表示了事件的严重程度。0最高,7最低 syslog为每个事件赋予几个不同的优先级:
* LOG_EMERG:紧急情况,需要立即通知技术人员。 LOG_ALERT:应该被立即改正的问题,如系统数据库被破坏,ISP连接丢失。
* LOG_CRIT:重要情况,如硬盘错误,备用连接丢失。 LOG_ERR:错误,不是非常紧急,在一定时间内修复即可。
* LOG_WARNING:警告信息,不是错误,比如系统磁盘使用了85%等。 LOG_NOTICE:不是错误情况,也不需要立即处理。
* LOG_INFO:情报信息,正常的系统消息,比如骚扰报告,带宽数据等,不需要处理。
* LOG_DEBUG:包含详细的开发情报的信息,通常只在调试一个程序时使用。
*/
syslog.log(0, URLDecoder.decode(buffer.toString(), "utf-8"));
} catch (Exception e) {
}
}
}
import org.apache.logging.log4j.*;
public class TestLog4j {
private static final Logger logger = LogManager.getLogger(TestLog4j.class);
public static void main(String[] args) throws Exception {
logger.debug("Mydebug message");
logger.info("Myinfo message");
logger.warn("Mywarn message");
logger.error("Myerror message");
try {
int i = 1 / 0;
} catch (Exception exc) {
logger.error("error message with stack trace", new Exception("I forced this exception", exc));
}
logger.fatal("fatal message");
}
}
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="console" target="SYSTEM_OUT">
<PatternLayout pattern="TOCONSOLE %d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/>
</Console>
<!-- OPTION#1: Use standard syslog and add fields with LoggerFields -->
<Syslog name="syslog" format="RFC5424" host="127.0.0.1" port="514"
protocol="UDP" appName="testlog4j" includeMDC="false" mdcId="testlog4j"
facility="LOCAL0" enterpriseNumber="18060" newLine="false"
messageId="Audit">
<LoggerFields>
<KeyValuePair key="thread" value="%t"/>
<KeyValuePair key="priority" value="%p"/>
<KeyValuePair key="category" value="%c"/>
<KeyValuePair key="exception" value="%ex"/>
</LoggerFields>
</Syslog>
<!-- OPTION#2: Use socket with explicit pattern -->
<Socket name="syslogsocket" host="127.0.0.1" port="514" protocol="UDP">
<PatternLayout
pattern="<134>%d{MMM dd HH:mm:ss} ${hostName} testlog4j: {
"thread":"%t",
"priority":"%p",
"category":"%c{1}",
"exception":"%exception"
}%n"
/>
</Socket>
</Appenders>
<Loggers>
<Root level="warn">
<AppenderRef ref="console"/>
<AppenderRef ref="syslog"/>
</Root>
</Loggers>
</Configuration>
receive from:/127.0.0.1:54111 message2021-10-28T15:24:23.257+08:00 hostname testlog4j 15188 Audit [testlog4j@18060 category="TestLog4j" exception="" priority="WARN" thread="main"] Mywarn message
receive from:/127.0.0.1:54111 message2021-10-28T15:24:23.266+08:00 hostname testlog4j 15188 Audit [testlog4j@18060 category="TestLog4j" exception="" priority="ERROR" thread="main"] Myerror message
receive from:/127.0.0.1:54111 message2021-10-28T15:24:23.267+08:00 hostname testlog4j 15188 Audit [testlog4j@18060 category="TestLog4j" exception="java.lang.Exception: I forced this exception
at TestLog4j.main(TestLog4j.java:15)
Caused by: java.lang.ArithmeticException: / by zero
at TestLog4j.main(TestLog4j.java:13)
" priority="ERROR" thread="main"] error message with stack trace
receive from:/127.0.0.1:54111 message2021-10-28T15:24:23.301+08:00 hostname testlog4j 15188 Audit [testlog4j@18060 category="TestLog4j" exception="" priority="FATAL" thread="main"] fatal message