javaloggingconfigurationlog4j2pattern-layout

Limit Max Message Size in log4j has no effect


I have read this question Limit max message size in log4j2 pattern.

I am using %.-1000mto limit number of characters in my message event. For some reason this has no effect.

<?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>

I tried to change various values for %m and it does not have an effect.


Solution

  • I tested your pattern locally (with version 2.24.1) and %.-1000m works correctly! Did you count the size correctly? This limits the size of the "message" key only (the exception, which usually is longer, is unconstrained). The limit is applied before JSON encoding, so the effective number of characters might be greater.

    Remarks: Even if your example works correcly (provided you set alwaysWriteExceptions to false) you should consider switching to JSON Template Layout.

    The Pattern Layout is not conceived to output structured formats, but text. A simple LF in some fields that you didn't escape (like the thread name), will break your output. Rather than playing with fire:

    <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"
          }
        }
      }'/>