gpt4 book ai didi

java - log4j2如何记录包?

转载 作者:行者123 更新时间:2023-12-01 16:40:06 24 4
gpt4 key购买 nike

我需要支持将特定包记录到 chats.log 中,并将错误记录到 error.log 中。如何正确执行此操作?到目前为止,我在几个附加程序中创建了阈值过滤器,但 error.log 保持为空,并且 chats.log 有一个条目,该条目不属于特定包。毕竟,我仔细阅读了 log4j 的文档,并尝试了 2 天解决这个问题,并遵循了网站和 youtube 上的几个教程。我也尝试过这个:Apache Log4j2 package specific logging using log4j2.xml我也尝试了旧的 log4j 教程,但这以错误结束。

这些是我在 Maven 项目结构中使用的文件。src/main/resources/log4j2.properties

status = error
name = PropertiesConfig

######################################
# Global properties as varies
######################################
property.logPath = logs

######################################
# Filters and properties of filters
######################################
filters = threshold

filter.threshold.type = ThresholdFilter
filter.threshold.level = all

######################################
# Appenders Section for roles
######################################
appenders = rolling, console, rolling2, errorAppender, service

appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.immediateFlush= true
appender.rolling.append = true
appender.rolling.fileName = ${logPath}/server.log
appender.rolling.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
appender.rolling.filter.threshold.type = LevelRangeFilter
appender.rolling.filter.threshold.minLevel = INFO
appender.rolling.filter.threshold.maxLevel = INFO
appender.rolling.filter.threshold.onMatch = ACCEPT
appender.rolling.filter.threshold.onMismatch = DENY

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

appender.rolling2.type = RollingFile
appender.rolling2.name = debugLog
appender.rolling2.immediateFlush= true
appender.rolling2.append = true
appender.rolling2.fileName = ${logPath}/debug.log
appender.rolling2.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling2.layout.type = PatternLayout
appender.rolling2.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling2.policies.type = Policies
appender.rolling2.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling2.policies.time.interval = 1
appender.rolling2.policies.time.modulate = true
appender.rolling2.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling2.policies.size.size=10MB
appender.rolling2.strategy.type = DefaultRolloverStrategy
appender.rolling2.strategy.max = 20
appender.rolling2.filter.threshold.type = LevelRangeFilter
appender.rolling2.filter.threshold.minLevel = DEBUG
appender.rolling2.filter.threshold.maxLevel = DEBUG
appender.rolling2.filter.threshold.onMatch = ACCEPT
appender.rolling2.filter.threshold.onMismatch = DENY

appender.errorAppender.type = RollingFile
appender.errorAppender.name = errorLog
appender.errorAppender.immediateFlush= true
appender.errorAppender.append = true
appender.errorAppender.fileName = ${logPath}/error.log
appender.errorAppender.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.errorAppender.layout.type = PatternLayout
appender.errorAppender.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.errorAppender.policies.type = Policies
appender.errorAppender.policies.time.type = TimeBasedTriggeringPolicy
appender.errorAppender.policies.time.interval = 1
appender.errorAppender.policies.time.modulate = true
appender.errorAppender.policies.size.type = SizeBasedTriggeringPolicy
appender.errorAppender.policies.size.size=10MB
appender.errorAppender.strategy.type = DefaultRolloverStrategy
appender.errorAppender.strategy.max = 20
appender.errorAppender.filter.threshold.type = LevelRangeFilter
appender.errorAppender.filter.threshold.minLevel = ERROR
appender.errorAppender.filter.threshold.maxLevel = ERROR
appender.errorAppender.filter.threshold.onMatch = ACCEPT
appender.errorAppender.filter.threshold.onMismatch = DENY

appender.service.type = RollingFile
appender.service.name = chats
appender.service.append = true
appender.service.fileName = ${logPath}/chats.log
appender.service.filePattern = chats-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.service.layout.type = PatternLayout
appender.service.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.service.policies.type = Policies
appender.service.policies.time.type = TimeBasedTriggeringPolicy
appender.service.policies.time.interval = 1
appender.service.policies.time.modulate = true
appender.service.policies.size.type = SizeBasedTriggeringPolicy
appender.service.policies.size.size=10MB
appender.service.strategy.type = DefaultRolloverStrategy
appender.service.strategy.max = 20
appender.service.filter.threshold.type = LevelRangeFilter
appender.service.filter.threshold.minLevel = INFO
appender.service.filter.threshold.maxLevel = INFO
appender.service.filter.threshold.onMatch = ACCEPT
appender.service.filter.threshold.onMismatch = DENY

######################################
# Loggers Section for file write
######################################
loggers = rolling, package

logger.rolling.name = org.remad.logging
logger.rolling.appenderRefs = rolling, debugLog, errorLog
logger.rolling.level = all
logger.rolling.additivity = true
logger.rolling.appenderRef.rolling.ref = RollingFile
logger.rolling.appenderRef.rolling2.ref = debugLog

logger.package.name = org.remad.logging.protocol.Protocol
logger.package.appenderRefs = service
logger.package.level = info
logger.package.additivity = false
logger.package.appenderRef.service.ref = chats

######################################
# RootLogger Section for settings
######################################
rootLogger.level = all
rootLogger.appenderRefs = stdout, chats, errorLog
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.service.ref = chats
rootLogger.apenderRef.errorAppender.ref = errorLog

pom.xml

<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>

<groupId>org.remad</groupId>
<artifactId>Logging</artifactId>
<version>1.0-SNAPSHOT</version>

<!-- ====================================================================== -->
<!-- Global project properties -->
<!-- ====================================================================== -->
<properties>
<project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
</properties>

<!-- ====================================================================== -->
<!-- project Dependencies -->
<!-- ====================================================================== -->
<dependencies>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>2.13.2</version>
</dependency>
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-core</artifactId>
<version>2.13.2</version>
</dependency>
</dependencies>

<!-- ====================================================================== -->
<!-- project build with plugins -->
<!-- ====================================================================== -->
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.8.1</version>
<configuration>
<source>10</source>
<target>10</target>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-shade-plugin</artifactId>
<version>3.2.2</version>
<executions>
<execution>
<phase>package</phase>
<goals>
<goal>shade</goal>
</goals>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-dependency-plugin</artifactId>
<version>3.1.2</version>
<executions>
<execution>
<id>copy-dependencies</id>
<phase>package</phase>
<goals>
<goal>copy-dependencies</goal>
</goals>
<configuration>
<outputDirectory>${project.build.directory}/lib</outputDirectory>
<overWriteReleases>false</overWriteReleases>
<overWriteSnapshots>false</overWriteSnapshots>
<overWriteIfNewer>true</overWriteIfNewer>
</configuration>
</execution>
</executions>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-jar-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<archive>
<manifest>
<addClasspath>true</addClasspath>
<classpathPrefix>lib/</classpathPrefix>
<mainClass>org.remad.logging.Main</mainClass>
</manifest>
</archive>
</configuration>
</plugin>
<plugin>
<artifactId>maven-assembly-plugin</artifactId>
<version>3.2.0</version>
<configuration>
<descriptorRefs>
<descriptorRef>jar-with-dependencies</descriptorRef>
</descriptorRefs>
</configuration>
</plugin>
</plugins>
</build>

</project>

src/main/org.remad.logging.Main.java

package org.remad.logging;

import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
import org.remad.logging.protocol.Protocol;

public class Main {

private static final Logger logger = LogManager.getLogger(Main.class);

public static void main(String[] args) {
String message = "Hello there!";
LoggerEntryPoint loggerEntryPoint = new LoggerEntryPoint();
Protocol protocol = new Protocol();
logger.trace(message);
logger.debug(message);
logger.info(message);
logger.warn(message);
logger.error(message);
logger.fatal(message);
loggerEntryPoint.entries();
protocol.logSomeMessages();
}
}

org.remad.logging.LoggerEntryPoint.java

package org.remad.logging;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class LoggerEntryPoint {

private static final Logger logger = LogManager.getLogger(LoggerEntryPoint.class);

public LoggerEntryPoint() {}

public void entries() {
logger.info("now in " + getClass().getCanonicalName());
logger.error("now error.");
logger.debug("hggxdfghcdft");
}
}

