Log Filter
一款轻量级的日志过滤模组,旨在减少控制台和日志文件中的垃圾信息,让开发者和玩家能够专注于关键错误并节省磁盘空间。
功能特性
- 正则表达式过滤:支持强大的正则匹配,精确筛选特定的日志内容。
- 精确匹配过滤:可以精确过滤掉指定的整行文本。
- 按记录器(Logger)过滤:支持过滤来自某个模组或类名(Logger Name)的所有日志。
- 按日志级别过滤:一键屏蔽
TRACE 或 DEBUG 等低级日志。
屏蔽 INFO 日志?当然可以!这样你只会看到错误和警告,非常适合调试。
- 白名单模式:设置排除规则,确保重要日志(如严重错误)不会被意外删除。
- 高效缓存:内置去重缓存机制,避免重复处理相同的日志。
安装方法
- 下载模组的 JAR 文件。
- 将 JAR 文件放入 Minecraft 安装目录下的
mods 文件夹中。
- 启动游戏一次。模组会自动生成默认配置文件。
- 根据需要修改配置文件并保存——配置支持热重载(无需重启游戏)。无效的正则表达式会被跳过并给出警告;详见下方说明。
或者手动创建 logfilter-common.toml 文件,按需修改配置,然后再启动游戏。
配置简介
配置文件位于:config/logfilter-common.toml
默认配置如下:
[General]
#Enable or disable log filtering
#启用或禁用日志过滤
enableFilter = true
#Enable debug mode to see which logs are being filtered
#启用调试模式以查看哪些日志被过滤
debugMode = false
#Maximum size of filtered log cache (for duplicate detection)
#过滤日志缓存的最大容量(用于重复检测)
#Range: 100 ~ 10000
maxCacheSize = 1000
[FilterRules]
#Regex patterns to filter log messages. Matching is PARTIAL (regex find): a rule hits when it matches any part of the message, so wrapping with '.*' is unnecessary.
#用于过滤日志消息的正则表达式。匹配方式为包含匹配(find): 规则命中消息任意片段即生效, 无需用 '.*' 包裹。
#REGEX ESCAPING: metacharacters ()[]{}*+?.^$|\ are special; escape them to match literally, e.g. literal parentheses must be written as \( \).
#正则转义: 元字符 ()[]{}*+?.^$|\ 有特殊含义, 按字面匹配必须转义, 例如字面圆括号必须写成 \( \)。
#TOML ESCAPING: in double-quoted strings TOML consumes one level of backslashes, so write "some \\(thing\\)"; in single-quoted literal strings write 'some \(thing\)' directly.
#TOML 转义: 双引号字符串中 TOML 会消耗一层反斜杠, 因此需写 "some \\(thing\\)"; 单引号字面字符串直接写 'some \(thing\)' 即可。
#An invalid regex (e.g. unbalanced parentheses) is safely skipped with a warning (log WARN + in-game chat message); other rules keep working.
#非法正则(如括号不闭合)会被安全跳过并告警(日志 WARN + 进入世界时聊天框提示), 其余规则照常生效。
filterRules = []
#Exact message strings to filter (case-sensitive)
#精确匹配并过滤的消息字符串(区分大小写)
exactMatches = []
#Logger names to completely filter (e.g., 'net.minecraft.server.MinecraftServer')
#完全过滤的 Logger 名称(例如 'net.minecraft.server.MinecraftServer')
loggerNames = []
#Log levels to filter: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
#要过滤的日志级别: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
logLevels = ["TRACE", "DEBUG"]
#Regex patterns that will EXCLUDE logs from filtering (whitelist)
#Regex/TOML escaping rules are the same as filterRules (see its comment above).
#将日志排除在过滤之外的正则表达式(白名单)
#正则与 TOML 的转义规则与 filterRules 相同(见其上方注释)。
excludePatterns = []
[async]
#Enable async log output: wraps all root appenders into a Log4j2 AsyncAppender so console/file I/O runs on a background thread instead of the logging thread
#启用异步日志输出: 将 root logger 的全部 appender 包装进 Log4j2 AsyncAppender, 控制台/文件 I/O 转移到后台线程执行, 打日志的线程只付入队成本
enableAsyncLogging = true
#Capacity of the async queue (number of buffered log events)
#异步队列容量(缓冲的日志事件数量)
#Range: 128 ~ 65536
asyncQueueSize = 4096
#When queue is full: true = briefly block the logging thread (no log loss), false = drop the log event
#队列满时: true = 短暂阻塞打日志线程(不丢日志), false = 丢弃该条日志事件
asyncBlockingWhenFull = true
#Milliseconds to wait for the queue to drain before discarding remaining events (on pipeline rebuild and JVM shutdown)
#等待队列排干的毫秒数, 超时后丢弃剩余事件(在管线重建与 JVM 关闭时生效)
#Range: 0 ~ 600000
asyncShutdownTimeoutMs = 5000
#Capture caller location (class/method/line). Costs a stack walk per event; Minecraft's default log pattern does not need it
#捕获调用方位置(类/方法/行号)。每条日志付出一次栈遍历成本; Minecraft 默认日志格式用不到它, 保持 false 即可
asyncIncludeLocation = false
#Fully qualified class name of a org.apache.logging.log4j.core.async.BlockingQueueFactory implementation (empty = default ArrayBlockingQueue). Upgrade hook: a Disruptor-based factory can be injected later via JarJar without code changes
#BlockingQueueFactory 实现类的全限定名(留空 = 默认 ArrayBlockingQueue)。升级钩子: 后续可通过 JarJar 注入 Disruptor 队列工厂而无需改代码
asyncQueueFactoryClass = ""
General (常规设置)
| 选项 |
默认值 |
描述 |
enableFilter |
true |
是否启用日志过滤功能。 |
debugMode |
false |
启用调试模式,将过滤掉的日志打印到控制台,方便测试规则。 |
maxCacheSize |
1000 |
已过滤日志的缓存大小,用于去重。 |
FilterRules (过滤规则)
1. filterRules (正则表达式)
使用正则表达式匹配需要过滤的日志。
filterRules = [
".*Exception.*", # 过滤掉所有包含 "Exception" 的日志
".*stack trace.*", # 过滤掉堆栈跟踪信息
".*Could not pass event.*"# 过滤掉特定的事件错误
]
⚠ 常见陷阱:正则元字符与双重 TOML 转义
- 正则层:
()[]{}*+?.^$|\ 是正则元字符;若需匹配字面量,必须对其进行转义。例如日志中的 some (thing) 必须写为 \(thing\) —— 否则它们会被解析为捕获组,导致规则静默失效(正则本身是合法的,不会报错)。
- TOML 层:在双引号字符串中,TOML 会消耗一层反斜杠,因此需要双写:
"some \\(thing\\)";推荐使用单引号字面量字符串(无需 TOML 转义):'some \(thing\)'。
- 匹配语义:
filterRules 使用部分匹配(find);只要消息的任何部分匹配到规则,即视为命中,因此无需使用 .* 进行包裹。
- 无效正则(如括号不匹配)会被安全跳过:日志中会写入 WARN 警告,进入世界时会在游戏聊天栏显示警告;其他规则继续正常工作 —— 不会导致启动崩溃。建议先在 regex101.com(Java 模式)上验证规则。
2. exactMatches(精确匹配)
仅当日志内容完全相同(区分大小写)时才被过滤。
exactMatches = [
"This message will be completely filtered out"
]
3. loggerNames(记录器名称)
基于日志来源(类名或模组包名)进行过滤。支持层级过滤。
loggerNames = [
"net.minecraft.server.MinecraftServer", # 过滤主服务器的日志
"com.some.noisy.mod" # 过滤某个嘈杂模组的所有日志
]
4. logLevels(日志级别)
基于日志级别进行过滤。可用值:TRACE、DEBUG、INFO、WARN、ERROR、FATAL。
logLevels = [
"TRACE",
"DEBUG"
]
5. excludePatterns(白名单/排除规则)
非常重要。与此处规则匹配的日志将不会被过滤,即使其他规则也匹配了它们。用于保留关键错误信息。
excludePatterns = [
".*CRITICAL ERROR.*", # 即使它匹配 Exception,如果是 CRITICAL ERROR,则保留
".*IMPORTANT.*"
]
? 构建
如果你想自己编译此模组:
./gradlew build
编译后的 JAR 文件位于 build/libs/ 目录中。
深入探究
第一部分:模组代码层面的工作原理
此模组的核心思想是拦截。它在 Minecraft 的日志输出到达控制台或文件之前“劫持”数据,决定是让通过还是丢弃。
1. 日志框架基础:Log4j 2
Minecraft 1.20.1 使用 Log4j 2 日志框架。
- 日志流程:游戏代码生成日志事件 (
LogEvent) -> 传递给 Log4j 的 LoggerContext -> 传递给 Appender(如控制台 appender、文件写入器)-> 最终显示在屏幕上。
- 过滤机制:Log4j 允许在 Logger 或 Appender 上挂载“过滤器 (
Filter)”。
- 异步输出管道:根 logger 上的所有 appender 都被包装进 Log4j2 的
AsyncAppender(默认启用,可配置):控制台/文件 I/O 在后台线程运行,日志线程仅支付入队成本;队列大小和溢出策略均可配置。
2. 代码执行流程
我们的模组在游戏启动时(FMLCommonSetupEvent)通过 LogFilterManager.java 执行以下操作:
-
获取上下文:
LoggerContext loggerContext = LoggerContext.getContext(false);
我们获取了 Minecraft 当前的日志环境上下文。
-
获取根配置:
Configuration configuration = loggerContext.getConfiguration();
LoggerConfig rootLoggerConfig = configuration.getRootLogger();
我们获取了“根 Logger”的配置。由于几乎所有日志最终都会流向根 Logger,在此挂载过滤器可以捕获全局日志。
-
注册自定义过滤器:
log4jFilter = new FilteringLogFilter(); // 我们的自定义过滤器类
log4jFilter.start();
rootLoggerConfig.addFilter(log4jFilter);
我们在日志处理链的最前端插入了自定义的 FilteringLogFilter。
7. 拦截与决策 (FilteringLogFilter.filter 方法):
每当 Minecraft 尝试输出一条日志行时,Log4j 都会调用我们的 filter(LogEvent event) 方法。为防止因日志过滤导致的游戏卡顿,我们采用了“快速失败”设计,逻辑优先级如下:
* 步骤 A:提取关键信息。 直接从 Log4j LogEvent 中提取 Logger 名称和级别等关键细节。
* 步骤 B:快速检查(级别与 Logger)。 优先检查日志级别 (logLevels) 和 Logger 名称 (loggerNames)。这是一个极低开销的操作。如果找到匹配项,日志将被立即丢弃,完全跳过后续昂贵的消息格式化和正则匹配,显著降低主线程开销。
* 步骤 C:消息格式化。 只有当日志通过快速检查且未被拦截时,才会调用 getFormattedMessage() 来生成消息文本。
* 步骤 D:缓存检查。 计算日志内容的哈希值以检查其是否存在于缓存中。如果存在,立即返回 DENY,避免冗余计算。
* 步骤 E:白名单检查 (excludePatterns)。 如果日志匹配白名单正则,返回 NEUTRAL。白名单具有最高优先级,用于保护重要日志。
* 步骤 F:精确匹配检查 (exactMatches)。 如果日志消息与配置的字符串完全匹配,返回 DENY。
* 步骤 G:正则规则检查 (filterRules)。 如果日志消息匹配配置的正则表达式,返回 DENY。
- 最终结论:
- 如果上述拦截条件中的任何一个匹配,我们返回
Result.DENY。收到 DENY 后,Log4j 会立即丢弃该日志,它不会出现在控制台或文件中。
- 如果没有匹配项,我们返回
Result.NEUTRAL。Log4j 认为过滤器“没有意见”,并将日志继续传递给下一个处理器,最终正常显示。
- 配置热重载:在您编辑并保存
logfilter-common.toml 后,Forge 的配置文件监听器会立即触发重载事件:异步流水线以幂等方式重建(如果参数未更改则跳过),过滤规则重新编译,无效的正则表达式将被跳过并发出警告——无需重启游戏,所有操作均由事件驱动。
第二部分:实际案例分析与配置
让我们看看这条日志:
[241... 00:32:22.574] [Render thread/WARN] [net.minecraft.client.renderer.ShaderInstance/]: Shader rendertype_entity_translucent_emissive could not find sampler named Sampler2 in the specified shader program.
1. 日志条目拆解
我们需要将这条日志分解为几个关键部分:
| 日志片段 |
含义 |
对应配置项 |
备注 |
WARN |
日志级别 |
logLevels |
表示这是警告,而非错误或信息。 |
net.minecraft.client.renderer.ShaderInstance |
Logger 名称 |
loggerNames |
发出此日志的 Java 类的全限定名。 |
Shader ... program. |
日志消息 |
filterRules, exactMatches |
具体的错误内容。 |
2. 如何确定它属于哪个配置项?
- 如果您想阻止由特定类/模组发出的所有消息(例如,我厌倦了看到此类 Shader 的所有错误),您应该使用
loggerNames。
- 如果您想阻止特定级别的所有消息(例如,我不想看到任何 WARN 级别的日志),您应该使用
logLevels。
- 如果您想精确阻止这一句话(即使它只出现一次),您应该使用
exactMatches。
- 如果您想模糊阻止这类错误(例如,无论找不到的是 Sampler1 还是 Sampler2,或者是哪个 Shader,只要它是“cannot find sampler”就阻止它),您应该使用
filterRules。
3. 实际配置解决方案
针对这个特定的 Shader 错误,我们有四种过滤策略。请根据您的需要选择:
方案 A:精确过滤此错误(推荐 - 使用 filterRules)
这条日志的核心特征是“无法找到采样器”。我们可以编写一个正则表达式,涵盖所有找不到采样器的情况,而不影响其他日志。
适用场景:您认为所有关于缺失着色器采样器的警告都是无关紧要的,并希望全部阻止它们。
配置代码:
# 解释:.* 表示任意字符,匹配所有包含 "could not find sampler named" 的日志,无论前后是什么。
filterRules = [".*could not find sampler named.*"]
方案 B:仅阻止这条特定的长句子(使用 exactMatches)
如果您只想阻止关于找不到 Sampler2 的特定警告,但保留其他 Shader 警告。
适用场景:极其精准的打击,无附带伤害。
配置代码:
# 必须与日志中的文本完全相同(通常不包括时间戳和线程名称,仅包括冒号后的内容)
exactMatches = ["Shader rendertype_entity_translucent_emissive could not find sampler named Sampler2 in the specified shader program."]
方案 C:阻止来自 ShaderInstance 类的所有日志(使用 loggerNames)
如果 ShaderInstance 类非常嘈杂,并且您不想看到它输出的任何内容。
适用场景:激进过滤。警告:如果此类后来输出严重的错误日志,您将看不到它们。
配置代码:
# 只要日志来源是 net.minecraft.client.renderer.ShaderInstance,就阻止一切。
loggerNames = ["net.minecraft.client.renderer.ShaderInstance"]
方案 D:阻止所有 WARN 级别的日志(使用 logLevels)
适用场景:不推荐。这将阻止所有警告消息,可能导致您错过真正需要注意的潜在问题。
配置代码:
logLevels = ["WARN"]
Log Filter
A lightweight log filtering mod designed to reduce spam in the console and log files, allowing developers and players to focus on critical errors and save disk space.
Features
- Regex Filtering: Supports powerful regex matching to precisely filter specific log content.
- Exact Match Filtering: Can precisely filter out specified entire lines of text.
- Filter by Logger: Supports filtering all logs from a mod or class name (Logger Name).
- Filter by Log Level: One-click blocking of low-level logs like
TRACE or DEBUG.
Block INFO logs? Of course! This way you will only see errors and warnings, suitable for debugging.
- Whitelist Mode: Set exclusion rules to ensure important logs (like critical errors) are not accidentally deleted.
- Efficient Caching: Built-in deduplication cache mechanism to avoid processing the same logs repeatedly.
Installation
- Download the mod's JAR file.
- Put the JAR file into the
mods folder in your Minecraft installation directory.
- Launch the game once. The mod will automatically generate a default configuration file.
- Modify the configuration file as needed and save — the config hot-reloads automatically (no game restart needed). Invalid regexes are skipped with a warning; see the notes below.
Or manually create a logfilter-common.toml file, modify the configuration as needed, and then launch the game.
Configuration Brief
The configuration file is located at: config/logfilter-common.toml
Default configuration:
[General]
#Enable or disable log filtering
#启用或禁用日志过滤
enableFilter = true
#Enable debug mode to see which logs are being filtered
#启用调试模式以查看哪些日志被过滤
debugMode = false
#Maximum size of filtered log cache (for duplicate detection)
#过滤日志缓存的最大容量(用于重复检测)
#Range: 100 ~ 10000
maxCacheSize = 1000
[FilterRules]
#Regex patterns to filter log messages. Matching is PARTIAL (regex find): a rule hits when it matches any part of the message, so wrapping with '.*' is unnecessary.
#用于过滤日志消息的正则表达式。匹配方式为包含匹配(find): 规则命中消息任意片段即生效, 无需用 '.*' 包裹。
#REGEX ESCAPING: metacharacters ()[]{}*+?.^$|\ are special; escape them to match literally, e.g. literal parentheses must be written as \( \).
#正则转义: 元字符 ()[]{}*+?.^$|\ 有特殊含义, 按字面匹配必须转义, 例如字面圆括号必须写成 \( \)。
#TOML ESCAPING: in double-quoted strings TOML consumes one level of backslashes, so write "some \\(thing\\)"; in single-quoted literal strings write 'some \(thing\)' directly.
#TOML 转义: 双引号字符串中 TOML 会消耗一层反斜杠, 因此需写 "some \\(thing\\)"; 单引号字面字符串直接写 'some \(thing\)' 即可。
#An invalid regex (e.g. unbalanced parentheses) is safely skipped with a warning (log WARN + in-game chat message); other rules keep working.
#非法正则(如括号不闭合)会被安全跳过并告警(日志 WARN + 进入世界时聊天框提示), 其余规则照常生效。
filterRules = []
#Exact message strings to filter (case-sensitive)
#精确匹配并过滤的消息字符串(区分大小写)
exactMatches = []
#Logger names to completely filter (e.g., 'net.minecraft.server.MinecraftServer')
#完全过滤的 Logger 名称(例如 'net.minecraft.server.MinecraftServer')
loggerNames = []
#Log levels to filter: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
#要过滤的日志级别: TRACE, DEBUG, INFO, WARN, ERROR, FATAL
logLevels = ["TRACE", "DEBUG"]
#Regex patterns that will EXCLUDE logs from filtering (whitelist)
#Regex/TOML escaping rules are the same as filterRules (see its comment above).
#将日志排除在过滤之外的正则表达式(白名单)
#正则与 TOML 的转义规则与 filterRules 相同(见其上方注释)。
excludePatterns = []
[async]
#Enable async log output: wraps all root appenders into a Log4j2 AsyncAppender so console/file I/O runs on a background thread instead of the logging thread
#启用异步日志输出: 将 root logger 的全部 appender 包装进 Log4j2 AsyncAppender, 控制台/文件 I/O 转移到后台线程执行, 打日志的线程只付入队成本
enableAsyncLogging = true
#Capacity of the async queue (number of buffered log events)
#异步队列容量(缓冲的日志事件数量)
#Range: 128 ~ 65536
asyncQueueSize = 4096
#When queue is full: true = briefly block the logging thread (no log loss), false = drop the log event
#队列满时: true = 短暂阻塞打日志线程(不丢日志), false = 丢弃该条日志事件
asyncBlockingWhenFull = true
#Milliseconds to wait for the queue to drain before discarding remaining events (on pipeline rebuild and JVM shutdown)
#等待队列排干的毫秒数, 超时后丢弃剩余事件(在管线重建与 JVM 关闭时生效)
#Range: 0 ~ 600000
asyncShutdownTimeoutMs = 5000
#Capture caller location (class/method/line). Costs a stack walk per event; Minecraft's default log pattern does not need it
#捕获调用方位置(类/方法/行号)。每条日志付出一次栈遍历成本; Minecraft 默认日志格式用不到它, 保持 false 即可
asyncIncludeLocation = false
#Fully qualified class name of a org.apache.logging.log4j.core.async.BlockingQueueFactory implementation (empty = default ArrayBlockingQueue). Upgrade hook: a Disruptor-based factory can be injected later via JarJar without code changes
#BlockingQueueFactory 实现类的全限定名(留空 = 默认 ArrayBlockingQueue)。升级钩子: 后续可通过 JarJar 注入 Disruptor 队列工厂而无需改代码
asyncQueueFactoryClass = ""
General (General Settings)
| Option |
Default |
Description |
enableFilter |
true |
Whether to enable the log filtering function. |
debugMode |
false |
Enable debug mode to print filtered logs to the console, convenient for testing rules. |
maxCacheSize |
1000 |
The cache size for filtered logs, used for deduplication. |
FilterRules (Filtering Rules)
1. filterRules (Regex)
Use regex to match logs to be filtered.
filterRules = [
".*Exception.*", # Filter out all logs containing "Exception"
".*stack trace.*", # Filter out stack traces
".*Could not pass event.*"# Filter out specific event errors
]
⚠ Common Pitfall: Regex Metacharacters & Double TOML Escaping
- Regex layer:
()[]{}*+?.^$|\ are regex metacharacters; escape them for literal matching. E.g. the parentheses in log some (thing) must be written as \(thing\) — otherwise they are parsed as a capture group and the rule silently never matches (the regex itself is valid, no error is shown).
- TOML layer: inside double-quoted strings TOML consumes one level of backslashes, so double them up:
"some \\(thing\\)"; single-quoted literal strings are recommended (no TOML escaping needed): 'some \(thing\)'.
- Match semantics:
filterRules uses partial matching (find); a rule hits if it matches any part of the message, so no .* wrapping is needed.
- Invalid regex (e.g. unbalanced parentheses) is safely skipped: a WARN is written to the log and an in-game chat warning appears when you enter a world; all other rules keep working — no startup crash. Validate rules at regex101.com (Java flavor) first.
2. exactMatches (Exact Match)
Logs are filtered only when their content is exactly identical (case-sensitive).
exactMatches = [
"This message will be completely filtered out"
]
3. loggerNames (Logger Names)
Filter based on the source of the log (class name or mod package name). Supports hierarchical filtering.
loggerNames = [
"net.minecraft.server.MinecraftServer", # Filter out logs from the main server
"com.some.noisy.mod" # Filter out all logs from a noisy mod
]
4. logLevels (Log Levels)
Filter based on log level. Available values: TRACE, DEBUG, INFO, WARN, ERROR, FATAL.
logLevels = [
"TRACE",
"DEBUG"
]
5. excludePatterns (Whitelist/Exclusion Rules)
Very Important. Logs matching rules here will not be filtered, even if other rules match them. Used to retain critical errors.
excludePatterns = [
".*CRITICAL ERROR.*", # Even if it matches Exception, if it is a CRITICAL ERROR, keep it
".*IMPORTANT.*"
]
? Build
If you want to compile this mod yourself:
./gradlew build
The compiled JAR file is located in the build/libs/ directory.
Deep Dive
Part 1: How it works at the mod code level
The core idea of this mod is interception. It "hijacks" the data before Minecraft's log output reaches the console or files, deciding whether to let it pass or discard it.
1. Log Framework Basics: Log4j 2
Minecraft 1.20.1 uses the Log4j 2 logging framework.
- Log Flow: Game code generates log events (
LogEvent) -> Passes to Log4j's LoggerContext -> Passes to Appender (e.g., console appender, file writer) -> Finally displayed on the screen.
- Filter Mechanism: Log4j allows mounting "filters (
Filter)" on Loggers or Appenders.
- Async Output Pipeline: all appenders on the root logger are wrapped into a Log4j2
AsyncAppender (enabled by default, configurable): console/file I/O runs on a background thread, the logging thread only pays the enqueue cost; queue size and overflow policy are configurable.
2. Code Execution Flow
Our mod performs the following operations via LogFilterManager.java when the game starts (FMLCommonSetupEvent):
-
Get Context:
LoggerContext loggerContext = LoggerContext.getContext(false);
We obtained Minecraft's current log environment context.
-
Get Root Configuration:
Configuration configuration = loggerContext.getConfiguration();
LoggerConfig rootLoggerConfig = configuration.getRootLogger();
We got the configuration of the "Root Logger". Since almost all logs eventually flow to the Root Logger, mounting a filter here can capture global logs.
-
Register Custom Filter:
log4jFilter = new FilteringLogFilter(); // Our custom filter class
log4jFilter.start();
rootLoggerConfig.addFilter(log4jFilter);
We inserted our custom FilteringLogFilter at the very front of the log processing chain.
7. Interception and Decision Making (FilteringLogFilter.filter method):
Whenever Minecraft attempts to output a log line, Log4j invokes our filter(LogEvent event) method. To prevent game stuttering caused by log filtering, we adopt a "fail-fast" design, with the following logic priority:
* Step A: Extract Key Information. Directly extract key details such as the Logger name and level from the Log4j LogEvent.
* Step B: Quick Check (Level & Logger). Prioritize checking the log level (logLevels) and Logger name (loggerNames). This is an extremely low-overhead operation. If a match is found, the log is discarded immediately, completely skipping the expensive message formatting and regex matching that follows, significantly reducing main thread overhead.
* Step C: Message Formatting. Only when a log passes the quick check and is not intercepted will getFormattedMessage() be called to generate the message text.
* Step D: Cache Check. Calculate the hash value of the log content to check if it exists in the cache. If it does, return DENY immediately to avoid redundant computation.
* Step E: Whitelist Check (excludePatterns). If the log matches a whitelist regex, return NEUTRAL. The whitelist has the highest priority and is used to protect important logs.
* Step F: Exact Match Check (exactMatches). If the log message matches a configured string exactly, return DENY.
* Step G: Regex Rule Check (filterRules). If the log message matches a configured regular expression, return DENY.
- Final Verdict:
- If any of the above interception conditions match, we return
Result.DENY. Upon receiving DENY, Log4j immediately discards the log, and it will not appear in the console or file.
- If none match, we return
Result.NEUTRAL. Log4j considers the filter to have "no opinion" and continues to pass the log to the next processor, eventually displaying it normally.
- Config Hot-Reload: after you edit and save
logfilter-common.toml, Forge's config file watcher immediately fires the reload event: the async pipeline rebuilds idempotently (skipped if parameters unchanged), filter rules recompile, invalid regexes are skipped with warnings — no game restart needed, all event-driven.
Part 2: Practical Case Analysis and Configuration
Let's look at this log:
[241... 00:32:22.574] [Render thread/WARN] [net.minecraft.client.renderer.ShaderInstance/]: Shader rendertype_entity_translucent_emissive could not find sampler named Sampler2 in the specified shader program.
1. Log Entry Dissection
We need to break down this log into several key parts:
| Log Fragment |
Meaning |
Corresponding Config Item |
Note |
WARN |
Log Level |
logLevels |
Indicates this is a warning, not an error or info. |
net.minecraft.client.renderer.ShaderInstance |
Logger Name |
loggerNames |
The fully qualified name of the Java class that emitted this log. |
Shader ... program. |
Log Message |
filterRules, exactMatches |
The specific error content. |
2. How to determine which configuration item it belongs to?
- If you want to block all messages emitted by a certain class/mod (e.g., I'm tired of seeing all errors from this Shader class), you should use
loggerNames.
- If you want to block all messages of a certain level (e.g., I don't want to see any WARN level messages), you should use
logLevels.
- If you want to precisely block this one sentence (even if it only appears once), you should use
exactMatches.
- If you want to fuzzily block this type of error (e.g., regardless of whether it can't find Sampler1 or Sampler2, or which Shader it is, just block it if it's "cannot find sampler"), you should use
filterRules.
3. Practical Configuration Solutions
For this specific Shader error, we have four filtering strategies. Please choose according to your needs:
Solution A: Precisely filter this error (Recommended - Use filterRules)
The core feature of this log is "cannot find sampler". We can write a regular expression that covers all cases where a sampler is not found, without affecting other logs.
Applicable Scenario: You consider all warnings about missing shader samplers to be irrelevant and want to block them all.
Configuration Code:
# Explanation: .* means any character, matching all logs containing "could not find sampler named", regardless of what comes before or after.
filterRules = [".*could not find sampler named.*"]
Solution B: Only block this specific long sentence (Use exactMatches)
If you only want to block the specific warning about Sampler2 not being found, but keep other Shader warnings.
Applicable Scenario: Extremely precise strike, no collateral damage.
Configuration Code:
# Must be exactly the same as the text in the log (usually excluding timestamp and thread name, only including the content after the colon)
exactMatches = ["Shader rendertype_entity_translucent_emissive could not find sampler named Sampler2 in the specified shader program."]
Solution C: Block all logs from the ShaderInstance class (Use loggerNames)
If the ShaderInstance class is very noisy and you don't want to see anything it outputs at all.
Applicable Scenario: Aggressive filtering. Warning: If this class outputs serious error logs later, you won't see them either.
Configuration Code:
# As long as the log source is net.minecraft.client.renderer.ShaderInstance, block everything.
loggerNames = ["net.minecraft.client.renderer.ShaderInstance"]
Solution D: Block all WARN level logs (Use logLevels)
Applicable Scenario: Not Recommended. This will block all warning messages, potentially causing you to miss potential issues that really need attention.
Configuration Code:
logLevels = ["WARN"]
评论 0
登录后参与评分
还没有评论,来抢沙发吧