限制 log4j 中的最大消息大小没有效果

问题描述 投票:0回答:1

我已经读过这个问题Limit max message size in log4j2 pattern

我使用

%.-1000m
来限制消息事件中的字符数。 由于某种原因,这没有效果。

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="WARN">
    <Properties>
        <Property name="log-path">${sys:root}/var/output/logs</Property>
    </Properties>
    <Appenders>

        <Socket name="ApplicationTcp" host="localhost" port="5170" ignoreExceptions="false">

                     to reduce logging volume. -->
                <Pattern>{ "timestamp": "%d{ISO8601}", "logger": "%c","threadName": "%t"%notEmpty{, "requestId": "%X{RequestId}"}%notEmpty{, "message": "%enc{%.-1000m{nolookups}}{JSON}"}%notEmpty{, "exception": "%enc{%ex{full}}{JSON}"} }%n</Pattern>
            </PatternLayout>
        </Socket>


...
            </PatternLayout>
        </Socket>
    </Appenders>

我尝试更改 %m 的各种值,但没有效果。

java logging configuration log4j2 pattern-layout
1个回答
0
投票

我在本地测试了您的模式(使用版本

2.24.1
)并且
%.-1000m
工作正常!你计算的尺寸正确吗?这仅限制“消息”键的大小(例外情况,通常较长,不受限制)。该限制在 JSON 编码之前应用,因此有效字符数可能会更长。

备注

:即使您的示例正确运行(假设您将 alwaysWriteExceptions 设置为

false
),您也应该考虑切换到 
JSON 模板布局 Pattern Layout 的目的不是输出结构化格式,而是文本。在某些您

没有

转义的字段(例如线程名称)中,一个简单的

LF
将会破坏您的输出。而不是玩火:

    log4j-layout-template-json
  • 添加到您的依赖项,如
    Usage
    , 中所述 使用等效的 JTL 配置并将
  • maxStringLength 配置属性
     设置为您喜欢的值:
  • <JsonTemplateLayout maxStringLength="500" eventTemplate=' { "timestamp": { "$resolver": "timestamp", "pattern": { "format": "yyyy-MM-dd&apos;T&apos;HH:mm:ss.SSS&apos;Z&apos;", "timeZone": "UTC" } }, "logger": { "$resolver": "logger", "field": "name" }, "threadName": { "$resolver": "thread", "field": "name" }, "requestId": { "$resolver": "mdc", "key": "requestId" }, "message": { "$resolver": "message" }, "exception": { "type": { "$resolver": "exception", "field": "className" }, "message": { "$resolver": "exception", "field": "message" }, "stackTrace": { "$resolver": "exception", "field": "stackTrace" } } }'/>
	
© www.soinside.com 2019 - 2024. All rights reserved.