org.remad.logging.protocol.Protocol.java

package org.remad.logging.protocol;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;

public class Protocol {

public Protocol() {}

private static final Logger logger = LogManager.getLogger(Protocol.class);

public void logSomeMessages() {
logger.fatal("Fatal error.");
logger.error("Error happened.");
logger.warn("Warning message.");
logger.info("This message informs.");
logger.debug("Debug message.");
logger.info("This is also chat message");
}
}

日志/server.log

2020-05-18 17:24:42 INFO  Main:17 - Hello there!
2020-05-18 17:24:42 INFO LoggerEntryPoint:13 - now in org.remad.logging.LoggerEntryPoint

日志/错误.log


日志/debug.log

2020-05-18 17:24:42 DEBUG Main:16 - Hello there!
2020-05-18 17:24:42 DEBUG LoggerEntryPoint:15 - hggxdfghcdft

日志/chats.log

2020-05-18 17:24:42 INFO  Main:17 - Hello there!
2020-05-18 17:24:42 INFO LoggerEntryPoint:13 - now in org.remad.logging.LoggerEntryPoint
2020-05-18 17:24:42 INFO Protocol:16 - This message informs.
2020-05-18 17:24:42 INFO Protocol:18 - This is also chat message

最佳答案

您有一个级别设置为“全部”的全局阈值过滤器。这意味着每个日志事件都将被发送到附加程序,无论记录器上设置的日志记录级别如何。您还将根日志记录级别设置为“全部”。这是一种非常糟糕的做法,因为它将导致性能问题,因为每个日志记录调用都会创建一个 LogEvent,并且因为您正在捕获行号,所以每个事件都需要通过遍历线程的堆栈跟踪来捕获位置信息。

摆脱全局阈值过滤器。您的情况不需要它。将根日志记录级别设置为 DEBUG,然后设置附加程序引用的日志记录级别以匹配您想要记录的内容。

我已将您的配置修改为我认为可行的配置,但我还没有尝试过。我更喜欢 XML 语法,所以如果我打错了,请不要感到惊讶。

status = error
name = PropertiesConfig

######################################
# Global properties as varies
######################################
property.logPath = logs


######################################
# Appenders Section for roles
######################################
appenders = rolling, console, rolling2, errorAppender, service

appender.rolling.type = RollingFile
appender.rolling.name = RollingFile
appender.rolling.immediateFlush= true
appender.rolling.append = true
appender.rolling.fileName = ${logPath}/server.log
appender.rolling.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling.layout.type = PatternLayout
appender.rolling.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling.policies.type = Policies
appender.rolling.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling.policies.time.interval = 1
appender.rolling.policies.time.modulate = true
appender.rolling.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling.policies.size.size=10MB
appender.rolling.strategy.type = DefaultRolloverStrategy
appender.rolling.strategy.max = 20
appender.rolling.filter.threshold.type = LevelRangeFilter
appender.rolling.filter.threshold.minLevel = INFO
appender.rolling.filter.threshold.maxLevel = INFO
appender.rolling.filter.threshold.onMatch = ACCEPT
appender.rolling.filter.threshold.onMismatch = DENY

appender.console.type = Console
appender.console.name = STDOUT
appender.console.layout.type = PatternLayout
appender.console.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

appender.rolling2.type = RollingFile
appender.rolling2.name = debugLog
appender.rolling2.immediateFlush= true
appender.rolling2.append = true
appender.rolling2.fileName = ${logPath}/debug.log
appender.rolling2.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.rolling2.layout.type = PatternLayout
appender.rolling2.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.rolling2.policies.type = Policies
appender.rolling2.policies.time.type = TimeBasedTriggeringPolicy
appender.rolling2.policies.time.interval = 1
appender.rolling2.policies.time.modulate = true
appender.rolling2.policies.size.type = SizeBasedTriggeringPolicy
appender.rolling2.policies.size.size=10MB
appender.rolling2.strategy.type = DefaultRolloverStrategy
appender.rolling2.strategy.max = 20
appender.rolling2.filter.threshold.type = LevelRangeFilter
appender.rolling2.filter.threshold.minLevel = DEBUG
appender.rolling2.filter.threshold.maxLevel = DEBUG
appender.rolling2.filter.threshold.onMatch = ACCEPT
appender.rolling2.filter.threshold.onMismatch = DENY

