Spring Boot 嵌入式 tomcat 日志

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/48312851/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 01:34:25  来源:igfitidea点击:

Spring boot embedded tomcat logs

springspring-bootloggingtomcat8embedded-tomcat-8

提问by Robocide

i'm using spring boot embedded tomcat with spring boot 1.5.9 , im also using Log4j2.

我正在使用带有 spring boot 1.5.9 的 spring boot 嵌入式 tomcat,我也在使用 Log4j2。

recently i exerience problems during load, so i want to understand better the tomcat logs [Not the access Logs] , i tried (in application.properties) :

最近我在加载过程中遇到问题,所以我想更好地了解 tomcat 日志 [不是访问日志],我尝试过(在 application.properties 中):

logging.level.org.apache.tomcat: INFO
logging.level.org.apache.catalina: INFO

but none of the above worked. is there any other way to achieve it ?

但以上都没有奏效。还有其他方法可以实现吗?

采纳答案by Robocide

Found it !! You are now able to see the internal Logs of Embedded Tomcat in your App's Log4j log file with 3 easy steps:

找到了 !!您现在可以通过 3 个简单的步骤在应用程序的 Log4j 日志文件中查看嵌入式 Tomcat 的内部日志:

1] add to your pom:

1] 添加到你的 pom:

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

2] add to your running arg a new JVM param , e.g:

2] 向您正在运行的 arg 添加一个新的 JVM 参数,例如:

java -Djava.util.logging.manager=org.apache.logging.log4j.jul.LogManager -jar target/demo-0.0.1-SNAPSHOT.jar

3] add to your application.properties:

3] 添加到您的 application.properties:

logging.level.org.apache=DEBUG

Enjoy Life ! :)

享受生活!:)

Explaination:the problem is because Log4j log levels is not propagated into JUL (which is the actual Logging way Embedded tomcat use) so the above achieves this connection with JUL and Log4j log levels.

解释:问题是因为Log4j的日志级别没有传播到JUL(这是嵌入式tomcat使用的实际Logging方式)所以上面实现了JUL和Log4j日志级别的这种联系。

Reference:After reading the Spring boot 1.5.10 release notes (which is not required for the solution) i saw the new documentation that shed light how to achive it and explaination about it:

参考:阅读 Spring boot 1.5.10 发行说明(解决方案不需要)后,我看到了新文档,其中阐明了如何实现它并对其进行了解释:

https://github.com/spring-projects/spring-boot/issues/2923#issuecomment-358451260

https://github.com/spring-projects/spring-boot/issues/2923#issuecomment-358451260

回答by Vikram Palakurthi

Please refer to this urlwhich contains common application properties which also includes application logging properties and tomcat level logging properties. Whether you use yaml or properties file, spring boot uses this configuration to bootstrap the application. Search for below configuration items.

请参阅此url,其中包含常见的应用程序属性,其中还包括应用程序日志记录属性和 tomcat 级别的日志记录属性。无论您使用 yaml 还是属性文件,spring boot 都会使用此配置来引导应用程序。搜索以下配置项。

# LOGGING
logging.config= # Location of the logging configuration file. For instance `classpath:logback.xml` for Logback
logging.exception-conversion-word=%wEx # Conversion word used when logging exceptions.
logging.file= # Log file name. For instance `myapp.log`
logging.level.*= # Log levels severity mapping. For instance `logging.level.org.springframework=DEBUG`
logging.path= # Location of the log file. For instance `/var/log`
logging.pattern.console= # Appender pattern for output to the console. Only supported with the default logback setup.
logging.pattern.file= # Appender pattern for output to the file. Only supported with the default logback setup.
logging.pattern.level= # Appender pattern for log level (default %5p). Only supported with the default logback setup.
logging.register-shutdown-hook=false # Register a shutdown hook for the logging system when it is initialized.

