对于一个spring引导应用程序,我正在尝试设置一个log4j2记录器,它可以将日志写入几个精子文件,但是日志只写到控制台,我检查了user_dir,以确保没有查找错误的位置。
这是应该编写测试日志的代码:
import org.apache.logging.log4j.LogManager; import org.apache.logging.log4j.Logger; public class UsersController { @Autowired UsersService userService; private static final Logger logger = LogManager.getLogger(UsersController.class); @PostMapping("CreateUserWithEmailAndPassword") public void createUserWithEmailAndPassword(@RequestParam String userName, @RequestParam String password, @RequestParam String email, HttpServletResponse response) throws ExecutionException, InterruptedException { logger.info("creating a new user"); if(userService.createUserWithEmailAndPassword(userName, password, email)) response.setStatus(HttpServletResponse.SC_ACCEPTED); else{ logger.error("failed on creating a new user"); response.setStatus(HttpServletResponse.SC_EXPECTATION_FAILED); }
这是我的log4j2.xml文件:
<?xml version="1.0" encoding="UTF-8"?> <Configuration status="INFO"> <Appenders> <Console name="ConsoleAppender" target="SYSTEM_OUT"> <PatternLayout pattern="%d{HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n" /> </Console> <File name="FileAppender" ref="infoAppender" fileName="info-${date:yyyyMMdd}.log" immediateFlush="true" append="true"> <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </File> <File name="FileAppender" ref="errorAppender" fileName="error_warn-${date:yyyyMMdd}.log" immediateFlush="true" append="true"> <PatternLayout pattern="%d{yyy-MM-dd HH:mm:ss.SSS} [%t] %-5level %logger{36} - %msg%n"/> </File> </Appenders> <Loggers> <Root level="warn"> <AppenderRef ref="errorAppender"/> </Root> <AppenderRef ref="ConsoleAppender"/> <AppenderRef ref="infoAppender" level="info"/> </Loggers> <Properties> <!--LINUX LOG DIRECTORY--> <Property name="logDirLinux">/storage1/user/logs/folderName/</Property> <!--WINDOWS LOG DIRECTORY--> <Property name="logDirWindows">C:\\logs\\</Property> </Properties> </Configuration>
这是我的build.gradle文件:
plugins { id 'org.springframework.boot' version '2.7.2' id 'io.spring.dependency-management' version '1.0.12.RELEASE' id 'java' group = 'com.Itamarled' version = '0.0.1-SNAPSHOT' sourceCompatibility = '17' configurations { compileOnly { extendsFrom annotationProcessor repositories { mavenCentral() dependencies { implementation ('org.springframework.boot:spring-boot-starter-web'){ exclude group : 'spring-boot-starter-logging' compileOnly 'org.projectlombok:lombok' annotationProcessor 'org.projectlombok:lombok' testImplementation ('org.springframework.boot:spring-boot-starter-test'){ exclude group : 'spring-boot-starter-logging' implementation 'com.google.firebase:firebase-admin:9.0.0' implementation 'org.springframework.boot:spring-boot-starter-log4j2' tasks.named('test') { useJUnitPlatform() }
发布于 2022-08-09 10:41:29
问题是,由于文件结构的原因,spring无法识别log4j2.xml文件。
该文件必须直接位于src/main/resources中。
发布于 2022-08-09 09:15:29
将属性标记添加到XML文件中,然后定义路径以保存日志文件:
<Properties> <!--LINUX LOG DIRECTORY-->