Logback:同时按照日期和大小分割日志(最新日志可以不带日期或数字)

Maven坐标

<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-core</artifactId>
  <version>1.1.11</version>
</dependency>
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-classic</artifactId>
  <version>1.1.11</version>
</dependency>
<dependency>
  <groupId>ch.qos.logback</groupId>
  <artifactId>logback-access</artifactId>
  <version>1.1.11</version>
</dependency>

 

官网说明:Size and time based rolling policy

Sometimes you may wish to archive files essentially by date but at the same time limit the size of each log file, in particular if post-processing tools impose size limits on the log files. In order to address this requirement, logback ships with SizeAndTimeBasedRollingPolicy.

有时候你本来是希望按照日期来对日志进行归档,但是同时你又希望限制每个日志文件的大小,为了满足这一需求,logback提供了SizeAndTimeBasedRollingPolicy.

Note that TimeBasedRollingPolicy already allows limiting the combined size of archived log files. If you only wish to limit the combined size of log archives, then TimeBasedRollingPolicy described above and setting the totalSizeCap property should be amply sufficent.

注意,TimeBasedRollingPolicy已经允许限制合并归档日志文件的大小。如果你只希望限制合并归档日志的大小,TimeBasedRollingPolicy中设置totalSizeCap即可:

Here is a sample configuration file demonstrating time and size based log file archiving.

Example: Sample configuration for SizeAndTimeBasedFNATP (logback-examples/src/main/resources/chapters/appenders/conf/logback-sizeAndTime.xml)

下面是一个示例配置文件说明基于时间和大小的日志文件归档。      

View as .groovy

<configuration>
  <appender name="ROLLING" class="ch.qos.logback.core.rolling.RollingFileAppender">
    <file>mylog.txt</file>
    <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
      <!-- rollover daily -->
      <fileNamePattern>mylog-%d{yyyy-MM-dd}.%i.txt</fileNamePattern>
       <!-- each file should be at most 100MB, keep 60 days worth of history, but at most 20GB -->
       <maxFileSize>100MB</maxFileSize>    
       <maxHistory>60</maxHistory>
       <totalSizeCap>20GB</totalSizeCap>
    </rollingPolicy>
    <encoder>
      <pattern>%msg%n</pattern>
    </encoder>
  </appender>


  <root level="DEBUG">
    <appender-ref ref="ROLLING" />
  </root>

</configuration>

Note the "%i" conversion token in addition to "%d". Both the %i and %d tokens are mandatory. Each time the current log file reaches maxFileSize before the current time period ends, it will be archived with an increasing index, starting at 0.

注意:“%i"”转换标记除了“% d”。%i"和% d令牌都是强制性的。每次当前日志文件之前到达maxFileSize当前时间段结束时,它将存档增加索引从0开始。

Size and time based archiving supports deletion of old archive files. You need to specify the number of periods to preserve with the maxHistory property. When your application is stopped and restarted, logging will continue at the correct location, i.e. at the largest index number for the current period.

基于大小和时间的归档支持删除旧存档文件。您需要指定使用maxHistory属性保留的时期数量。当应用程序停止并重新启动时,日志记录将在正确的位置继续,即当前期间的最大索引号。

In versions prior to 1.1.7, this document mentioned a component called SizeAndTimeBasedFNATP. However, given that SizeAndTimeBasedFNATP offers a simpler configuration structure, we no longer document SizeAndTimeBasedFNATP. Nevertheless, earlier configuration files using SizeAndTimeBasedFNATP will continue to work just fine. In fact,SizeAndTimeBasedRollingPolicy is implemented with a SizeAndTimeBasedFNATP subcomponent.

 

在1.1.7之前的版本中,本文档提到了一个名为SizeAndTimeBasedFNATP的组件。但是,考虑到SizeAndTimeBasedFNATP提供了更简单的配置结构,我们不再记录SizeAndTimeBasedFNATP。不过,使用SizeAndTimeBasedFNATP的早期配置文件将继续正常工作。实际上,SizeAndTimeBasedRollingPolicy是用SizeAndTimeBasedFNATP子组件实现的。

Logback.xml:同时按照日期和大小分割日志

有两种形式:
最新的日志,是日期最大数字最大的
最新的日志,是没有日期没有数字的
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">
    <!--定义日志文件的存储地址 -->
    <property name="LOG_HOME" value="/usr/local/java/tomcat-log/项目名" />

    <!-- 控制台输出 -->
    <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
    </appender>

    <!-- 按照每天和固定大小(5MB)生成日志文件【最新的日志,是日期最大数字最大的】 -->
   <!-- <appender name="FILE"  class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            &lt;!&ndash;日志文件输出的文件名&ndash;&gt;
            <FileNamePattern>${LOG_HOME}/项目名_%d{yyyy-MM-dd}.%i.log</FileNamePattern>
            &lt;!&ndash;日志文件保留天数&ndash;&gt;
            <MaxHistory>30</MaxHistory>
            &lt;!&ndash;日志文件最大的大小&ndash;&gt;
            <MaxFileSize>5MB</MaxFileSize>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            &lt;!&ndash;格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符&ndash;&gt;
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        &lt;!&ndash;日志文件最大的大小&ndash;&gt;
        &lt;!&ndash;<triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            &lt;!&ndash;<MaxFileSize>5MB</MaxFileSize>&ndash;&gt;
            <MaxFileSize>5KB</MaxFileSize>
        </triggeringPolicy>&ndash;&gt;
    </appender>-->

    <!-- 按照每天和固定大小(5MB)生成日志文件【最新的日志,是没有日期没有数字的】 -->
    <appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>${LOG_HOME}/项目名.log</file>
        <append>true</append>
        <rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
            <fileNamePattern>${LOG_HOME}/项目名_%d{yyyy-MM-dd}.%i.log</fileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
            <!--日志文件最大的大小-->
            <MaxFileSize>5MB</MaxFileSize>
        </rollingPolicy>
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
       <!-- <filter class="ch.qos.logback.classic.filter.LevelFilter">
            <level>TRACE</level>
            <onMatch>ACCEPT</onMatch>
            <onMismatch>DENY</onMismatch>
        </filter>-->
    </appender>

    <!-- show parameters for hibernate sql 专为 Hibernate 定制 -->
    <logger name="org.hibernate.type.descriptor.sql.BasicBinder"  level="WARN" />
    <logger name="org.hibernate.type.descriptor.sql.BasicExtractor"  level="WARN" />
    <logger name="org.hibernate.SQL" level="WARN" />
    <logger name="org.hibernate.engine.QueryParameters" level="WARN" />
    <logger name="org.hibernate.engine.query.HQLQueryPlan" level="WARN" />

    <!--myibatis log configure-->
    <logger name="com.apache.ibatis" level="WARN"/>
    <logger name="java.sql.Connection" level="WARN"/>
    <logger name="java.sql.Statement" level="WARN"/>
    <logger name="java.sql.PreparedStatement" level="WARN"/>


    <!--newcapec-->
    <logger name="com.newcapec" level="INFO"/>

    <!-- 日志输出级别 -->
    <root level="INFO">
        <appender-ref ref="STDOUT" />
        <appender-ref ref="FILE" />
    </root>

    <!--日志异步到数据库 -->
    <!--<appender name="DB" class="ch.qos.logback.classic.db.DBAppender">-->
    <!--&lt;!&ndash;日志异步到数据库 &ndash;&gt;-->
    <!--<connectionSource class="ch.qos.logback.core.db.DriverManagerConnectionSource">-->
    <!--&lt;!&ndash;连接池 &ndash;&gt;-->
    <!--<dataSource class="com.mchange.v2.c3p0.ComboPooledDataSource">-->
    <!--<driverClass>com.mysql.jdbc.Driver</driverClass>-->
    <!--<url>jdbc:mysql://127.0.0.1:3306/databaseName</url>-->
    <!--<user>root</user>-->
    <!--<password>root</password>-->
    <!--</dataSource>-->
    <!--</connectionSource>-->
    <!--</appender>-->
</configuration>

最新的日志,是日期最大数字最大的

最新的日志,是没有日期没有数字的

Java程序使用

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

private final Logger log = LoggerFactory.getLogger(this.getClass());

 

默认情况下,logback框架并不直接支持按照日志文件大小来进行分割。然而,你可以通过重写SizeAndTimeBasedFNATP类来实现按照大小分割的方式。 你可以在logback.xml配置文件中使用自定义的SizeAndTimeBasedFNATP类来替代默认的分割方式。在配置文件中,你需要设置最大的日志文件大小,并指定分割后的文件名格式。同时,你还可以配置最多保存多少个文件以及是否压缩旧的日志文件等参数。这样就可以实现按照日志文件大小分割日志了。在使用Spring Boot时,你可以在application.yml配置文件中指定logback的配置文件路径,例如:logging.config: classpath:logback.xml。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* [logback按照文件大小切割日志](https://blog.csdn.net/Aruis26/article/details/89260192)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *3* [logback配置按日期,按文件大小分隔日志文件](https://blog.csdn.net/HuanBuXingDeXingXing/article/details/115355304)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v92^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

琦彦

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值