springboot 使用 logback 输出日志打印本机 ip
网上很多贴推荐使用在 logback-spring.xml 里配置 conversionRule 标签,但报如下错:
ERROR in ch.qos.logback.core.joran.spi.Interpreter@4:95 - no applicable action for [converisonRule], current ElementPath is [[configuration][converisonRule]]
怀疑和 spring 内置的 conversionRlue 冲突。换了一种思路,使用 define 标签实现。
实现办法如下: 在 logback-spring.xml 加入
<define name="ip" class="com.xxx.x.xx.xxxx.LogIpConfig"/> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <encoder> <pattern> ${ip} %d %p (%file:%line)- %m%n</pattern> <!-- 控制台也要使用UTF-8,不要使用GBK,否则会中文乱码 --> <charset>UTF-8</charset> </encoder> </appender>
注意 使用 ${ip}的方式来引用自定义的 ip 变量
在项目中新建 LogIpConfig 继承类 PropertyDefinerBase
package com.xxx.x.xx.xxxx; import ch.qos.logback.core.PropertyDefinerBase; import java.net.InetAddress; import java.net.UnknownHostException; public class LogIpConfig extends PropertyDefinerBase { private static String ip; static { try { ip = InetAddress.getLocalHost().getHostAddress(); } catch (UnknownHostException e) { e.printStackTrace(); ip = null; } } @Override public String getPropertyValue() { return ip; } }