简体   繁体   中英

java logback different log level for different tenants

Currently I'm using logback MDC to set different tenants. But I wish to have different log levels for different tenants.

<?xml version="1.0" encoding="UTF-8"?>
<configuration scan="true">

    <appender name="TENANT-THREAD" class="ch.qos.logback.classic.sift.SiftingAppender">

        <discriminator>
            <key>tenantName</key>
            <defaultValue>MYAPP</defaultValue>
        </discriminator>

        <sift>

          <appender name="FILE-${tenantName}"
            class="ch.qos.logback.core.rolling.RollingFileAppender">
            <file>${logPath}/${tenantName}.log</file>

            <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
                <Pattern>
                    %d{yyyy-MM-dd HH:mm:ss} %mdc [%thread] %level %logger{35} - %msg%n
                </Pattern>
            </encoder>
          </appender>

        </sift>
    </appender>

    <root level="DEBUG">
        <appender-ref ref="TENANT-THREAD"/>
    </root>
</configuration>


MDC.put("tenantName", tenantName);
MDC.remove("tenantName");

Is it possible to set different log level for different tenants programmatically?

To change log level programmatically use:

Logger root = (Logger)LoggerFactory.getLogger(Logger.ROOT_LOGGER_NAME);
root.setLevel(Level.INFO);

Level.INFO being the selected level

The following steps can be done by wrapping the logger through a custom TenantLogger

  1. Get the logger
  2. Get the tenant log configuration from the database table based on the module and cache in the service.
  3. log the message based on the level as per the configuration obtained from the database (step 2)
  4. if the corresponding level is not configured for the tenant, the message can be skipped from logging

This would need a separate table like TenantLoggingConfig which would contain columns like TenantId , ModuleId , LogLevel etc.

You can have modules like customer, orders, products etc. In case of microservices, this is simple in the sense that each microservice contains only its modules.

kindly share your thoughts on this or if you prefer any alternative approach.

You can use following steps to achieve the same

  • Set tenant Name in MDC
  • Provide a custom filter that extends ch.qos.logback.classic.turbo.DynamicThresholdFilter
  • Update TurboFilters with your filter LoggerContext#getTurboFilterList#add

Hope you find this helpful

vp

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM