在 log4j2 中打印 intLevel



您可以在 https://logging.apache.org/log4j/2.x/manual/customloglevels.html 中看到与内置log4j2日志记录级别对应的数值,例如INFO->400。如何在 JDBC 记录器配置中的模式布局或模式布局中引用它?

我有一个旧的 log4j 1.x JDBC 配置,它被称为 %iprio。

解决方法是使用

级别{关闭=0,致命=100,

错误=200,警告=300,INFO=400,调试=500,跟踪=600,全部=1000}

但我对此不是很满意。

听起来您想记录日志级别的整数值而不是名称,并且您不想使用PatternLayoutlevel参数的标记功能。

一种可能的解决方案是创建自定义Lookup,以下是一些示例代码:

package example;
import org.apache.logging.log4j.core.LogEvent;
import org.apache.logging.log4j.core.config.plugins.Plugin;
import org.apache.logging.log4j.core.lookup.StrLookup;
@Plugin(name = "level", category = "Lookup")
public class LevelLookup implements StrLookup{
/**
* Lookup the value for the key.
* @param key  the key to be looked up, may be null
* @return The value for the key.
*/
public String lookup(String key) {
return null;
}

/**
* Lookup the value for the key using the data in the LogEvent.
* @param event The current LogEvent.
* @param key  the key to be looked up, may be null
* @return The value associated with the key.
*/
public String lookup(LogEvent event, String key) {
return String.valueOf(event.getLevel().intLevel());
}
}

接下来,下面是使用新查找的示例配置 - 请注意${level:}

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
<Appenders>
<Console name="Console" target="SYSTEM_OUT">
<PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] ${level:} %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<AppenderRef ref="Console" />           
</Root>
</Loggers>
</Configuration>

下面是一些执行一些日志记录的示例代码:

package example;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class SomeClass {
private static final Logger log = LogManager.getLogger();   
public static void main(String[] args){
log.debug("This is some debug!");
log.info("Here's some info!");
log.error("Some erorr happened!");
}
}

最后是输出:

22:49:29.438 [main] 500 example.SomeClass - This is some debug!
22:49:29.440 [main] 400 example.SomeClass - Here's some info!
22:49:29.440 [main] 200 example.SomeClass - Some erorr happened!

希望这有帮助!

最新更新