一、业务需求
多个实例需要拥有各自的配置文件,并通过文件名-[ip].log标识。或想要在打印的日志中显示线程id,ip地址,自定义标识,都可以通过如下方式实现
参考文章:Logback日志名和日志内容配置增加ip等信息_下个路口见_20的博客-优快云博客
二、实现
1、只在文件内部使用
实现步骤:
①编写继承了ch.qos.logback.classic.pattern.ClassicConverter类的方法
②重写convert()方法,将需要用到的变量返回即可
③在xml配置文件中引入,并使用
编写方法
package com.ipu.server.util;
import ch.qos.logback.classic.pattern.ClassicConverter;
import ch.qos.logback.classic.spi.ILoggingEvent;
import org.springframework.util.StringUtils;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
public class IpUtil2 extends ClassicConverter {
@Override
public String convert(ILoggingEvent iLoggingEvent) {
InetAddress ia = null;
String result="";
try {
ia = InetAddress.getLocalHost();
String ip = ia.getHostAddress();
result = ip.substring(ip.indexOf(".", ip.indexOf(".") + 1) + 1);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (StringUtils.isEmpty(result)){
Random random = new Random();
result = "noip-"+random.nextInt();
}
return result;
}
}
在配置文件中引入
<conversionRule conversionWord="ip2" converterClass="com.ipu.server.util.IpUtil2" />
使用
在需要用到的地方通过%ip2取就可以,ip2换成自己定义的名字
<pattern>%d{HH:mm:ss.SSS} [%thread] -%ip2 %-5level %logger - %msg%n</pattern>
2、需要在文件名称上添加标识
以上方式可以在文件内部使用,但是在运行过程中发现在日志文件创建过程中,该配置还没有生效,文件名显示undefined。 所以如果需要在日志文件名中也显示ip等自定义信息,可以实现PropertyDefiner接口或者继承PropertyDefinerBase类,然后重写getPropertyValue()方法即可。
实现步骤:
①继承ch.qos.logback.core.PropertyDefinerBase类
②重写getPropertyValue(),把需要用到的变量返回
③在xml文件中定义并使用
编写方法
package com.ipu.server.util;
import ch.qos.logback.core.PropertyDefinerBase;
import org.springframework.util.StringUtils;
import javax.servlet.http.HttpServletRequest;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Random;
public class IpUtil extends PropertyDefinerBase {
@Override
public String getPropertyValue() {
InetAddress ia = null;
String result="";
try {
ia = InetAddress.getLocalHost();
String ip = ia.getHostAddress();
result = ip.substring(ip.indexOf(".", ip.indexOf(".") + 1) + 1);
} catch (UnknownHostException e) {
e.printStackTrace();
}
if (StringUtils.isEmpty(result)){
Random random = new Random();
result = "noip-"+random.nextInt();
}
return result;
}
}
在xml文件中引入
<define name="ip" class="com.ipu.server.util.IpUtil"/>
在xml文件中使用
在需要用到的地方通过${ip}取值即可,需要将ip换成自己定义的名字
<file>logs/mapp-${ip}.log</file>