Using java.util.logging (default)

本文介绍如何使用Java Util Logging及Log4j配置Tomcat的日志记录。包括如何为不同的组件设置日志级别、指定日志文件位置等。还介绍了如何在每个Web应用程序中配置单独的日志设置。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

 
Using java.util.logging (default)

The default implementation of java.util.logging provided in the JDK is too limited to be useful. A limitation of JDK Logging appears to be the inability to have per-web application logging, as the configuration is per-VM. As a result, Tomcat will, in the default configuration, replace the default LogManager implementation with a container friendly implementation called JULI, which addresses these shortcomings. It supports the same configuration mechanisms as the standard JDK java.util.logging, using either a programmatic approach, or properties files. The main difference is that per-classloader properties files can be set (which enables easy redeployment friendly webapp configuration), and the properties files support slightly extended constructs which allows more freedom for defining handlers and assigning them to loggers.

JULI is enabled by default, and supports per classloader configuration, in addition to the regular global java.util.logging configuration. This means that logging can be configured at the following layers:

  • Globally. That is usually done in the ${catalina.base}/conf/logging.properties file. The file is specified by the java.util.logging.config.file System property which is set by the startup scripts. If it is not readable or is not configured, the default is to use the ${java.home}/lib/logging.properties file in the JRE.
  • In the web application. The file will be WEB-INF/classes/logging.properties

The default logging.properties in the JRE specifies a ConsoleHandler that routes logging to System.err. The default conf/logging.properties in Apache Tomcat also adds several FileHandlers that write to files.

A handler's log level threshold is INFO by default and can be set using SEVERE, WARNING, INFO, CONFIG, FINE, FINER, FINEST or ALL. You can also target specific packages to collect logging from and specify a level.

Here is how you would set debugging from Tomcat. You would need to ensure the ConsoleHandler's (or FileHandler's') level is also set to collect this threshold, so FINEST or ALL should be set. Please refer to java.util.logging documentation in the JDK for the complete details:

org.apache.catalina.level=FINEST

The configuration used by JULI is extremely similar to the one supported by plain java.util.logging, but uses a few extensions to allow better flexibility in assigning loggers. The main differences are:

  • A prefix may be added to handler names, so that multiple handlers of a single class may be instantiated. A prefix is a String which starts with a digit, and ends with '.'. For example, 22foobar. is a valid prefix.
  • System property replacement is performed for property values which contain ${systemPropertyName}.
  • As in Java 6.0, loggers can define a list of handlers using the loggerName.handlers property.
  • By default, loggers will not delegate to their parent if they have associated handlers. This may be changed per logger using the loggerName.useParentHandlers property, which accepts a boolean value.
  • The root logger can define its set of handlers using the .handlers property.

There are several additional implementation classes, that can be used together with the ones provided by Java. The notable one is org.apache.juli.FileHandler.

org.apache.juli.FileHandler supports buffering of the logs. The buffering is not enabled by default. To configure it, use the bufferSize property of a handler. A value of 0 uses system default buffering (typically an 8K buffer will be used). A value of <0 forces a writer flush upon each log write. A value >0 uses a BufferedOutputStream with the defined value but note that the system default buffering will also be applied.

Example logging.properties file to be placed in $CATALINA_BASE/conf:

handlers = 1catalina.org.apache.juli.FileHandler, \
           2localhost.org.apache.juli.FileHandler, \
           3manager.org.apache.juli.FileHandler, \
           java.util.logging.ConsoleHandler

.handlers = 1catalina.org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

1catalina.org.apache.juli.FileHandler.level = FINE
1catalina.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
1catalina.org.apache.juli.FileHandler.prefix = catalina.

2localhost.org.apache.juli.FileHandler.level = FINE
2localhost.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
2localhost.org.apache.juli.FileHandler.prefix = localhost.

3manager.org.apache.juli.FileHandler.level = FINE
3manager.org.apache.juli.FileHandler.directory = ${catalina.base}/logs
3manager.org.apache.juli.FileHandler.prefix = manager.
3manager.org.apache.juli.FileHandler.bufferSize = 16384

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter


############################################################
# Facility specific properties.
# Provides extra control for each logger.
############################################################

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].handlers = \
   2localhost.org.apache.juli.FileHandler

org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].level = INFO
org.apache.catalina.core.ContainerBase.[Catalina].[localhost].[/manager].handlers = \
   3manager.org.apache.juli.FileHandler

# For example, to log debug messages in ContextConfig and HostConfig
# classes and to log only warnings and errors in other
# org.apache.catalina.** classes, uncomment these lines:
#org.apache.catalina.startup.ContextConfig.level = FINE
#org.apache.catalina.startup.HostConfig.level = FINE
#org.apache.catalina.level = WARNING

Example logging.properties for the servlet-examples web application to be placed in WEB-INF/classes inside the web application:

handlers = org.apache.juli.FileHandler, java.util.logging.ConsoleHandler

############################################################
# Handler specific properties.
# Describes specific configuration info for Handlers.
############################################################

org.apache.juli.FileHandler.level = FINE
org.apache.juli.FileHandler.directory = ${catalina.base}/logs
org.apache.juli.FileHandler.prefix = servlet-examples.

java.util.logging.ConsoleHandler.level = FINE
java.util.logging.ConsoleHandler.formatter = java.util.logging.SimpleFormatter

Documentation references

See the following resources for additional information:

Considerations for productive usage

You may want to take note of the following:

  • Consider removing ConsoleHandler from configuration.

    By default (thanks to the .handlers setting) logging goes both to a FileHandler and to a ConsoleHandler. The output of the latter one is usually captured into a file, such as catalina.out. Thus you end up with two copies of the same messages.

  • Consider removing FileHandlers for the applications that you do not use. E.g., the one for host-manager.

  • The handlers by default use the system default encoding to write the log files. It can be configured with encoding property. See Javadoc for details.

  • Consider configuring an Access log.

Using Log4j

This section explains how to configure Tomcat to use log4j rather than java.util.logging for all Tomcat's internal logging.

Note: The steps described in this section are needed when you want to reconfigure Tomcat to use Apache log4j for its own logging. These steps are not needed if you just want to use log4j in your own web application. — In that case, just put log4j.jar and log4j.properties into WEB-INF/lib and WEB-INF/classes of your web application.

The following steps describe configuring log4j to output Tomcat's internal logging.

  1. Create a file called log4j.properties with the following content and save it into $CATALINA_BASE/lib
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
  1. Download Log4J (v1.2 or later).
  2. Download or build tomcat-juli.jar and tomcat-juli-adapters.jar that are available as an "extras" component for Tomcat. See Additional Components documentation for details.

    This tomcat-juli.jar differs from the default one. It contains the full Apache Commons Logging implementation and thus is able to discover the presense of log4j and configure itself.

  3. If you want to configure Tomcat to use log4j globally:

    • Put log4j.jar into $CATALINA_HOME/lib.
    • Replace $CATALINA_HOME/bin/tomcat-juli.jar with tomcat-juli.jar from "extras".
    • Put tomcat-juli-adapters.jar from "extras" into $CATALINA_HOME/lib
  4. If you are running Tomcat with separate $CATALINA_HOME and $CATALINA_BASE and want to configure to use log4j in a single $CATALINA_BASE only:

    • Create $CATALINA_BASE/bin and $CATALINA_BASE/lib directories if they do not exist.
    • Put log4j.jar into $CATALINA_BASE/lib
    • Put tomcat-juli.jar from "extras" as $CATALINA_BASE/bin/tomcat-juli.jar
    • Put tomcat-juli-adapters.jar from "extras" into $CATALINA_BASE/lib
    • If you are running with a security manager, you would need to edit the $CATALINA_BASE/conf/catalina.policy file to adjust it to using a different copy of tomcat-juli.jar.
    • The old tomcat-juli.jar in $CATALINA_HOME/bin is still referenced by manifest of bootstrap.jar and thus will be implicitly present on Tomcat's classpath. The startup scripts configure $CATALINA_BASE/bin/tomcat-juli.jar to be earlier on the classpath than bootstrap.jar, and so it should have higher priority. Thus it should be OK, but consider removing the unneeded copy of tomcat-juli.jar (copy it into all other $CATALINA_BASEs that do not use log4j). Tomcat 7 does not have this issue.
  5. Delete $CATALINA_BASE/conf/logging.properties to prevent java.util.logging generating zero length log files.

  6. Start Tomcat

This log4j configuration mirrors the default java.util.logging setup that ships with Tomcat: both the manager and host-manager apps get an individual log file, and everything else goes to the "catalina.log" log file. Each file is rolled-over once per day.

You can (and should) be more picky about which packages to include in the logging. Tomcat defines loggers by Engine and Host names. For example, for a more detailed Catalina localhost log, add this to the end of the log4j.properties above. Note that there are known issues with using this naming convention (with square brackets) in log4j XML based configuration files, so we recommend you use a properties file as described until a future version of log4j allows this convention.

log4j.logger.org.apache.catalina.core.ContainerBase.[Catalina].[localhost]=DEBUG
log4j.logger.org.apache.catalina.core=DEBUG
log4j.logger.org.apache.catalina.session=DEBUG

Be warned: a level of DEBUG will produce megabytes of logging and slow startup of Tomcat. This level should be used sparingly when debugging of internal Tomcat operations is required.

Your web applications should certainly use their own log4j configuration. This is valid with the above configuration. You would place a similar log4j.properties file in your web application's WEB-INF/classes directory, and log4jx.y.z.jar into WEB-INF/lib. Then specify your package level logging. This is a basic setup of log4j which does *not* require Commons-Logging, and you should consult the log4j documentation for more options. This page is intended only as a bootstrapping guide.

Additional notes

  • This exposes log4j libraries to the web applications through the Common classloader. See class loading documentation for details.

    Because of that, the web applications and libraries using Apache Commons Logging library are likely to automatically choose log4j as the underlying logging implementation.

  • The java.util.logging API is still available, for those web applications that use it directly. The ${catalina.base}/conf/logging.properties file is still referenced by Tomcat startup scripts.

    Removal of ${catalina.base}/conf/logging.properties file, mentioned as one of the steps, just causes java.util.logging to fallback to the default configuration as configured in JRE, which is to use a ConsoleHandler and do not create any files.

