您的位置:首页 > 编程语言 > Java开发

spring-boot笔记-日志记录、启动加载、定时任务(五)

2017-06-14 19:06 736 查看

日志记录

spring boot支持的日志框架有:logback,Log4j2,Log4j和Java Util Logging,默认使用的是logback日志框架,在起基础包中就可以看到一些默认的配置:具体配置大家可以从源码中多看看



自定义输出级别:可以直接在application.properties中进行配置

logging.level.org.springframework.web=DEBUG
logging.level.com.example.demo=TRACE


这样相当于我们在logback.xml 中配置的对应的日志级别。名称以logging.level开头,后面跟要输入日志的包名。 如果在 logback.xml 和 application.properties 中定义了相同的配置(如都配置了 org.springframework.web)但是输出级别不同,则实际上 application.properties 的优先级高于 logback.xml

自定义logback文件

对于一些项目,我们有自己约定的日志输出格式,如果需要自己来定义logback文件,可以直接在resources目录下新建logback.xml即可【具体logback配置这里不再多述】。



其实我们可以通过启动时的日志输出来看:

18:41:48,617 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback.groovy]
18:41:48,617 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Could NOT find resource [logback-test.xml]
18:41:48,617 |-INFO in ch.qos.logback.classic.LoggerContext[default] - Found resource [logback.xml] at [file:/D:/intelliIdea/demo/target/classes/logback.xml]


可以发现SpringBoot会先找logback.groovy,找不到再找logback-test.xml,如果再找不到继续找logback.xml。这里我们是找到了,如果找不到就会使用默认的logback配置。

其他日志类型配置:这里是一个配置log4j的例子,大家有兴趣的可以看看。

启动加载:CommandLineRunner

实际应用中,我们会有在项目服务启动的时候就去加载一些数据或做一些事情这样的需求。为了解决这样的问题,spring Boot 为我们提供了一个方法,通过实现接口 CommandLineRunner 来实现。

很简单,只需要一个类就可以,无需其他配置。 来看下具体代码:

import org.springframework.boot.CommandLineRunner;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;

/**
* Created by gonghao on 2017/6/5.
* 服务启动执行类
*/
@Component
@Order(value = 1)//如果有多个的话,执行优先级是按value值从小到大顺序【越小越先执行】
public class GhStartUpRunner implements CommandLineRunner {
@Override
public void run(String... args) throws Exception {
System.out.println("启动加载类:11111111");
}
}


看下控制台输出:



定时任务

在spring Boot中使用定时任务也是相当简单,它的时间表达式和一般的spring项目中的是一样的,我们直接看下代码即可:

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;

import java.util.Date;

/**
* Created by gonghao on 2017/6/8.
*/
@Configuration
@EnableScheduling
public class ScheduleDemo {
private final Logger log = LoggerFactory.getLogger(ScheduleDemo.class);

@Scheduled(cron = "0 0/1 * * * ?")//1分钟跑一次
public void doSchedule(){
log.info("spring boot 定时任务:date "+ new Date());
}

}


通过控制台打印看下结果:

2017-06-14 19:03:00.003 [pool-3-thread-1] INFO  com.example.demo.utils.ScheduleDemo[ScheduleDemo.java:21] - spring boot 定时任务:date Wed Jun 14 19:03:00 CST 2017
2017-06-14 19:04:00.004 [pool-3-thread-1] INFO  com.example.demo.utils.ScheduleDemo[ScheduleDemo.java:21] - spring boot 定时任务:date Wed Jun 14 19:04:00 CST 2017
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: