log4j2 按天分日志

时间:2021-01-25 21:49:12

log4j2的按天分日志文件


    	<RollingFile name="error_appender" fileName="${LOG_HOME}/error.log" filePattern="${LOG_HOME}/error-%d{yyyy-MM-dd}.log">
    		<PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss} [%thread] %m%n"/>
    		<Policies>
    			<TimeBasedTriggeringPolicy modulate="true" interval="1"/>
    		</Policies>
    	</RollingFile>


按大小分

    	<RollingFile name="error_appender" fileName="${LOG_HOME}/error.log" filePattern="${LOG_HOME}/error-%d{yyyy-MM-dd}-%i.log.gz">
    		<PatternLayout pattern="%-d{yyyy-MM-dd HH:mm:ss} [%thread] %m%n"/>
    		<SizeBasedTriggeringPolicy size="100 MB" />
    	</RollingFile>


按分钟分

    	<RollingRandomAccessFile name="_1min_appender" fileName="${MINUTE_HOME}/minute" filePattern="${MINUTE_HOME}/minute-%d{yyyy-MM-dd-HH-mm}.log">
    		<PatternLayout pattern="%m%n"/>
    		<Policies>
				<TimeBasedTriggeringPolicy interval="1" modulate="true" />
			</Policies>
    	</RollingRandomAccessFile>

关键点在于 filePattern后的日期格式,以及TimeBasedTriggeringPolicy的interval,日期格式精确到哪一位,interval也精确到哪一个单位


log4j2 设置同一类型日志文件个数


<Appenders>
    <Console name="Console" target="SYSTEM_OUT">
         <PatternLayout pattern="[%-5p] %d %c - %m%n" />
    </Console>
    <File name="File" fileName="dist/my.log">
         <PatternLayout pattern="%m%n" />
    </File>
    <RollingFile name="RollingFile" fileName="dist/my2.log"

        filePattern="dist/$${date:yyyy-MM}/app-%d{MM-dd-yyyy}-%i.log.gz">
        <PatternLayout pattern="[%-5p] %d %c - %m%n" />
        <Policies>
            <TimeBasedTriggeringPolicy />
            <SizeBasedTriggeringPolicy size="25 KB" />
        </Policies>
        <DefaultRolloverStrategy max="20"/>
    </RollingFile>
</Appenders>



关键在于 <DefaultRolloverStrategy max="20"/>,如果不做配置,默认是7,这个7指的是上面i的最大值,超过了就会覆盖之前的