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


    1.设置环境变量

    Java代码 
    /设置系统环境变量  
    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配置获取环境变量

    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过滤掉还回和虚拟网卡地址

    Java代码 
        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

  • 相关阅读:
    [No0000161]IDEA初步接触
    [No0000171]wpf 类层次结构Class Hierarchy
    [No0000160]常用C# 正则表达式大全
    [No000015D]【李笑来 笔记整理】个人商业模式升级
    thinkphp 系统变量
    thinkphp不读取.env文件的键对值
    thinkphp 模板变量输出替换和赋值
    thinkphp 视图view
    thinkphp 响应对象response
    Thinkphp 请求和响应
  • 原文地址:https://www.cnblogs.com/interdrp/p/15596717.html
Copyright © 2020-2023  润新知