logback udp appender

package com.macken;

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

import ch.qos.logback.classic.encoder.PatternLayoutEncoder;
import ch.qos.logback.classic.spi.ILoggingEvent;
import ch.qos.logback.core.AppenderBase;

public class UpdAppender extends AppenderBase<ILoggingEvent> {

	PatternLayoutEncoder encoder;
	int port;
	String ip;
	DatagramSocket socket;


	public PatternLayoutEncoder getEncoder() {
		return encoder;
	}
	public void setEncoder(PatternLayoutEncoder encoder) {
		this.encoder = encoder;
	}
	public int getPort() {
		return port;
	}
	public void setPort(int port) {
		this.port = port;
	}
	public String getIp() {
		return ip;
	}
	public void setIp(String ip) {
		this.ip = ip;
	}

	public DatagramSocket getSocket() {
		return socket;
	}
	public void setSocket(DatagramSocket socket) {
		this.socket = socket;
	}
	public UpdAppender() {
//		this.ip="10.11.199.154";
//		this.port=5070;
	}
	@Override
	public void start() {
		if (this.encoder == null) {
			addError("no layout of udp appender");
			return;
		}
		if (socket==null) {
			try {
				socket = new DatagramSocket(port);
			} catch (SocketException e) {
				e.printStackTrace();
			} 
		}
		super.start();
	}
	@Override
	protected void append(ILoggingEvent event) {
		byte[] buf = encoder.getLayout().doLayout(event).trim().getBytes();
		try {
			InetAddress address = InetAddress.getByName(ip);
			DatagramPacket p = new DatagramPacket(buf, buf.length, address, port);
			socket.send(p);
		} catch (Exception e) {
			e.printStackTrace();
		}

	}
	@Override
	public void stop() {
		if (!socket.isClosed()) {
			socket.close();
		}
		super.stop();
	}

}

 配置文件:

<configuration>
	<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
		</encoder>
	</appender>
	<appender name="upd" class="com.macken.UpdAppender">
		<encoder>
			<pattern>%d{HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern>
		</encoder>
		<ip>10.11.199.154</ip>
		<port>5070</port>
	</appender>
	<root level="debug">
		<!--  <appender-ref ref="STDOUT" />-->
		<appender-ref ref="upd" />
	</root>
</configuration>
 
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值