server.tomcat.accept-count= # Maximum queue length for incoming connection requests when all possible request processing threads are in use.
server.tomcat.accesslog.buffered=true # Buffer output such that it is only flushed periodically.
server.tomcat.accesslog.directory=logs # Directory in which log files are created. Can be relative to the tomcat base dir or absolute.
server.tomcat.accesslog.enabled=false # Enable access log.
server.tomcat.accesslog.file-date-format=.yyyy-MM-dd # Date format to place in log file name.
server.tomcat.accesslog.pattern=common # Format pattern for access logs.
server.tomcat.accesslog.prefix=access_log # Log file name prefix.
server.tomcat.accesslog.rename-on-rotate=false # Defer inclusion of the date stamp in the file name until rotate time.
server.tomcat.accesslog.request-attributes-enabled=false # Set request attributes for IP address, Hostname, protocol and port used for the request.
server.tomcat.accesslog.rotate=true # Enable access log rotation.
server.tomcat.accesslog.suffix=.log # Log file name suffix.
server.tomcat.additional-tld-skip-patterns= # Comma-separated list of additional patterns that match jars to ignore for TLD scanning.
server.tomcat.background-processor-delay=30 # Delay in seconds between the invocation of backgroundProcess methods.
server.tomcat.basedir= # Tomcat base directory. If not specified a temporary directory will be used.
server.tomcat.internal-proxies=10\.\d{1,3}\.\d{1,3}\.\d{1,3}|\
        192\.168\.\d{1,3}\.\d{1,3}|\
        169\.254\.\d{1,3}\.\d{1,3}|\
        127\.\d{1,3}\.\d{1,3}\.\d{1,3}|\
        172\.1[6-9]{1}\.\d{1,3}\.\d{1,3}|\
        172\.2[0-9]{1}\.\d{1,3}\.\d{1,3}|\
        172\.3[0-1]{1}\.\d{1,3}\.\d{1,3} # regular expression matching trusted IP addresses.
server.tomcat.max-connections= # Maximum number of connections that the server will accept and process at any given time.
server.tomcat.max-http-post-size=0 # Maximum size in bytes of the HTTP post content.
server.tomcat.max-threads=0 # Maximum amount of worker threads.
server.tomcat.min-spare-threads=0 # Minimum amount of worker threads.
server.tomcat.port-header=X-Forwarded-Port # Name of the HTTP header used to override the original port value.
server.tomcat.protocol-header= # Header that holds the incoming protocol, usually named "X-Forwarded-Proto".
server.tomcat.protocol-header-https-value=https # Value of the protocol header that indicates that the incoming request uses SSL.
server.tomcat.redirect-context-root= # Whether requests to the context root should be redirected by appending a / to the path.
server.tomcat.remote-ip-header= # Name of the http header from which the remote ip is extracted. For instance `X-FORWARDED-FOR`
server.tomcat.uri-encoding=UTF-8 # Character encoding to use to decode the URI.

回答by Mahesh_Loya

I struggled a lot,and didnt find anything of my help.Utlimately I had build "WAR" out of my spring boot application.Deploy it to tomcat instance and followed below steps,which redirected all the internal tomcat logs(JULI) logs to my application log file.

我挣扎了很多,没有找到任何帮助。最终我从我的 spring 启动应用程序中构建了“WAR”。将它部署到 tomcat 实例并按照以下步骤将所有内部 tomcat 日志(JULI)日志重定向到我的应用程序日志文件。

  1. Delete existing JULI library (CATALINA_HOME/bin/tomcat-juli.jar file) and the existing Tomcat Java Logging configuration file (CATALINA_HOME/conf/logging.properties).

  2. Download JULI Log4j Tomcat library (tomcat-juli.jar) from the Tomcat downloads' Extras section (http://tomcat.apache.org/download-70.cgi). Place the downloaded file to CATALINA_HOME/bin directory.

  3. Download Tomcat JULI adapters library (tomcat-juli-adapters.jar) from the Tomcat downloads' Extras section. Place this file in the CATALINA_HOME/lib directory.

  4. Download Log4j (version 1.2 or later), and place the downloaded library file to CATALINA_HOME/lib directory.

  5. Create the Log4j configuration file at the following location: CATALINA_HOME/lib/log4j.properties. Check below log4j configuration matching the default Java Logging configuration.

  6. Restart Tomcat.

  1. 删除现有的 JULI 库(CATALINA_HOME/bin/tomcat-juli.jar 文件)和现有的 Tomcat Java Logging 配置文件(CATALINA_HOME/conf/logging.properties)。

  2. 从 Tomcat 下载的 Extras 部分 ( http://tomcat.apache.org/download-70.cgi)下载 JULI Log4j Tomcat 库 (tomcat-juli.jar )。将下载的文件放到 CATALINA_HOME/bin 目录。

  3. 从 Tomcat 下载的 Extras 部分下载 Tomcat JULI 适配器库 (tomcat-juli-adapters.jar)。将此文件放在 CATALINA_HOME/lib 目录中。

  4. 下载Log4j(1.2及以上版本),将下载的库文件放到CATALINA_HOME/lib目录下。

  5. 在以下位置创建 Log4j 配置文件:CATALINA_HOME/lib/log4j.properties。检查下面与默认 Java Logging 配置匹配的 log4j 配置。

  6. 重启Tomcat。

Log4j configuration File Matching the Default Tomcat Logging Settings:

匹配默认 Tomcat 日志记录设置的 Log4j 配置文件:

log4j.rootLogger=INFO, CATALINA
//Define all the appenders log4j.appender.CATALINA=org.apache.log4j.DailyRollingFileAppender
log4j.appender.CATALINA.File=${catalina.base}/logs/catalina.
log4j.appender.CATALINA.Append=true log4j.appender.CATALINA.Encoding=UTF-8

//Roll-over the log once per day
log4j.appender.CATALINA.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.CATALINA.layout = org.apache.log4j.PatternLayout

log4j.appender.CATALINA.layout.ConversionPattern = %d [%t] %-5p %c- %m%n
log4j.appender.LOCALHOST=org.apache.log4j.DailyRollingFileAppender
log4j.appender.LOCALHOST.File=${catalina.base}/logs/localhost.
log4j.appender.LOCALHOST.Append=true log4j.appender.LOCALHOST.Encoding=UTF-8
log4j.appender.LOCALHOST.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.LOCALHOST.layout = org.apache.log4j.PatternLayout
log4j.appender.LOCALHOST.layout.ConversionPattern = %d [%t] %-5p %c- %m%n
log4j.appender.MANAGER=org.apache.log4j.DailyRollingFileAppender
log4j.appender.MANAGER.File=${catalina.base}/logs/manager.
log4j.appender.MANAGER.Append=true log4j.appender.MANAGER.Encoding=UTF-8
log4j.appender.MANAGER.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.MANAGER.layout = org.apache.log4j.PatternLayout
log4j.appender.MANAGER.layout.ConversionPattern = %d [%t] %-5p %c- %m%n
log4j.appender.HOST-MANAGER=org.apache.log4j.DailyRollingFileAppender
log4j.appender.HOST-MANAGER.File=${catalina.base}/logs/host-manager.
log4j.appender.HOST-MANAGER.Append=true log4j.appender.HOST-MANAGER.Encoding=UTF-8
log4j.appender.HOST-MANAGER.DatePattern='.'yyyy-MM-dd'.log'
log4j.appender.HOST-MANAGER.layout = org.apache.log4j.PatternLayout
log4j.appender.HOST-MANAGER.layout.ConversionPattern = %d [%t] %-5p %c- %m%n
log4j.appender.CONSOLE=org.apache.log4j.ConsoleAppender
log4j.appender.CONSOLE.Encoding=UTF-8
log4j.appender.CONSOLE.layout=org.apache.log4j.PatternLayout
log4j.appender.CONSOLE.layout.ConversionPattern = %d [%t] %-5p %c- %m%n

//Configure which loggers log to which appenders
log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].
[localhost]=INFO,
 LOCALHOST
log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].
[localhost].[/manager]=INFO,MANAGER
log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].
[localhost].[/host-manager]=
INFO, HOST-
MANAGER

You can also check a adapter avaiable on GIT@ link

您还可以在 GIT@链接上检查可用的适配器

In your spring boot application,you can make changes like adding and removing jars,folder from embedded Tomcat server Or even adding custom config files to it using TomcatEmbeddedServletContainerFactory.class,of spring boot.

在您的 Spring Boot 应用程序中,您可以进行更改,例如从嵌入式 Tomcat 服务器中添加和删除 jars、文件夹,甚至可以使用TomcatEmbeddedServletContainerFactory.class 向其添加自定义配置文件 。

回答by dsharew

The package for the embeded tomcat is org.springframework.boot.context.embedded.tomcatSo adding this to your application.propertiesfile