appender.errorAppender.type = RollingFile
appender.errorAppender.name = errorLog
appender.errorAppender.immediateFlush= true
appender.errorAppender.append = true
appender.errorAppender.fileName = ${logPath}/error.log
appender.errorAppender.filePattern = debug-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.errorAppender.layout.type = PatternLayout
appender.errorAppender.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.errorAppender.policies.type = Policies
appender.errorAppender.policies.time.type = TimeBasedTriggeringPolicy
appender.errorAppender.policies.time.interval = 1
appender.errorAppender.policies.time.modulate = true
appender.errorAppender.policies.size.type = SizeBasedTriggeringPolicy
appender.errorAppender.policies.size.size=10MB
appender.errorAppender.strategy.type = DefaultRolloverStrategy
appender.errorAppender.strategy.max = 20
appender.errorAppender.filter.threshold.type = LevelRangeFilter
appender.errorAppender.filter.threshold.minLevel = ERROR
appender.errorAppender.filter.threshold.maxLevel = ERROR
appender.errorAppender.filter.threshold.onMatch = ACCEPT
appender.errorAppender.filter.threshold.onMismatch = DENY

appender.service.type = RollingFile
appender.service.name = chats
appender.service.append = true
appender.service.fileName = ${logPath}/chats.log
appender.service.filePattern = chats-backup-%d{MM-dd-yy-HH-mm-ss}-%i.log.gz
appender.service.layout.type = PatternLayout
appender.service.layout.pattern = %d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
appender.service.policies.type = Policies
appender.service.policies.time.type = TimeBasedTriggeringPolicy
appender.service.policies.time.interval = 1
appender.service.policies.time.modulate = true
appender.service.policies.size.type = SizeBasedTriggeringPolicy
appender.service.policies.size.size=10MB
appender.service.strategy.type = DefaultRolloverStrategy
appender.service.strategy.max = 20
appender.service.filter.threshold.type = LevelRangeFilter
appender.service.filter.threshold.minLevel = INFO
appender.service.filter.threshold.maxLevel = INFO
appender.service.filter.threshold.onMatch = ACCEPT
appender.service.filter.threshold.onMismatch = DENY

######################################
# Loggers Section for file write
######################################
loggers = rolling, package

logger.rolling.name = org.remad.logging
logger.rolling.appenderRefs = rolling, rolling2
logger.rolling.level = DEBUG
logger.rolling.additivity = true
logger.rolling.appenderRef.rolling.ref = RollingFile
logger.rolling.appenderRef.rolling.level = INFO
logger.rolling.appenderRef.rolling2.ref = debugLog
logger.rolling.appenderRef.rolling2.ref = DEBUG

logger.package.name = org.remad.logging.protocol.Protocol
logger.package.appenderRefs = service
logger.package.level = info
logger.package.additivity = false
logger.package.appenderRef.service.ref = chats
logger.package.appenderRef.service.level = INFO

######################################
# RootLogger Section for settings
######################################
rootLogger.level = INFO
rootLogger.appenderRefs = stdout, chats, errorLog
rootLogger.appenderRef.stdout.ref = STDOUT
rootLogger.appenderRef.stdout.level = INFO
rootLogger.appenderRef.service.ref = chats
rootLogger.appenderRef.service.level = INFO
rootLogger.apenderRef.errorAppender.ref = errorLog
rootLogger.appenderRef.errorAppender.ref = ERROR

我将过滤器留在了 Appender 上,以仅过滤您想要的级别。我不确定为什么你只想要特定 Appender 上的 INFO 或 ERROR 消息,而不是该级别的默认消息和更具体的消息,但我保留了它。如果您确实不需要,请删除这些过滤器。

关于java - log4j2如何记录包?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61874348/

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