对于一个非常基本的spring-boot应用程序,我尝试使用log4j 2 yaml配置登录到一个日志文件。但是没有创建日志文件。我试着四处看看,但是似乎没有一个解决方案起作用。
pom档案具有下列相依性:
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
<exclusions>
<exclusion>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-logging</artifactId>
</exclusion>
</exclusions>
</dependency>
<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>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.24</version>
</dependency>
</dependencies>
完成日志记录的代码(也是应用程序中唯一的代码):
import com.example.demo.model.DemoData;
import lombok.extern.log4j.Log4j2;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
@Log4j2
@RestController
public class DemoController {
@Value("${messageFromProperties}")
private String messageFromProperties;
@Value("${messageFromYaml}")
private String messageFromYaml;
@GetMapping("/demo")
public ResponseEntity<DemoData> getDemoMessage(){
DemoData demoData = new DemoData(messageFromProperties, messageFromYaml);
log.error("ERROR!!!");
log.debug("DEBUG!!!");
log.info("INFO!!!");
return ResponseEntity.ok().body(demoData);
}
}
属性文件:
messageFromProperties: Message from properties
messageFromYaml: Message from YAML!!!
logging:
config: classpath:log4j2.yml
log4j2.yml 文件内容。文件存在于“resources”目录中
Configuration:
status: debug
appenders:
RollingFile:
- name: LogToRollingFile
fileName: "logs/demo.log"
filePattern: "logs/$${date:yyyy-MM}/demo-%d{MM-dd-yyyy}-%i.log.gz"
PatternLayout:
pattern: "[%-5level] %d{yyyy-MM-dd HH:mm:ss.SSS} [%t] %c{1} - %msg%n"
Policies:
SizeBasedTriggeringPolicy:
size: 10MB
DefaultRollOverStrategy:
max: 10
Loggers:
logger:
- name: com.example
level: debug
AppenderRef:
- ref: LogToRollingFile
Root:
level: debug
AppenderRef:
- ref: LogToRollingFile
我看到控制台中正在打印内容:
. ____ _ __ _ _
/\\ / ___'_ __ _ _(_)_ __ __ _ \ \ \ \
( ( )\___ | '_ | '_| | '_ \/ _` | \ \ \ \
\\/ ___)| |_)| | | | | || (_| | ) ) ) )
' |____| .__|_| |_|_| |_\__, | / / / /
=========|_|==============|___/=/_/_/_/
:: Spring Boot :: (v2.7.2)
17:25:49.535 [http-nio-8080-exec-2] ERROR com.example.demo.controller.DemoController - ERROR!!!
1条答案
按热度按时间aurhwmvo1#
如果您可以将记录器配置放在单独的XML文件中,则可以尝试以下操作:
一旦将此配置(
logback.xml
)放在与applciation.properties
相同的目录中,就可以在类的顶部使用@Slf4j
注解(由Lombok提供),并使用log对象记录任何所需的内容。如果一切正常,您应该可以在
/logs/debug_logs/debug.log
的文件夹(与项目位于同一目录)中看到日志。