我有一个具有多租户支持的应用程序,即一个服务器和多个DB,每个租户都会有单独的DB。应用程序中抛出的所有异常都将记录在一个日志中。 tenantID将与例外一起打印。
我想在单独的文件中处理它,即每个租户都有一个单独的日志文件。这将有助于识别由于属于特定租户的用户所做的活动而导致此异常。是否有可能使用自定义ObjectRenderer
或任何其他技术实现此目的。提前谢谢。
答案 0 :(得分:4)
我的建议是创建自己的Appenders
。在自定义Appenders
中,您可以执行任何您想要的操作,例如单独的日志文件等。,
参考: How to create a own Appender in log4j? http://logging.apache.org/log4j/2.x/manual/extending.html
答案 1 :(得分:2)
I would suggest you to use logback with MDC.
See documentation at
I was using request response filter, where in the request filter I would add the tenantId
to MDC context reading the value from request object and remove it from MDC in the response filter.
And in the logback configuration, configured filename as,
<file>${FILE_PATH}/${tenantId}.log</file>
specifying discriminator as,
<discriminator>
<key>tenantId</key>
<defaultValue>defaultFileName</defaultValue>
</discriminator>
Here the logback treats tenantId
as discriminator and gets it from MDC Context, if it is unavailable it is set to default value.
Below is the complete configuration we are using,
<property name="USER_HOME" value="/home/logs" />
<appender name="FILE-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender">
<!-- This is MDC value -->
<!-- This is being set via request response filter via Java code -->
<discriminator>
<key>tenant</key>
<defaultValue>applyService</defaultValue>
</discriminator>
<sift>
<!-- A standard RollingFileAppender, the log file is based on 'logFileName' at runtime -->
<appender name="FILE-${tenant}"
class="ch.qos.logback.core.rolling.RollingFileAppender">
<file>${USER_HOME}/${tenant}.log</file>
<encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger:%line] [%mdc{tenant}] [%mdc{username}] - %msg%n
</Pattern>
</encoder>
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<!-- rollover daily -->
<fileNamePattern>${USER_HOME}/${tenant}-%d{yyyy-MM-dd}.%i.log.zip</fileNamePattern>
<!-- each file should be at most 10MB, keep 60 days worth of history-->
<maxFileSize>10MB</maxFileSize>
<maxHistory>60</maxHistory>
</rollingPolicy>
</appender>
</sift>
</appender>
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<layout class="ch.qos.logback.classic.PatternLayout">
<Pattern>
%d{yyyy-MM-dd HH:mm:ss} [%level] [%logger:%line] [%mdc{tenant}] [%mdc{username}] - %msg%n
</Pattern>
</layout>
</appender>
<logger name="com.test.client" level="debug" additivity="false">
<appender-ref ref="FILE-THREAD" />
</logger>
<root level="INFO">
<appender-ref ref="STDOUT" />
</root>