logback配置多个日志文件

使用场景

最近有个需求,要把记录sql的日志,与业务的分开.在业务中sql太多,在看日志的时候不方便.

使用

maven依赖

使用spring boot starter 里面包含了logback依赖,这里使用spring-boot-starter-web方便测试

<dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-web</artifactId>
</dependency>

配置

logback配置

  • 配置多个 appender,然后指定包的范围以及指定文件目录.达到sql与业务日志分开记录的目的
  • 具体例子
<?xml version="1.0" encoding="UTF-8"?>
<configuration debug="false">

    <!-- 业务日志 -->
    <appender name="APP_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>data/log/log.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <!--<encoder class="com.test.query.feign.rewrite.PatternLayoutEncoderReWrite">-->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <!--<pattern>%msg</pattern>-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- 只记录sql日志 -->
    <appender name="SQL_LOG" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <!--日志文件输出的文件名-->
            <FileNamePattern>data/log/log.sql@.%d{yyyy-MM-dd}.log</FileNamePattern>
            <!--<FileNamePattern>C:/logs/log.@build.finalName@.%d{yyyy-MM-dd}.log</FileNamePattern>-->
            <!--日志文件保留天数-->
            <MaxHistory>30</MaxHistory>
        </rollingPolicy>
        <!--<encoder class="com.test.query.feign.rewrite.PatternLayoutEncoderReWrite">-->
        <encoder class="ch.qos.logback.classic.encoder.PatternLayoutEncoder">
            <!--格式化输出:%d表示日期,%thread表示线程名,%-5level:级别从左显示5个字符宽度%msg:日志消息,%n是换行符-->
            <!--<pattern>%msg</pattern>-->
            <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{50} - %msg%n</pattern>
        </encoder>
        <!--日志文件最大的大小-->
        <triggeringPolicy class="ch.qos.logback.core.rolling.SizeBasedTriggeringPolicy">
            <MaxFileSize>10MB</MaxFileSize>
        </triggeringPolicy>
    </appender>

    <!-- 控制台输出 -->
    <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>

    <logger name="jdbc.sqlonly" level="INFO" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="SQL_LOG"/>
    </logger>

    <logger name="jdbc.resultset" level="ERROR" additivity="false">
        <appender-ref ref="STDOUT"/>
        <appender-ref ref="SQL_LOG"/>
    </logger>

    <logger name="jdbc.connection" level="OFF" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="jdbc.sqltiming" level="OFF" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="jdbc.audit" level="OFF" additivity="false">
        <appender-ref ref="STDOUT"/>
    </logger>

    <!--指定业务日志包范围-->
    <logger name="com.example" level="INFO" additivity="false">
        <appender-ref ref="APP_LOG"/>
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="com" level="INFO" additivity="false">
        <appender-ref ref="APP_LOG"/>
        <appender-ref ref="STDOUT"/>
    </logger>

    <logger name="org" level="INFO" additivity="false">
        <appender-ref ref="APP_LOG"/>
        <appender-ref ref="STDOUT"/>
    </logger>

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

</configuration>

测试

  • 项目启动,在启动时指定ddl-auto: update,在启动时候就会生成sql语句,并记录到SQL_LOGappender中.而启动日志等非sql,就会保存到APP_LOGappender中.

测试结果如下

  • 文件log.2018-08-23.log的日志
2018-08-23 13:35:43.006 [main] INFO  c.e.s.boot.logback.SpringExampleLogbackApplication - Starting SpringExampleLogbackApplication on macs-MacBook-Pro.local with PID 9199 (/Users/mac/code/github/spring-boot-example-logback/target/classes started by mac in /Users/mac/code/github/spring-boot-example-logback)
2018-08-23 13:35:43.010 [main] INFO  c.e.s.boot.logback.SpringExampleLogbackApplication - No active profile set, falling back to default profiles: default
2018-08-23 13:35:43.094 [main] INFO  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Refreshing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2b0f373b: startup date [Thu Aug 23 13:35:43 CST 2018]; root of context hierarchy
2018-08-23 13:35:43.933 [main] INFO  o.s.c.s.PostProcessorRegistrationDelegate$BeanPostProcessorChecker - Bean 'org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration' of type [org.springframework.transaction.annotation.ProxyTransactionManagementConfiguration$$EnhancerBySpringCGLIB$$92080d45] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
2018-08-23 13:35:44.297 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat initialized with port(s): 8080 (http)
2018-08-23 13:35:44.308 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Initializing ProtocolHandler ["http-nio-8080"]
2018-08-23 13:35:44.332 [main] INFO  org.apache.catalina.core.StandardService - Starting service [Tomcat]
2018-08-23 13:35:44.332 [main] INFO  org.apache.catalina.core.StandardEngine - Starting Servlet Engine: Apache Tomcat/8.5.32
2018-08-23 13:35:44.337 [localhost-startStop-1] INFO  org.apache.catalina.core.AprLifecycleListener - The APR based Apache Tomcat Native library which allows optimal performance in production environments was not found on the java.library.path: [/Users/mac/Library/Java/Extensions:/Library/Java/Extensions:/Network/Library/Java/Extensions:/System/Library/Java/Extensions:/usr/lib/java:.]
2018-08-23 13:35:44.407 [localhost-startStop-1] INFO  o.a.c.c.C.[.[.[/spring-boot-example-logback] - Initializing Spring embedded WebApplicationContext
2018-08-23 13:35:44.407 [localhost-startStop-1] INFO  org.springframework.web.context.ContextLoader - Root WebApplicationContext: initialization completed in 1313 ms
2018-08-23 13:35:44.465 [localhost-startStop-1] INFO  o.s.boot.web.servlet.ServletRegistrationBean - Servlet dispatcherServlet mapped to [/]
2018-08-23 13:35:44.469 [localhost-startStop-1] INFO  o.s.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'characterEncodingFilter' to: [/*]
2018-08-23 13:35:44.470 [localhost-startStop-1] INFO  o.s.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'hiddenHttpMethodFilter' to: [/*]
2018-08-23 13:35:44.470 [localhost-startStop-1] INFO  o.s.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'httpPutFormContentFilter' to: [/*]
2018-08-23 13:35:44.470 [localhost-startStop-1] INFO  o.s.boot.web.servlet.FilterRegistrationBean - Mapping filter: 'requestContextFilter' to: [/*]
2018-08-23 13:35:44.616 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Starting...
2018-08-23 13:35:44.687 [main] INFO  com.zaxxer.hikari.pool.PoolBase - HikariPool-1 - Driver does not support get/set network timeout for connections. (net.sf.log4jdbc.ConnectionSpy.getNetworkTimeout()I)
2018-08-23 13:35:44.756 [main] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Start completed.
2018-08-23 13:35:44.796 [main] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Building JPA container EntityManagerFactory for persistence unit 'default'
2018-08-23 13:35:44.806 [main] INFO  org.hibernate.jpa.internal.util.LogHelper - HHH000204: Processing PersistenceUnitInfo [
    name: default
    ...]
2018-08-23 13:35:44.868 [main] INFO  org.hibernate.Version - HHH000412: Hibernate Core {5.2.17.Final}
2018-08-23 13:35:44.869 [main] INFO  org.hibernate.cfg.Environment - HHH000206: hibernate.properties not found
2018-08-23 13:35:44.904 [main] INFO  org.hibernate.annotations.common.Version - HCANN000001: Hibernate Commons Annotations {5.0.1.Final}
2018-08-23 13:35:45.000 [main] INFO  org.hibernate.dialect.Dialect - HHH000400: Using dialect: org.hibernate.dialect.H2Dialect
2018-08-23 13:35:45.479 [main] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Initialized JPA EntityManagerFactory for persistence unit 'default'
2018-08-23 13:35:45.841 [main] INFO  o.s.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**/favicon.ico] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 13:35:46.069 [main] INFO  o.s.w.s.m.m.a.RequestMappingHandlerAdapter - Looking for @ControllerAdvice: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2b0f373b: startup date [Thu Aug 23 13:35:43 CST 2018]; root of context hierarchy
2018-08-23 13:35:46.102 [main] WARN  o.s.b.a.o.j.JpaBaseConfiguration$JpaWebConfiguration$JpaWebMvcConfiguration - spring.jpa.open-in-view is enabled by default. Therefore, database queries may be performed during view rendering. Explicitly configure spring.jpa.open-in-view to disable this warning
2018-08-23 13:35:46.137 [main] INFO  o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/user/{id}],methods=[GET]}" onto public org.springframework.http.ResponseEntity com.example.spring.boot.logback.controller.UserController.user(java.lang.Long)
2018-08-23 13:35:46.141 [main] INFO  o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error]}" onto public org.springframework.http.ResponseEntity<java.util.Map<java.lang.String, java.lang.Object>> org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.error(javax.servlet.http.HttpServletRequest)
2018-08-23 13:35:46.141 [main] INFO  o.s.w.s.m.m.a.RequestMappingHandlerMapping - Mapped "{[/error],produces=[text/html]}" onto public org.springframework.web.servlet.ModelAndView org.springframework.boot.autoconfigure.web.servlet.error.BasicErrorController.errorHtml(javax.servlet.http.HttpServletRequest,javax.servlet.http.HttpServletResponse)
2018-08-23 13:35:46.170 [main] INFO  o.s.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/webjars/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 13:35:46.170 [main] INFO  o.s.web.servlet.handler.SimpleUrlHandlerMapping - Mapped URL path [/**] onto handler of type [class org.springframework.web.servlet.resource.ResourceHttpRequestHandler]
2018-08-23 13:35:46.454 [main] INFO  o.s.jmx.export.annotation.AnnotationMBeanExporter - Registering beans for JMX exposure on startup
2018-08-23 13:35:46.456 [main] INFO  o.s.jmx.export.annotation.AnnotationMBeanExporter - Bean with name 'dataSource' has been autodetected for JMX exposure
2018-08-23 13:35:46.461 [main] INFO  o.s.jmx.export.annotation.AnnotationMBeanExporter - Located MBean 'dataSource': registering with JMX server as MBean [com.zaxxer.hikari:name=dataSource,type=HikariDataSource]
2018-08-23 13:35:46.471 [main] INFO  org.apache.coyote.http11.Http11NioProtocol - Starting ProtocolHandler ["http-nio-8080"]
2018-08-23 13:35:46.494 [main] INFO  org.apache.tomcat.util.net.NioSelectorPool - Using a shared selector for servlet write/read
2018-08-23 13:35:46.505 [main] INFO  o.s.boot.web.embedded.tomcat.TomcatWebServer - Tomcat started on port(s): 8080 (http) with context path '/spring-boot-example-logback'
2018-08-23 13:35:46.509 [main] INFO  c.e.s.boot.logback.SpringExampleLogbackApplication - Started SpringExampleLogbackApplication in 4.017 seconds (JVM running for 4.75)
2018-08-23 13:36:12.719 [http-nio-8080-exec-1] INFO  o.a.c.c.C.[.[.[/spring-boot-example-logback] - Initializing Spring FrameworkServlet 'dispatcherServlet'
2018-08-23 13:36:12.719 [http-nio-8080-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization started
2018-08-23 13:36:12.737 [http-nio-8080-exec-1] INFO  org.springframework.web.servlet.DispatcherServlet - FrameworkServlet 'dispatcherServlet': initialization completed in 18 ms
2018-08-23 13:36:12.769 [http-nio-8080-exec-1] INFO  c.e.spring.boot.logback.controller.UserController - user 1 
2018-08-23 13:36:12.968 [http-nio-8080-exec-2] INFO  c.e.spring.boot.logback.controller.UserController - user 1 
2018-08-23 13:46:16.180 [Thread-12] INFO  o.s.b.w.s.c.AnnotationConfigServletWebServerApplicationContext - Closing org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2b0f373b: startup date [Thu Aug 23 13:35:43 CST 2018]; root of context hierarchy
2018-08-23 13:46:16.185 [Thread-12] INFO  o.s.jmx.export.annotation.AnnotationMBeanExporter - Unregistering JMX-exposed beans on shutdown
2018-08-23 13:46:16.185 [Thread-12] INFO  o.s.jmx.export.annotation.AnnotationMBeanExporter - Unregistering JMX-exposed beans
2018-08-23 13:46:16.186 [Thread-12] INFO  o.s.orm.jpa.LocalContainerEntityManagerFactoryBean - Closing JPA EntityManagerFactory for persistence unit 'default'
2018-08-23 13:46:16.187 [Thread-12] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown initiated...
2018-08-23 13:46:16.189 [Thread-12] INFO  com.zaxxer.hikari.HikariDataSource - HikariPool-1 - Shutdown completed.

  • 文件 log.sql@.2018-08-23.log的日志
2018-08-23 13:35:45.417 [main] INFO  jdbc.sqlonly - select SEQUENCE_CATALOG, SEQUENCE_SCHEMA, SEQUENCE_NAME, INCREMENT from information_schema.sequences 

2018-08-23 13:35:45.470 [main] INFO  jdbc.sqlonly - create table user_entity (id bigint not null, user_name varchar(255), primary key (id)) 

2018-08-23 13:36:12.801 [http-nio-8080-exec-1] INFO  jdbc.sqlonly - select userentity0_.id as id1_0_0_, userentity0_.user_name as user_nam2_0_0_ from user_entity 
userentity0_ where userentity0_.id=1 

2018-08-23 13:36:12.969 [http-nio-8080-exec-2] INFO  jdbc.sqlonly - select userentity0_.id as id1_0_0_, userentity0_.user_name as user_nam2_0_0_ from user_entity 
userentity0_ where userentity0_.id=1 

最后发现sql与启动业务日志分离,测试成功

示例代码github地址

END

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 212,294评论 6 493
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 90,493评论 3 385
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 157,790评论 0 348
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 56,595评论 1 284
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 65,718评论 6 386
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 49,906评论 1 290
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 39,053评论 3 410
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 37,797评论 0 268
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 44,250评论 1 303
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 36,570评论 2 327
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 38,711评论 1 341
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 34,388评论 4 332
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 40,018评论 3 316
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 30,796评论 0 21
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,023评论 1 266
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 46,461评论 2 360
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 43,595评论 2 350

推荐阅读更多精彩内容