嵌入式 tomcat 的包是org.springframework.boot.context.embedded.tomcat所以将它添加到您的application.properties文件中

logging.level.org.springframework.boot.context.embedded.tomcat.TomcatEmbeddedServletContainer=INFO

回答by Ramesh Fadatare

Default configurations are provided for Java Util Logging, Log4J, Log4J2 and Logback. In each case loggers are pre-configured to use console output with optional file output also available

为 Java Util Logging、Log4J、Log4J2 和 Logback 提供了默认配置。在每种情况下,记录器都预先配置为使用控制台输出,也可以使用可选的文件输出

refer this link : https://stackoverflow.com/questions/31939849/spring-boot-default-log-location/31939886

请参阅此链接:https: //stackoverflow.com/questions/31939849/spring-boot-default-log-location/31939886

The embedded tomcat in spring boot internally echoes logs to console. The default log configuration will echo messages to the console as they are written. So until you explicitly specify a file as you described, it stays in the Console.

spring boot 内嵌的tomcat 内部将日志回显到控制台。默认日志配置将在写入消息时将消息回显到控制台。因此,除非您按照描述明确指定文件,否则它会保留在控制台中。

From the spring boot logging doc.

来自spring boot logging doc

You can custmize the logging as per your need.

您可以根据需要自定义日志记录。

回答by Grigory Kislin

For slf4j and Spring Boot 2 hide exceptions from Tomcat and handle them by yourself:

对于 slf4j 和 Spring Boot 2,从 Tomcat 中隐藏异常并自行处理:

  • Add to pom:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    
  • Add to config:

    @PostConstruct
    void postConstruct() {
        SLF4JBridgeHandler.install();
    }
    
  • Add to application.yaml

    logging:
        level:
          org.apache.catalina: off
    
  • Handle exception in ErrorController

    @Controller
    @Slf4j
    public class ErrorController implements 
                  org.springframework.boot.web.servlet.error.ErrorController {
        private static final String ERROR_PATH = "/error";
    
       @Autowired
       private ErrorAttributes errorAttributes;
    
       @Override
       public String getErrorPath() {
          return ERROR_PATH;
       }
    
       @RequestMapping(ERROR_PATH)
       public ModelAndView error(HttpServletRequest request) {
           return processException(errorAttributes.getError(new ServletWebRequest(request)));
       }
    }
    
  • 添加到 pom:

    <dependency>
        <groupId>org.slf4j</groupId>
        <artifactId>jul-to-slf4j</artifactId>
        <version>${slf4j.version}</version>
    </dependency>
    
  • 添加到配置:

    @PostConstruct
    void postConstruct() {
        SLF4JBridgeHandler.install();
    }
    
  • 添加 application.yaml

    logging:
        level:
          org.apache.catalina: off
    
  • 处理异常 ErrorController

    @Controller
    @Slf4j
    public class ErrorController implements 
                  org.springframework.boot.web.servlet.error.ErrorController {
        private static final String ERROR_PATH = "/error";
    
       @Autowired
       private ErrorAttributes errorAttributes;
    
       @Override
       public String getErrorPath() {
          return ERROR_PATH;
       }
    
       @RequestMapping(ERROR_PATH)
       public ModelAndView error(HttpServletRequest request) {
           return processException(errorAttributes.getError(new ServletWebRequest(request)));
       }
    }
    

回答by igor.zh

A log file, generated by org.apache.catalina.valves.AccessLogValve, usually named something like localhost_access_logcan be configured like this:

由 生成的日志文件org.apache.catalina.valves.AccessLogValve通常命名为类似的名称,localhost_access_log可以这样配置:

@Configuration
public class EmbeddedTomcatConfig {
    @Bean
    public TomcatEmbeddedServletContainerFactory containerFactory() {
        TomcatEmbeddedServletContainerFactory tomcatEmbeddedServletContainerFactory = new TomcatEmbeddedServletContainerFactory();
        AccessLogValve accessLogValve = new AccessLogValve();
        // set desired properties like
        accessLogValve.setDirectory(...);
        tomcatEmbeddedServletContainerFactory.addEngineValves(accessLogValve);
        return tomcatEmbeddedServletContainerFactory;
    }
}