<?xml version="1.0" encoding="UTF-8"?>
<!--
  Console plus a size-and-time rolling file.

  Without this the application logs to the console only, and in Docker that goes
  to the json-file driver, which is unbounded by default: on a long-running box
  the log grows until the disk is full and Postgres can no longer write. Rotation
  is configured here *and* on the Docker side (see the deployment guide), because
  either one alone still leaves the other stream unbounded.

  Every line carries a request id so one user's actions can be followed across
  threads — see RequestIdFilter, which puts it in the MDC.
-->
<configuration>
    <include resource="org/springframework/boot/logging/logback/defaults.xml"/>

    <springProperty scope="context" name="LOG_DIR" source="app.logging.dir" defaultValue="./logs"/>
    <springProperty scope="context" name="LOG_MAX_HISTORY" source="app.logging.max-history-days" defaultValue="14"/>
    <springProperty scope="context" name="LOG_TOTAL_CAP" source="app.logging.total-size-cap" defaultValue="1GB"/>

    <!-- reqId is blank for background work (async audit writes, screening). -->
    <property name="PATTERN"
              value="%d{yyyy-MM-dd HH:mm:ss.SSS} %-5level [%X{reqId:-}] [%X{userId:-}] %logger{36} - %msg%n"/>

    <appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
        <encoder>
            <pattern>${PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_DIR}/shodh-api.log</file>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_DIR}/shodh-api.%d{yyyy-MM-dd}.%i.log.gz</fileNamePattern>
            <maxFileSize>50MB</maxFileSize>
            <maxHistory>${LOG_MAX_HISTORY}</maxHistory>
            <!-- Hard ceiling: oldest archives are deleted past this, so the log
                 directory can never grow without bound however chatty things get. -->
            <totalSizeCap>${LOG_TOTAL_CAP}</totalSizeCap>
        </rollingPolicy>
        <encoder>
            <pattern>${PATTERN}</pattern>
            <charset>UTF-8</charset>
        </encoder>
    </appender>

    <!-- Non-blocking so a slow disk cannot stall request threads. discardingThreshold
         0 keeps INFO lines instead of dropping them when the queue gets full. -->
    <appender name="ASYNC_FILE" class="ch.qos.logback.classic.AsyncAppender">
        <queueSize>1024</queueSize>
        <discardingThreshold>0</discardingThreshold>
        <appender-ref ref="FILE"/>
    </appender>

    <logger name="com.shodh.sanchayan" level="INFO"/>
    <logger name="org.springframework.security" level="INFO"/>
    <logger name="org.hibernate.SQL" level="WARN"/>

    <root level="INFO">
        <appender-ref ref="CONSOLE"/>
        <appender-ref ref="ASYNC_FILE"/>
    </root>
</configuration>
