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