How to use pid as key for log4j2 Kafka appender?

Viewed 332

I am trying to send logs to Kafka and I would like to have the process id as the key for the log message.

I found that the key in Kafka appender supports lookups. But how can I use pid in the key field just as I have done in the PatternLayout.

<Appenders>
    <Console name="console" target="SYSTEM_OUT">
        <PatternLayout
            pattern="[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
    </Console>
    <Kafka name="Kafka" topic="my_log_topic" key="%processId">
        <PatternLayout pattern="[%-5level] %processId  %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
        <Property name="bootstrap.servers">127.0.0.1:9092</Property>
    </Kafka>
</Appenders>

Can we use patterns in the key field? Or is there any way to get the PID in the lookup?

1 Answers

Adding the following line in main() worked fine.

ProcessIdUtil is found in org.apache.logging.log4j.util package.

System.setProperty("pid", ProcessIdUtil.getProcessId());

and then use key="${sys:pid}"

<Kafka name="Kafka" topic="my_log_topic" key="${sys:pid}">
    <PatternLayout pattern="[%-5level] %processId  %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n" />
    <Property name="bootstrap.servers">127.0.0.1:9092</Property>
</Kafka>

Is there a better way, without changing the code?

Related