系统弄一弄,收获不少。不要maven,不要spring,不要IDEA,就直接弄。
log4j2不再支持properties文件,所以下面会报错,以后只支持XML,JSON,YAML文件格式。
为了快速学习,很多代码糊在一起的,用注释来快速保留。
一,代码
log4j2.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration status="WARN">
<Appenders>
<!--
<File name="MyFile" fileName="myLogFile.log" append="false">
<PatternLayout pattern="%t %-5p %c{2} - %m%n" />
</File>
<Async name="Async">
<AppenderRef ref="MyFile" />
</Async>
<RollingFile name="RollingFile">
<Filename>mylog.log</Filename>
<FilePattern>%d{yyyy-MM-dd-hh-mm}.log.zip</FilePattern>
<PatternLayout>
<Pattern>%d{yyyy-MM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n</Pattern>
</PatternLayout>
<Policies>
<TimeBasedTriggeringPolicy interval="1" modulate="true" />
<SizeBasedTriggeringPolicy size="5KB" />
</Policies>
<DefaultRolloverStrategy max="5" />
</RollingFile>
-->
<Console name="consoleAppender" target="SYSTEM_OUT">
<RegexFilter regex=".*message.*" onMatch="ACCEPT" onMismatch="DENY" />
<PatternLayout pattern="%d{yyyy-MM-dd HH:mm:ss a} [%t] %-5level %logger{36} - %msg%n" />
</Console>
</Appenders>
<Loggers>
<Root level="debug">
<!-- <AppenderRef ref="Async" /> -->
<!-- <AppenderRef ref="RollingFile" /> -->
<AppenderRef ref="consoleAppender" />
</Root>
<!--
<Root level="trace">
<AppenderRef ref="consoleAppender" />
</Root>
-->
</Loggers>
</configuration>
Interface3 .java
package com.example.demo;
public interface Interface3 {
public int warningMessage(int count);
}
Interface4 .java
package com.example.demo;
public interface Interface4 {
public String errorMessage(String message);
}
DemoApplication.java
package com.example.demo;
import org.apache.logging.log4j.Level;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.core.Filter;
import org.apache.logging.log4j.core.LoggerContext;
import org.apache.logging.log4j.core.appender.ConsoleAppender;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.builder.api.*;
import org.apache.logging.log4j.core.config.builder.impl.BuiltConfiguration;
import java.io.File;
import java.net.URI;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.net.URISyntaxException;
public class DemoApplication {
public static void main(String[] args) throws InterruptedException, FileNotFoundException, IOException, URISyntaxException {
ConfigurationSource source = new ConfigurationSource(new FileInputStream(new File("D:\\test\\demo\\src\\main\\resources\\log4j2.xml")));
Configurator.initialize(null, source);
// log4j2不再支持properties文件,所以下面会报错,以后只支持XML,JSON,YAML文件格式
// ConfigurationSource source = new ConfigurationSource(new FileInputStream(new File("D:\\test\\demo\\src\\main\\resources\\log4j2.properties")));
// 配置Log4j
Configurator.initialize(null, source);
Logger LOG = LogManager.getLogger(DemoApplication.class);
/*
ConfigurationBuilder<BuiltConfiguration> builder = ConfigurationBuilderFactory.newConfigurationBuilder();
builder.setStatusLevel(Level.WARN);
builder.setConfigurationName("MyConfig");
// builder.add(builder.newFilter("ThresholdFilter", Filter.Result.ACCEPT, Filter.Result.NEUTRAL)
// .addAttribute("level", Level.DEBUG));
LayoutComponentBuilder layoutBuilder = builder.newLayout("PatternLayout")
.addAttribute("pattern", "%d [%t] %-5level: %msg%n");
ComponentBuilder triggeringPolicy = builder.newComponent("Policies")
.addComponent(builder.newComponent("SizeBasedTriggeringPolicy")
.addAttribute("size", "1KB"));
// AppenderComponentBuilder appenderComponent = builder.newAppender("Stdout", "CONSOLE").addAttribute("target",
// ConsoleAppender.Target.SYSTEM_OUT);
// appenderComponent.add(
// builder.newLayout("PatternLayout")
// .addAttribute("pattern", "%d [%t] (%c) %-5level: %msg%n%throwable"));
AppenderComponentBuilder appenderComponent = builder.newAppender("rolling", "RollingFile")
.addAttribute("fileName", "myRollingLogFile.log")
.addAttribute("filePattern", "rolling-%d{MM-dd-yy}.log.gz")
.addComponent(layoutBuilder)
.addComponent(triggeringPolicy);
builder.add(appenderComponent);
builder.add(builder.newLogger("com.example.demo.myFirstLogger", Level.DEBUG)
.add(builder.newAppenderRef("Stdout"))
.addAttribute("additivity", true));
builder.add(builder.newLogger("com.example.demo.mySecondLogger", Level.WARN)
.add(builder.newAppenderRef("Stdout"))
.addAttribute("additivity", true));
builder.add(builder.newRootLogger(Level.ERROR)
.add(builder.newAppenderRef("Stdout")));
LoggerContext ctx = Configurator.initialize(builder.build());
// Logger LOG = ctx.getRootLogger();
Logger LOG = ctx.getRootLogger();
Logger myFirstLogger = ctx.getLogger("com.example.demo.myFirstLogger");
Logger mySecondLogger = ctx.getLogger("com.example.demo.mySecondLogger");
*/
LOG.debug("LOG Debug Message");
LOG.info("LOG Info message");
LOG.warn("LOG Warn Message");
LOG.error("LOG error Message");
Interface3 int3 = (count) -> count + 1;
Interface4 int4 = (message) -> message + "Parameter Missing";
LOG.warn("Warning message: Count of files is : " + int3.warningMessage(4));
LOG.error("Error message: " + int4.errorMessage("Attentions!"));
/*
myFirstLogger.info("myFirstLogger Info Message");
myFirstLogger.error("myFirstLogger Error Message");
myFirstLogger.fatal("Fatal Message");
mySecondLogger.warn("mySecondLogger warn Message message");
mySecondLogger.fatal("mySecondLogger fatal Message message");
for (int i = 0; i < 100; i++) {
LOG.info("Info: " + i);
}
Object obj = null;
if (obj == null) LOG.fatal("Object is null!");
try {
int a = 5 / 0;
System.out.println(a);
} catch (ArithmeticException e) {
LOG.error("Cannot divide by zero!");
}
*/
}
}
二,输出
D:\Java\jdk17\bin\java.exe "-javaagent:D:\JetBrains\IntelliJ IDEA Community Edition 2024.3.1.1\lib\idea_rt.jar=3359:D:\JetBrains\IntelliJ IDEA Community Edition 2024.3.1.1\bin" -Dfile.encoding=UTF-8 -classpath D:\test\demo\target\classes;D:\test\demo\src\lib\log4j-api-2.24.3.jar;D:\test\demo\src\lib\log4j-core-2.24.3.jar com.example.demo.DemoApplication
2025-01-02 13:44:55 下午 [main] INFO com.example.demo.DemoApplication - LOG Info message
2025-01-02 13:44:55 下午 [main] WARN com.example.demo.DemoApplication - Warning message: Count of files is : 5
2025-01-02 13:44:55 下午 [main] ERROR com.example.demo.DemoApplication - Error message: Attentions!Parameter Missing
Process finished with exit code 0