Springboot2 集成log4j2


在任何定制系统开发过程中,健全的日志系统是调试、运维、追查故障的重要保障,因为log4j频频爆出漏洞,魁鲸科技目前主要使用log4j2这个组件替代

基础步骤

  • Spring Boot默认使用的是logback框架,因此需要排除spring-boot-starter-logging
  • 然后引入log4j2框架
  • 配置文件设置使用log4j2的配置路径
  • 程序代码种使用日志门面slf4j框架打印日志。

修改pom.xml文件

spring-boot-starter-web种排除默认的logging包

 


org.springframework.boot
spring-boot-starter-web
${spring-boot-starter.version}


org.springframework.boot
spring-boot-starter-logging


 

通过依赖树排除第三方的框架内对logback等冲突包的依赖


Springboot2 集成log4j2

Springboot2 集成log4j2

找到并排除

Springboot2 集成log4j2

在resource目录下新增log4j2的配置文件

 
<?xml version="1.0" encoding="UTF-8"?>   
  
    
        ./WebAppLogs/logs
    
    
        
        
        
        
        
              
            
            
            
        
        
        

        
            

            

            
                

                

            
            
            
                

                
                    
                    
                    
                    

                

            

        

        
            

            

            
                

                

            

            
                
                    

                    

                

            

             
               
            
            
            
                

                

            
            
                
                    

                    

                

            
             
        
            
            
            
                

                

            
            
                
                    

                    

                

            
             
        
            
            
            
                

                

            
            
                
                    

                    

                

            
        
       
    
        
        

        

        
            

            

            

            

            

            

        

    

配置application.yml

 
server:
  port: 8080
spring:
  banner:
    charset: utf-8
logging:
  level:
    # 根据不同的类设定不同级别
    root: info
    study.*: debug
    nobyte.*: debug
  config: classpath:log4j2-spring.xml

使用slf4j打印

 
package study.springboot.ioc;

import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;

/**
 * CustomService
 *
 * @author linkanyway
 * @version 1.0
 * @date 2022/04/06 20:37
 */
@Component("CustomService")
@Slf4j
public class CustomServiceImpl implements CustomService {

    /**
     * 构造器
     */
    public CustomServiceImpl() {
        log.debug ("CustomService被实例化,容器装配制定了Lazy因此容器装载时候不会立刻初始化,只有第一次调用才会初始化");
    }

    /**
     * 重载print方法
     */
    @Override
    public void print() {
    log.debug (this.getClass ().getCanonicalName ()+" 被调用了print方法");
    }
}