当前位置: 首页 > 知识库问答 >
问题:

日志记录:在Spring Boot中使用属性文件实现Log4j2

井高峯
2023-03-14

我使用Spring Boot和log4j2进行日志记录,因为我希望日志写在文件上而不是控制台上。所以我实现了log4j2.properties并将其保存在Spring Boot项目的资源文件夹下。

logging.config=classpath:log4j2.properties
# Root logger option
log4j.rootLogger=INFO, file, DEBUG, stdout


# configuration to print into file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:/Logs/app.log
log4j.appender.file.MaxFileSize=12MB
log4j.appender.file.MaxBackupIndex=10
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n


# configuration to print on console
log4j.appender.stdout=org.apache.log4j.ConsoleAppender
log4j.appender.stdout.Target=System.out
log4j.appender.stdout.layout=org.apache.log4j.PatternLayout
log4j.appender.stdout.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n
@SpringBootApplication
public class DemoApplication extends SpringBootServletInitializer {

  private final static Logger log = LogManager.getLogger(DemoApplication.class);

  @Override
  protected SpringApplicationBuilder configure(SpringApplicationBuilder application) {

    return application.sources(DemoApplication.class);
  }

  public static void main(String[] args) {

    SpringApplication.run(DemoApplication.class, args);
    log.info("**** Demo Application Started *****");

  }

}
<dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-data-jpa</artifactId>
      </dependency>

      <!--Logging-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter</artifactId>
         <exclusions>
            <exclusion>
               <groupId>org.springframework.boot</groupId>
               <artifactId>spring-boot-starter-logging</artifactId>
            </exclusion>
         </exclusions>
      </dependency>

      <!--https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-starter-log4j-->
      <dependency>
         <groupId>org.springframework.boot</groupId>
         <artifactId>spring-boot-starter-log4j2</artifactId>
      </dependency>

      <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-api</artifactId>
    </dependency>

    <dependency>
        <groupId>org.apache.logging.log4j</groupId>
        <artifactId>log4j-core</artifactId>
    </dependency>

共有1个答案

伯向晨
2023-03-14

尝试在application.properties文件中添加以下内容:

logging.level.my.base.package=TRACE
logging.level.org.springframework=INFO
logging.level.org.hibernate=INFO 

其中my.base.package表示整个项目的基本包

 类似资料: