Slf4j là gì
Code ví dụ Spring Boot Logging (Ghi log với SLF4J). Ghi Log trong Spring BootKhi bạn tạo Spring Boot Project. Bản thân thư việnspring-boot-starterđã chứa thư viện thực hiện logging SLF4J với cài đặt của nó (thường là common logging, slf4j) nên bạn không cần thực hiện thêm bất kỳ thư viện nào nữa Tạo Spring Boot ProjectỞ phần dependencies không cần thêm bất kỳ thư viện nào khác. Cấu trúc project File application.yaml logging: file: application.log level: root: DEBUG org.springframework: WARN stackjava.com.sblogging.service: INFOTrường hợp bạn muốn sử dụng file application.properties thay cho application.yaml logging.file: application.log logging.level.root: DEBUG logging.level.org.springframework: WARN logging.level.stackjava.com.sblogging.service: INFOTrong đó
Các mức độ / level ghi log:
Giả sử bạn để level log là INFO thì các log DEBUG hay TRACE sẽ không được lựu lại. (2 level cuối chỉ áp dụng cho 1 số ít thư viện) (Xem lại Ghi log ra file với Log4J, Ghi log ra database với Log4Jđể hiểu thêm cách định dạng log, ghi log ra database) File main package stackjava.com.sblogging; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.ApplicationContext; import stackjava.com.sblogging.service.DemoService; @SpringBootApplication public class SpringBootLoggingApplication { private static Logger logger = LoggerFactory.getLogger(SpringBootLoggingApplication.class); public static void main(String[] args) { ApplicationContext applicationContext = SpringApplication.run(SpringBootLoggingApplication.class, args); logger.info("debug enabled: {}", logger.isDebugEnabled()); logger.trace("trace"); logger.debug("debug"); logger.info("info"); logger.warn("warn"); logger.error("error"); DemoService demoService = applicationContext.getBean(DemoService.class); demoService.hello(); } }File Service package stackjava.com.sblogging.service; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.stereotype.Service; @Service public class DemoService { private static final Logger logger = LoggerFactory.getLogger(DemoService.class); public void hello() { logger.info("debug enabled: {}", logger.isDebugEnabled()); logger.trace("trace"); logger.debug("debug"); logger.info("info"); logger.warn("warn"); logger.error("error"); } }DemoClass DemoService.java nằm trong packagestackjava.com.sblogging.servicenên nó chỉ hiện log từ level INFO File application.log được tạo ra Okay, Done! Download code ví dụ trên tại đây. References: https://docs.spring.io//boot-features-logging.html https://docs.spring.io//howto-logging.html |