java—运行jar应用程序时,如何在某处记录错误信息

mpbci0fu  于 2021-07-16  发布在  Java
关注(0)|答案(2)|浏览(420)

我有下面的spring启动应用程序是get runtimeexception示例。

  1. @RestController
  2. public class HelloController {
  3. @GetMapping("/getRuntimeError")
  4. public String hello() {
  5. throw new RuntimeException("error");
  6. }
  7. }

在linux上运行
启动命令:

  1. nohup java -jar app.jar > app.log

当运行时出错时,我会使用vim edit app.log检查错误是什么。
但是当app.log文件增长到2gb大小时,我无法查看到底是什么错误,因为文件太大。
所以我使用的是log4j2 rollingfile logger record log,但不能提供实际的runtimeexception堆栈信息。
这是log4j2配置

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <configuration status="warn">
  3. <Properties>
  4. <Property name="LOG_EXCEPTION_CONVERSION_WORD">%xwEx</Property>
  5. <Property name="LOG_DATEFORMAT_PATTERN">yyyy-MM-dd HH:mm:ss.SSS</Property>
  6. <Property name="CONSOLE_LOG_PATTERN">%clr{%d{${LOG_DATEFORMAT_PATTERN}}}{faint} %clr{%5p} %clr{%pid}{magenta} %clr{---}{faint} %clr{[%15.15t]}{faint} %clr{%-40.40c{1.}}{cyan} %clr{:}{faint} %m%n${sys:LOG_EXCEPTION_CONVERSION_WORD}</Property>
  7. </Properties>
  8. <appenders>
  9. <console name="Console" target="SYSTEM_OUT" follow="true">
  10. <PatternLayout
  11. pattern="${sys:CONSOLE_LOG_PATTERN}"/>
  12. </console>
  13. <RollingFile name="RollingFileInfo" fileName="logs/info.log"
  14. filePattern="logs/log-INFO-%d{yyyy-MM-dd}_%i.log.gz"
  15. append="false">
  16. <PatternLayout pattern="${CONSOLE_LOG_PATTERN}"/>
  17. <Policies>
  18. <TimeBasedTriggeringPolicy/>
  19. <SizeBasedTriggeringPolicy size="200MB"/>
  20. </Policies>
  21. <DefaultRolloverStrategy max="15"/>
  22. </RollingFile>
  23. </appenders>
  24. <loggers>
  25. <root level="info" includeLocation="false">
  26. <appender-ref ref="Console"/>
  27. <appender-ref ref="RollingFileInfo"/>
  28. </root>
  29. </loggers>
  30. </configuration>

使用此命令

  1. nohup java -jar app.jar > /dev/null > 2>&1 &


我的问题是:怎样才能记录错误,又避免文件过大?
有什么建议吗
谢谢你的帮助

idfiyjo8

idfiyjo81#

据我所知,记录器配置为登录到控制台,然后将输出重定向到文件。
相反,您应该将logger配置为写入文件,然后很容易配置日志循环策略(请参阅spring引导文档)。
如果您提供log4j配置,将更容易提供帮助。
编辑:感谢您提供log4j配置。
问题可能是您的log4j文件没有被spring加载。如果要使用log4j,请将文件放在resources文件夹中,并向maven或gradle文件添加依赖项:

  1. <dependencies>
  2. <dependency>
  3. <groupId>org.springframework.boot</groupId>
  4. <artifactId>spring-boot-starter-web</artifactId>
  5. <exclusions>
  6. <exclusion>
  7. <groupId>org.springframework.boot</groupId>
  8. <artifactId>spring-boot-starter-logging</artifactId>
  9. </exclusion>
  10. </exclusions>
  11. </dependency>
  12. <dependency>
  13. <groupId>org.springframework.boot</groupId>
  14. <artifactId>spring-boot-starter-log4j2</artifactId>
  15. </dependency>
  16. </dependencies>

记住排除 spring-boot-starter-logging . 您的日志现在应该可以在控制台中看到了(控制台指的是运行spring引导应用程序的终端,而不是运行spring引导应用程序的终端) curl 客户端)和 info.log 文件。
您还可以使用logback文件而不是log4j来配置相同的东西。在这种情况下,您不必更改构建文件,只需将confing放入spring boot即可 application.properties 文件。

展开查看全部
uinbv5nw

uinbv5nw2#

我相信您要实现的是将错误记录到日志文件中,然后交叉检查stacktrace。
您可以使用logger,例如log4j或slf4j库。您可以指定文件在创建新文件之前可以达到的最大大小。

相关问题