logback同时输出到控制台和文件,并按级别输出到不同的文件--配置开箱即用
第一步:添加maven依赖,编写pom.xml文件
<dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-classic</artifactId> <version>1.2.3</version> </dependency> <dependency> <groupId>ch.qos.logback</groupId> <artifactId>logback-core</artifactId> <version>1.2.3</version> </dependency>
第二步:创建logback-test.xml文件,创建位置如下
logback-test.xml文件内容如下
<?xml version="1.0" encoding="UTF-8" ?> <configuration> <!-- 输出到控制台 --> <appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender"> <!-- 输出的格式 --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> </appender> <!--输出错误日志--> <appender name="ERROR" class="ch.qos.logback.core.rolling.RollingFileAppender"> <!-- 日志名称的格式 --> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <file>logs/error.log</file> <!-- 配置滚动的策略 --> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logs/%d{yyyy-MM-dd}/error.log</fileNamePattern> <!-- 保存的最长时间:天数 --> <maxHistory>10</maxHistory> </rollingPolicy> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <level>ERROR</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <appender name="INFO" class="ch.qos.logback.core.rolling.RollingFileAppender"> <encoder> <pattern>%d{yyyy-MM-dd HH:mm:ss.SSS} [%thread] %-5level %logger{36} - %msg%n</pattern> </encoder> <file>logs/info.log</file> <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy"> <fileNamePattern>logs/%d{yyyy-MM-dd}/XXXXMo.log</fileNamePattern> <maxHistory>10</maxHistory> </rollingPolicy> <filter class="ch.qos.logback.classic.filter.LevelFilter"> <!--可以修改成INFO,DEBUG等--> <level>DEBUG</level> <onMatch>ACCEPT</onMatch> <onMismatch>DENY</onMismatch> </filter> </appender> <root level="debug"> <appender-ref ref="STDOUT" /> <appender-ref ref="ERROR" /> <appender-ref ref="INFO"/> </root> </configuration>
第三步(仅为测试):
@SpringBootApplication @Component @RestController public class DemoApplication { private static final Logger logger = LoggerFactory.getLogger(DemoApplication.class); @Autowired private Test test; public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); } @RequestMapping("/get") public void get() { logger.error(DemoApplication.class+"error"); logger.info(DemoApplication.class+"success"); } }
检查效果(控制台输出:)
日志文件输出:
好的,logback配置,同时输出控制台和日志文件,日志文件按不同级别输出到不同日志文件到此结束。