Spring boot中log4j2配置yml方式併發送郵件
阿新 • • 發佈:2018-12-17
(1) 引包
(注:當排除預設logback日誌時,放spring-boot-starter-web下不能把logback清理乾淨,報Class path contains multiple SLF4J bindings.)
<!-- 發郵件 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-mail</artifactId> </dependency> <!-- log related --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter</artifactId> <exclusions><!-- 去掉預設log配置 --> <exclusion> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-logging</artifactId> </exclusion> </exclusions> </dependency> <!-- 引入log4j2依賴 --> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-log4j2</artifactId> </dependency> <!-- 支援識別yml配置 --> <dependency> <groupId>com.fasterxml.jackson.dataformat</groupId> <artifactId>jackson-dataformat-yaml</artifactId> <version>2.9.7</version> </dependency> <!-- 解析yml配置 --> <dependency> <groupId>com.fasterxml.jackson.core</groupId> <artifactId>jackson-databind</artifactId> <version>2.9.7</version> </dependency> <!-- end of log related -->
(2) 在resource下建立log4j2.yml檔案
Configuration: appenders: Console: name: Console target: SYSTEM_OUT PatternLayout: Pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" RollingFile: - name: ROLLING_FILE ignoreExceptions: false fileName: ../logs/log4j2.log filePattern: "../logs/log4j2-%d{yyyy-MM-dd}-%i.log" PatternLayout: Pattern: "%d{yyyy-MM-dd HH:mm:ss,SSS}:%4p %t (%F:%L) - %m%n" Policies: TimeBasedTriggeringPolicy: modulate: true interval: 1 SizeBasedTriggeringPolicy: size: 2MB DefaultRolloverStrategy: max: 20 SMTP: name: Mailer subject: ERROR LOG to:
[email protected] # 多收件人(以逗號隔開 ****@qq.com,****@163.com) from:*****@qq.com smtpHost: smtp.qq.com smtpPort: 25 smtpProtocol: smtp smtpUsername: *****@qq.com smtpPassword: yourpassword smtpDebug: false # 是否開啟發郵件除錯模式 bufferSize: 1024 # Async: # name: AsyncMailer # appender-ref: Mailer Loggers: root: level: INFO appender-ref: - ref: Console - ref: ROLLING_FILE Logger: #單獨設定某些包的輸出級別 - name: org.springframework.web additivity: false #去除重複的log level: error appender-ref: - ref: Console - ref: ROLLING_FILE - name: org.springboot.sample additivity: false level: error appender-ref: - ref: Console - ref: ROLLING_FILE - name: com.alibaba.druid additivity: false level: error appender-ref: - ref: Console - ref: ROLLING_FILE - name: AsyncMailerLogger additivity: false level: error appender-ref: - ref: Mailer
(3) 使用方式:【注:application.yml中就不必設定logger.config了】
private static final Logger LOGGER_MAIL = LoggerFactory.getLogger("AsyncMailerLogger");
LOGGER_MAIL.error("你好!");
總結:
1. 當把使用方式放spring boot的mian方法下使用時,會直接執行被攔截死,因為bean建立都未完成,直接呼叫肯定失敗。
2. log4j2與logback的使用:spring boot預設引入logback並提供了需要引用的類上加@Slf4j註解,而log4j2需要在呼叫類中引用(3)中的那段程式碼。