更新时间:2022-06-25 22:06:27
您需要下载此二进制存档
添加log4j-api-2.8。 1.jar和log4j-core-2.8.1.jar到你的项目。 (在NetBeans中:文件 - >项目属性 - >库。我必须将它添加到编译和运行,否则我会在运行时收到错误。)
Add "log4j-api-2.8.1.jar" and "log4j-core-2.8.1.jar" to your project. (in NetBeans: File -> Project Properties -> Libraries. I had to add it to both "compile" and "run", or else I would get an error at runtime.)
告诉Log4j文件所在的位置。 (在NetBeans中:文件 - >项目属性 - >运行。粘贴
Tell Log4j where the file is. (in NetBeans: File -> Project Properties -> Run. Paste
-Dlog4j.configurationFile=/path/to/your/file/log4j2.xml
进入Textfield VM-Options
into the Textfield "VM-Options"
在指定路径创建名为log4j2.xml的XML(我在我的项目的主文件夹)与您的配置,例如
Create an XML called log4j2.xml at the specified path (I did it in the main folder of my project) with your configuration, e.g.
<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn">
<Appenders>
<Console name="STDOUT" target="SYSTEM_OUT">
<PatternLayout pattern="%m%n"/>
</Console>
<File name="FILE" fileName="logs/myLog.log">
<PatternLayout>
<Pattern>%d %p %c{1.} [%t] %m%n</Pattern>
</PatternLayout>
</File>
</Appenders>
<Loggers>
<Root level="INFO">
<AppenderRef ref="FILE" level="INFO"/>
<AppenderRef ref="STDOUT" level="ERROR"/>
</Root>
</Loggers>
</Configuration>
这会创建两个appender,一个ConsoleAppender和一个FileAppender,它们登录System.out并调用一个文件分别是myLog.log。级别INFO和更高级别的日志消息将记录到文件中,只会将错误打印到控制台。
This creates two appenders, a ConsoleAppender and a FileAppender, that log into System.out and a file called "myLog.log", respectively. Log messages of level INFO and higher are logged into the file, only errors are printed to the console.
这是一些示例代码,用于演示如何使用Log4j2:
This is some sample code to demonstrate how Log4j2 is used:
import java.io.IOException;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
public class Demo {
private final static Logger log = LogManager.getLogger(Demo.class);
public static void main(String[] args) throws IOException {
log.info("starting...");
try {
((Object) null).toString();
} catch (Exception e) {
log.error("error message");
}
log.info("some info.");
}
}
运行此导致控制台输出
error message
虽然该文件包含
2017-03-29 14:37:20,675 INFO l.Demo [main] starting...
2017-03-29 14:37:20,676 ERROR l.Demo [main] error message
2017-03-29 14:37:20,676 INFO l.Demo [main] some info.
我希望这给你省点麻烦,因为我花了很长时间来解决这个问题。随意编辑这篇文章 - 我不知道我的陈述有多正确,这些只是对我有用的步骤。
I hope this saved you some trouble, as it took me quite some time to figure this out. Feel free to edit this post - I have no idea how correct my statements are, these are just the steps that worked for me.