2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Starting Servlet engine: [Apache Tomcat/9.0.33] 2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Initializing Spring embedded WebApplicationContext 2025.03.17 10:09:36|INFO |org.springframework.boot.web.servlet.context.ServletWebServerApplicationContext|prepareWebApplicationContext()|284|Root WebApplicationContext: initialization completed in 2729 ms 2025.03.17 10:09:36|DEBUG|io.micrometer.core.util.internal.logging.InternalLoggerFactory|newDefaultFactory()|61|Using SLF4J as the default logging framework 2025.03.17 10:09:36|ERROR|org.springframework.boot.web.embedded.tomcat.TomcatStarter|onStartup()|61|Error starting Tomcat context. Exception: org.springframework.beans.factory.BeanCreationException. Message: Error creating bean with name 'servletEndpointRegistrar' defined in class path resource [org/springframework/boot/actuate/autoconfigure/endpoint/web/ServletEndpointManagementContextConfiguration$WebMvcServletEndpointManagementContextConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.endpoint.web.ServletEndpointRegistrar]: Factory method 'servletEndpointRegistrar' threw exception; nested exception is org.springframework.beans.factory.UnsatisfiedDependencyException: Error creating bean with name 'healthEndpoint' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Unsatisfied dependency expressed through method 'healthEndpoint' parameter 0; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'healthContributorRegistry' defined in class path resource [org/springframework/boot/actuate/autoconfigure/health/HealthEndpointConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributorRegistry]: Factory method 'healthContributorRegistry' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'dbHealthContributor' defined in class path resource [org/springframework/boot/actuate/autoconfigure/jdbc/DataSourceHealthContributorAutoConfiguration.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [org.springframework.boot.actuate.health.HealthContributor]: Factory method 'dbHealthContributor' threw exception; nested exception is org.springframework.beans.factory.BeanCreationException: Error creating bean with name 'scopedTarget.dataSource' defined in class path resource [org/springframework/boot/autoconfigure/jdbc/DataSourceConfiguration$Hikari.class]: Bean instantiation via factory method failed; nested exception is org.springframework.beans.BeanInstantiationException: Failed to instantiate [com.zaxxer.hikari.HikariDataSource]: Factory method 'dataSource' threw exception; nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties$DataSourceBeanCreationException: Failed to determine a suitable driver class 2025.03.17 10:09:36|INFO |org.apache.juli.logging.DirectJDKLog|log()|173|Stopping service [Tomcat] 2025.03.17 10:09:36|WARN |org.springframework.context.support.AbstractApplicationContext|refresh()|558|Exception encountered during context initialization - cancelling refresh attempt: org.springframework.context.ApplicationContextException: Unable to start web server; nested exception is org.springframework.boot.web.server.WebServerException: Unable to start embedded Tomcat 2025.03.17 10:09:36|INFO |org.springframework.boot.autoconfigure.logging.ConditionEvaluationReportLoggingListener|logMessage()|136|
最新发布
03-18
<think>嗯,用户给了一段日志,需要分析问题。首先看日志级别,有ERROR,说明有严重错误。时间都是2025年,不过这可能只是测试或者模拟的时间,不用在意。接下来看错误信息,重点在Tomcat启动失败,原因是Bean创建异常,涉及到servletEndpointRegistrar。 然后错误链条一步步往下,最后看到DataSourceProperties的异常,说无法确定合适的驱动类。这说明Spring Boot在配置数据源的时候找不到合适的JDBC驱动。可能的原因有几个:项目依赖中没有添加数据库驱动的依赖,比如MySQL、H2或者其他数据库的驱动;或者在配置文件中没有正确配置数据源的URL,导致Spring无法自动检测驱动;还有一种可能是依赖的版本不对,或者配置文件中的驱动类名写错了。 接下来,用户可能需要检查pom.xml或者build.gradle文件,确认是否有数据库驱动的依赖。比如,如果使用MySQL,应该有mysql-connector-java的依赖。同时检查application.properties或application.yml中的spring.datasource.url、username、password等配置是否正确,特别是URL的格式是否正确,例如jdbc:mysql://localhost:3306/dbname。如果URL里没有指定数据库类型,或者驱动类没有被正确加载,也会导致这个问题。 另外,如果使用的是Spring Boot的自动配置,可能需要确保DataSource的配置是正确的,或者是否有多个数据源配置导致冲突。有时候排除自动配置也可能引起问题,需要检查是否有不必要的排除项。 用户可能需要一步步排查:首先确认依赖是否存在,然后检查配置文件,接着查看类路径中是否有对应的驱动jar包,最后考虑是否有其他配置干扰。可能还需要查看更详细的日志,确定驱动类加载的具体问题所在。</think>以下是对该日志的逐步分析及解决方案: --- ### **步骤1:定位核心错误** 日志中关键错误信息位于倒数第二段: $$...\text{nested exception is org.springframework.boot.autoconfigure.jdbc.DataSourceProperties\$DataSourceBeanCreationException: Failed to determine a suitable driver class}$$ **直接原因**:Spring Boot 无法找到数据库驱动类。 --- ### **步骤2:分析依赖关系** 此错误通常由以下原因导致: 1. **未添加数据库驱动依赖** - 例如未在 `pom.xml` 或 `build.gradle` 中声明 MySQL、PostgreSQL 等数据库驱动。 2. **错误的JDBC URL格式** - 配置文件中 `spring.datasource.url` 格式错误,导致无法识别驱动类型。 3. **驱动类未加载** - 驱动包未正确引入项目,或版本不兼容。 --- ### **步骤3:验证依赖配置** 以 Maven 项目为例,检查是否包含类似依赖: ```xml <!-- MySQL 驱动示例 --> <dependency> <groupId>mysql</groupId> <artifactId>mysql-connector-java</artifactId> <version>8.0.33</version> </dependency> ``` **若无驱动依赖**:需根据数据库类型添加对应依赖。 --- ### **步骤4:检查数据源配置** 在 `application.properties` 或 `application.yml` 中验证以下配置: ```properties # 示例:MySQL 配置 spring.datasource.url=jdbc:mysql://localhost:3306/your_database spring.datasource.username=root spring.datasource.password=secret spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` **注意**: - 若省略 `driver-class-name`,Spring Boot 需通过 `url` 自动推断驱动类型(如 `jdbc:mysql://` 对应 MySQL)。 - 若 URL 未明确协议(如拼写错误 `jdbc:mysq://`),将无法识别驱动。 --- ### **步骤5:验证类路径中的驱动包** 通过以下方式检查驱动是否存在: 1. Maven:执行 `mvn dependency:tree`,搜索驱动包。 2. 直接查看编译后的 `target` 目录下是否包含驱动 JAR 文件。 --- ### **步骤6:其他可能性排查** 1. **多数据源冲突** 如果手动配置了多个数据源,需禁用自动配置: ```java @SpringBootApplication(exclude = {DataSourceAutoConfiguration.class}) ``` 2. **Profile 配置问题** 检查不同 Profile(如 `application-dev.properties`)中配置是否覆盖了默认值。 --- ### **解决方案总结** 1. 添加数据库驱动依赖。 2. 检查 `spring.datasource.url` 格式。 3. 确保配置文件中数据库连接信息正确。 4. 清理并重新构建项目(如 `mvn clean install`)。 --- **附加建议**: 启用调试日志可获取更详细错误信息: ```properties logging.level.root=DEBUG ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值