1. 程式人生 > >spring-boot筆記-日誌記錄、啟動載入、定時任務(五)

spring-boot筆記-日誌記錄、啟動載入、定時任務(五)

日誌記錄

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