当使用log4j2 TcpSocketServer和SocketAppender时,是否可以记录远程(客户端)IP地址?

lp0sw83n  于 2022-11-06  发布在  其他
关注(0)|答案(1)|浏览(123)

我一直在寻找如何在log4j2 TcpSocketServer服务器端日志文件中打印远程客户端的ip地址的例子,我希望我没有找到正确的方法。是否可以打印远程客户端的ip地址,如果可以,如何打印?
如果我使用TcpSocketServer,我可以在服务器启动时获得以下信息:

2017-04-10 11:30:31,316 [Log4j2-0] DEBUG [TcpSocketServer.java:231] Socket accepted: Socket[addr=/10.64.1.2,port=52412,localport=4560]

我想要的是IP地址以某种方式包含在每个日志行中:

2017-04-10 11:30:31,316 [Log4j2-0] [10.64.1.2] DEBUG [MyFile.java:17] Test Logging line
bmvo0sr5

bmvo0sr51#

以下是使用筛选器的工作示例:

import java.io.IOException;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;

import org.apache.logging.log4j.ThreadContext;

/**
 * Servlet Filter implementation class UserIPFilter
 */
@WebFilter(filterName="UserIPFilter")
public class UserIPFilter implements Filter {

    private final String IP_ADDRESS = "ipAddress";

    public void destroy() {
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {

        boolean successfulRegistration = false;

        HttpServletRequest req = (HttpServletRequest) request;  

        if (req.getRemoteHost() != null) {
            String ipAddress = req.getRemoteHost();
            System.out.println("IP: " + ipAddress);
            successfulRegistration = registerUsername(ipAddress);
        }

        try {
            chain.doFilter(request, response);
        } finally {
            if (successfulRegistration) {
                ThreadContext.clearMap();
            }
        }
    }

    public void init(FilterConfig arg0) throws ServletException {
    }

    /**
     * Register the user in the ThreadContext under IP_ADDRESS.
     * 
     * @param username
     * @return true ipAddress can be successfully registered
     */
    private boolean registerUsername(String ipAddress) {
        if (ipAddress != null && ipAddress.trim().length() > 0) {
            ThreadContext.put(IP_ADDRESS, ipAddress);
            return true;
        }
        return false;
    }

}

web.xml

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE xml>
----
----
<filter-mapping>
        <filter-name>UserIPFilter</filter-name>
        <url-pattern>/*</url-pattern>
</filter-mapping>
</xml>

log4j2.xml

<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss:SSS} [%X{ipAddress}] [%t] %-5p (%c{1}.java:%L).%M - %m%n" />

相关问题