log4j2输出带有ip日志,便于集群环境查找

1.设置环境变量

  

//设置系统环境变量
System.setProperty("local-ip", "10.99.1.51");
//获取系统环境变量
System.out.println(System.getProperty("local-ip"));

try {
//设置本机地址到环境变量
	System.setProperty("local-ip", LocalIP.getIpAddress().getHostAddress());
} catch (SocketException e) {
	e.printStackTrace();
}

 2.log4j2.xml配置获取环境变量

   

<Property name="logFormat">
    [${sys:local-ip}] [%thread] %-5level %logger{35} - %msg %n
</Property>
<Property name="log-local-ip">
    ${sys:local-ip}
</Property>

 3.java获取本地ip过滤掉还回和虚拟网卡地址

   

import java.net.InetAddress;
import java.net.NetworkInterface;
import java.net.SocketException;
import java.util.Enumeration;

public class LocalIP {

	public static void main(String[] args) throws SocketException {
		System.out.println(getIpAddress().getHostAddress());

	}

	public static InetAddress getIpAddress() throws SocketException {
		Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
		while (interfaces.hasMoreElements()) {
			NetworkInterface current = interfaces.nextElement();
			if (!current.isUp() || current.isLoopback() || current.isVirtual())
				continue;
			Enumeration<InetAddress> addresses = current.getInetAddresses();
			while (addresses.hasMoreElements()) {
				InetAddress addr = addresses.nextElement();
				if (addr.isLoopbackAddress())
					continue;
				if (addr.isSiteLocalAddress()) {//去掉还回和虚拟地址
					return addr;
				}
//				System.out.println(addr.isSiteLocalAddress());
//				System.out.println(addr);
			}
		}

		throw new SocketException("Can't get our ip address, interfaces are: " + interfaces);
	}

}

 

 

 

11

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值