简体   繁体   English

使用log4j在Java中进行参数化日志记录时出现错误

[英]Errors in Parameterized Logging in java using log4j

I recently started using Log4j. 我最近开始使用Log4j。 I came across a better logging technique of parameterized logging. 我遇到了一种更好的参数化日志记录技术。

I referred the below link. 我引用了以下链接。

https://logging.apache.org/log4j/2.x/performance.html https://logging.apache.org/log4j/2.x/performance.html

The above link is for log4j2. 上面的链接用于log4j2。 But I was wondering if the same is applicable for 1.2.9 但我想知道是否同样适用于1.2.9

When I try to write a logger statement with parameters, I am getting below error. 当我尝试编写带有参数的logger语句时,出现以下错误。

The method info(Object, Throwable) in the type Category is not applicable for the arguments (String, String) 类型类别中的方法info(Object,Throwable)不适用于参数(字符串,字符串)

I checked the source code of 我检查了源代码

I am using log4j 1.2.9 我正在使用log4j 1.2.9

The java code is as below. Java代码如下。

import org.apache.log4j.Logger;

import com.test.validators.CreateValidator;

public class CreateLogic {

    Logger admin = Logger.getLogger("admin");

public void createLogic(){
    admin.info("This is Create Logic");
    CreateValidator CreateValidator = new CreateValidator();
    CreateValidator.validateCreate();
    int i = 5;
    admin.info("the name is {}",i);

    }

}

log4j properties are as below. log4j属性如下。

log4j.logger.admin=INFO, admin
log4j.additivity.admin = false

log4j.appender.admin=org.apache.log4j.RollingFileAppender
log4j.appender.admin.File=C:\\Create.log
log4j.appender.admin.MaxFileSize=5MB
log4j.appender.admin.MaxBackupIndex=1
log4j.appender.admin.layout=org.apache.log4j.PatternLayout
log4j.appender.admin.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1} - %m%n

The method that you reference from the 2.x API isn't parameterized logging, or at least in the way you want. 从2.x API引用的方法不是参数化日志记录,或者至少不是您想要的方式。 The method that you actually want is void info(String message, Object... params) . 您实际想要的方法是void info(String message,Object ... params) And this method is a part of the log4j 2.x API. 而且此方法是log4j 2.x API的一部分。 It looks like log4j 1.x doesn't offer it on its own. 看起来log4j 1.x并没有单独提供它。 However, if you aren't bound to log4j, you could take a look at the sl4j library, which essentially hides the log4j implementation and offers that parameterized logging functionality. 但是,如果您不受限于log4j,则可以查看sl4j库,该库实质上隐藏了log4j实现并提供了该参数化的日志记录功能。

If you are bound to log4j, then I think one solution would be to format the message beforehand with the parameters you would have passed in the log message, like so: 如果一定要log4j的话,我认为一个解决办法是你将在日志消息已经过去了,像这样的参数预先格式化消息:

 int i = 5;
 String msg = String.format("the name is %d", i);
 admin.info(msg);

Hope that helps. 希望能有所帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM