springboot多环境配置logback
1. 创建springboot项目
直接使用idea创建或者官网下载包导入这里就不做过多赘述。
2. 引入相关依赖
dependencies {
compile('org.springframework.boot:spring-boot-starter-web')
compile 'mysql:mysql-connector-java:6.0.6'
compile "org.mybatis.spring.boot:mybatis-spring-boot-starter:1.3.1"
compile 'org.mybatis.generator:mybatis-generator-core:1.3.2'
testCompile('org.springframework.boot:spring-boot-starter-test')
testCompile group: 'junit', name: 'junit', version: '4.12'
}
Spring Boot 集成logback需要添加spring-boot-starter-logging依赖,而此依赖已经在spring-boot-starter中添加过了,所以不用再添加此依赖了(如下图)
3. 在springboot的yml文件中对logging进行配置
application-dev.yml:
logging:
path: D:\\log\\dev
config: classpath:logback-spring.xml
level:
root: debug
application-test.yml:
logging:
path: D:\\log\\test
config: classpath:logback-spring.xml
level:
root: info
4. logback-spring.xml
<?xml version="1.0" encoding="UTF-8"?>
<configuration>
<!--定义日志文件的存储地址 从springboot配置文件中获取路径-->
<springProperty scope="context" name="LOG_PATH" source="logging.path"/>
<!--springboot配置文件中获取日志级别-->
<springProperty scope="context" name="LOG_LEVEL" source="logging.level.root"/>
<property name="LOG_NAME" value="main"/>
<!--引入默认的一些设置-->
<include resource="org/springframework/boot/logging/logback/defaults.xml"/>
<!--web信息-->
<logger name="org.springframework.web" level="info"/>
<!--写入日志到控制台的appender,用默认的,但是要去掉charset,否则windows下tomcat下乱码-->
<appender name="CONSOLE" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>${CONSOLE_LOG_PATTERN}</pattern>
</encoder>
</appender>
<!--写入日志到文件的appender-->
<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<rollingPolicy class="ch.qos.logback.core.rolling.SizeAndTimeBasedRollingPolicy">
<fileNamePattern>${LOG_PATH}/${LOG_NAME}.%d{yyyy-MM-dd}.%i.log</fileNamePattern>
<maxFileSize>512MB</maxFileSize>
<maxHistory>30</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%d{HH:mm:ss.SSS} %contextName [%thread] %-5level %logger{36} - %msg%n</pattern>
</encoder>
</appender>
<!--异步到文件-->
<appender name="asyncFileAppender" class="ch.qos.logback.classic.AsyncAppender">
<discardingThreshold>0</discardingThreshold>
<queueSize>500</queueSize>
<appender-ref ref="FILE"/>
</appender>
<!--生产环境:打印控制台和输出到文件-->
<springProfile name="prod">
<root level="${LOG_LEVEL}">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="asyncFileAppender"/>
</root>
</springProfile>
<!--开发环境:打印控制台-->
<springProfile name="dev">
<root level="${LOG_LEVEL}">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="asyncFileAppender"/>
</root>
</springProfile>
<!--测试环境:打印控制台-->
<springProfile name="test">
<!-- 打印sql -->
<logger name="com.sun.example" level="DEBUG"/>
<root level="${LOG_LEVEL}">
<appender-ref ref="CONSOLE"/>
<appender-ref ref="asyncFileAppender"/>
</root>
</springProfile>
</configuration>
参考:
蝈蝈的博客 - Spring Boot教程(五):默认日志logback
朱兆麟 - Spring Boot Logging 配置
结合了上面两个博客的配置 加上springProperty 标签的应用
希望可以帮到各位!