logback.xml中获取主机IP地址
方法一:自定义类并继承:ch.qos.logback.classic.pattern.ClassicConverter
1.自定义类LogIpConfig
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author huang
* @version 1.0
* @description:
* @date 2022-10-08 16:12
*/
public class LogIpConfig extends ClassicConverter {
private static final Logger logger = LoggerFactory.getLogger(LogIpConfig .class);
private static String webIP;
static {
try {
webIP = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.error("获取日志Ip异常", e);
webIP = null;
}
}
@Override
public String convert(ILoggingEvent event) {
return webIP;
}
}
2.在logback.xml文件中添加如下配置
<conversionRule conversionWord="ipAddress" converterClass="com.***.config.LogIpConfig" />
3.获取主机地址IP值:%ipAddress 值
"ipAddress":%ipAddress
方法二:自定义类并继承:ch.qos.logback.core.PropertyDefinerBase类
1.自定义类LogIpConfig
import ch.qos.logback.core.PropertyDefinerBase;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.net.InetAddress;
import java.net.UnknownHostException;
/**
* @author huang
* @version 1.0
* @description:
* @date 2022-10-09 15:16
*/
public class LogIpPropertyConfig extends PropertyDefinerBase {
private static final Logger logger = LoggerFactory.getLogger(LogIpPropertyConfig .class);
private static String ip;
static {
try {
ip = InetAddress.getLocalHost().getHostAddress();
} catch (UnknownHostException e) {
logger.error("获取日志IP地址异常",e);
ip = null;
}
}
@Override
public String getPropertyValue() {
return ip;
}
}
2.在logback.xml文件中添加如下配置
<define name="ip" class="com.***.config.LogIpPropertyConfig"></define>
3.获取主机地址IP值:${ip}值
将IP地址拼接到日志名称上:
<fileNamePattern>${log_path}/${ip}-%d{yyyy-MM-dd}.%i.log</fileNamePattern>