Write logs from existing log4j appenders all logs

2019-08-21 05:55发布

In our java project, we send logs to all kinds of appenders. How do I log to rsyslog all logs that are written to those appenders from "error" level and higher by only changing configuration files such as log4j.xml (without meddling with the code)?

in How to log error and info messages separately into syslog with log4j?, there is an explanation how to create a new appender, and from my understanding to follow up with that answer I need to touch the code.

my log4j version is: 2.4.1 Here is a small log4j.xml for one of the machines we wrote:

<?xml version="1.0" encoding="UTF-8"?>
<Configuration status="warn" monitorInterval="5">
  <Appenders>
      <RollingRandomAccessFile name="RollingRandomAccessFile" fileName="log/la.full.log" filePattern="log/la.full.%d{yy-dd-MM}.%i.log">
      <PatternLayout>
        <Pattern>%highlight{%d{DEFAULT}|%5p|%6t|%X|%m%n}</Pattern>
      </PatternLayout>
      <Policies>
        <TimeBasedTriggeringPolicy />
        <SizeBasedTriggeringPolicy size="10 MB"/>
      </Policies>
      <DefaultRolloverStrategy max="100"/>
    </RollingRandomAccessFile>
    <Console name="STDOUT" target="SYSTEM_OUT">
     <PatternLayout pattern="%highlight{%d{DEFAULT}|%5p|%6t|%X|%m%n}"/>
   </Console>
  </Appenders>
  <Loggers>
    <Root level="debug" additivity="false">
      <AppenderRef ref="STDOUT" level="DEBUG"/>
      <AppenderRef ref="RollingRandomAccessFile" level="DEBUG"/>
    </Root>
  </Loggers>
</Configuration>

1条回答
聊天终结者
2楼-- · 2019-08-21 06:47

Given you add an Appender for rsyslog ( which should be available from somewhere on the internet if not already built-in ) you just would add another appender-ref:

<Loggers>
    <Root level="debug" additivity="false">
      <AppenderRef ref="STDOUT" level="DEBUG"/>
      <AppenderRef ref="RollingRandomAccessFile" level="DEBUG"/>
      <AppenderRef ref="RSYSLOG" level="ERROR"/>
    </Root>
</Loggers>

Concerning loglevel: Setting the level on Root logger will "filter" the messages going through to debug and higher ( debug, info, error, ... ). Setting it also on the appender will further filter to that level (or higher). So if you set the level property on the appender-ref to "error" (as shown above) it will only get messages in level error and higher. The other appender won't be affected by that and still log debug and info messages.

查看更多
登录 后发表回答