gpt4 book ai didi

java - Log4j 打印扩展类名

转载 作者:行者123 更新时间:2023-11-30 03:36:00 26 4
gpt4 key购买 nike

如何记录扩展类的名称?我想写“FTSControl”而不是“Control”。

public abstract class Control {   
Logger logger = Logger.getLogger(getClass());
}

@Component
public class FTSControl extends Control {

}

<layout class="org.apache.log4j.PatternLayout">
<param name="ConversionPattern" value="%d{dd.MM.yyyy HH:mm:ss.SSS} %-5p - %C{1}:%m%n" />
</layout>

输出:

09.01.2015 15:58:00.006 WARN  - Control: No files found! Hash:-844390824

我还指出了一些事情,

尽管使用相同的记录器实例,但 Control 和 FTSControl 方法中的 log.info() 调用会打印其自己的类名。我的意思是

FTSControl 打印方法中的 logger.info()

09.01.2015 15:58:00.006 WARN  - FTSControl : No files found! Hash:-844390824

Control打印方法中的logger.info()

09.01.2015 15:58:00.006 WARN  - Control: No files found! Hash:-844390824

//更新完整示例

package com.log;

import org.apache.log4j.Logger;
import org.apache.log4j.xml.DOMConfigurator;

import com.log.abstracttest.ControlAbs;
import com.log.abstracttest.ImosControl;


public class LogMainTest {

private Logger logger = Logger.getLogger("console");

public LogMainTest(){
DOMConfigurator.configure(this.getClass().getClassLoader().getResource("log4j.xml"));
logger.info("Initializing...");

ImosControl control = new ImosControl();
control.print();
control.printAll();

}

public static void main(String[] args) {
new LogMainTest();

}


}


package com.log.abstracttest;

import org.apache.log4j.Logger;

public abstract class ControlAbs {
Logger logger = Logger.getLogger(this.getClass());

public void print(){
logger.info(" print");
}

}


package com.log.abstracttest;

public class ImosControl extends ControlAbs {

public void printAll(){
logger.info("printAll");
}

}

输出:

10.01.2015 05:38:43.497 INFO  - LogMainTest:Initializing...
10.01.2015 05:38:43.502 INFO - ControlAbs: print
10.01.2015 05:38:43.503 INFO - ImosControl:printAll

最佳答案

只需将抽象类中的 Logger logger = Logger.getLogger(getClass()); 替换为

protected final Logger logger = Logger.getLogger(this.getClass());

这样,如果您在 FTSControl 中使用类似 logger.info("test") 的内容,您将在日志中获取实例化类名称

关于java - Log4j 打印扩展类名,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27862348/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com