Logging configuration
了解 Quarkus 中日志 API 的用法、如何配置日志输出,以及如何使用日志适配器统一来自其他日志 API 的输出。
Read about the use of logging API in Quarkus, configuring logging output, and using logging adapters to unify the output from other logging APIs.
Quarkus 使用 JBoss Log Manager 日志后端发布应用程序和框架日志。Quarkus 支持 JBoss Logging API 和多个其他日志 API,它们无缝集成到 JBoss Log Manager 中。您可以使用以下任何 following APIs:
Quarkus uses the JBoss Log Manager logging backend for publishing application and framework logs. Quarkus supports the JBoss Logging API and multiple other logging APIs, seamlessly integrated with JBoss Log Manager. You can use any of the logging-apis:
Use JBoss Logging for application logging
如果使用 JBoss 日志记录 API,应用程序无需其他依赖项,因为 Quarkus 会自动提供该 API。
When using the JBoss Logging API, your application requires no additional dependencies, as Quarkus automatically provides it.
import org.jboss.logging.Logger;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import jakarta.ws.rs.Produces;
import jakarta.ws.rs.core.MediaType;
@Path("/hello")
public class ExampleResource {
private static final Logger LOG = Logger.getLogger(ExampleResource.class);
@GET
@Produces(MediaType.TEXT_PLAIN)
public String hello() {
LOG.info("Hello");
return "hello";
}
}
虽然 JBoss 日志记录会直接将日志消息路由到 JBoss 日志管理器,但某个库有时可能依赖的其他日志记录 API。在这种情况下,需要使用 logging adapter 确保其日志消息也可以路由到 JBoss 日志管理器。 |
While JBoss Logging routes log messages into JBoss Log Manager directly, one of your libraries might rely on a different logging API. In such cases, you need to use a logging-apis to ensure that its log messages are routed to JBoss Log Manager as well. |
Get an application logger
在 Quarkus 中,获取应用程序记录器的最常见方式有:
In Quarkus, the most common ways to obtain an application logger are by:
Declaring a logger field
这种经典方法是使用特定 API 获取记录器实例,将其存储在类的静态字段中,然后针对此实例调用日志记录操作。
With this classic approach, you use a specific API to obtain a logger instance, store it in a static field of a class, and call logging operations upon this instance.
使用任何 supported logging APIs 也可以使用相同流程。
The same flow can be applied with any of the logging-apis.
package com.example;
import org.jboss.logging.Logger;
public class MyService {
private static final Logger log = Logger.getLogger(MyService.class); 1
public void doSomething() {
log.info("It works!"); 2
}
}
1 | Define the logger field. |
2 | Invoke the desired logging methods on the log object. |
Simplified logging
Quarkus 会自动为使用 io.quarkus.logging.Log
的类添加记录器字段,从而简化日志记录。这样可以省去重复的样板代码,增强日志记录设置的便捷性。
Quarkus simplifies logging by automatically adding logger fields to classes that use io.quarkus.logging.Log
.
This eliminates the need for repetitive boilerplate code and enhances logging setup convenience.
package com.example;
import io.quarkus.logging.Log; (1)
class MyService { (2)
public void doSomething() {
Log.info("Simple!"); (3)
}
}
1 | The io.quarkus.logging.Log class contains the same methods as JBoss Logging, except that they are static . |
2 | Note that the class does not declare a logger field.
This is because during application build, a private static final org.jboss.logging.Logger field is created automatically in each class that uses the Log API.
The fully qualified name of the class that calls the Log methods is used as a logger name.
In this example, the logger name would be com.example.MyService . |
3 | Finally, all calls to Log methods are rewritten to regular JBoss Logging calls on the logger field during the application build. |
仅在应用程序类中使用 Log
API,不要在外部依赖项中使用。在构建时未由 Quarkus 处理的 Log
方法调用将引发异常。
Only use the Log
API in application classes, not in external dependencies.
Log
method calls that are not processed by Quarkus at build time will throw an exception.
Injecting a configured logger
注入带有 @Inject
注解的已配置 org.jboss.logging.Logger
记录器实例是添加应用程序记录器的另一种方法,但仅适用于 CDI Bean。
The injection of a configured org.jboss.logging.Logger
logger instance with the @Inject
annotation is another alternative to adding an application logger, but is applicable only to CDI beans.
可以使用 @Inject Logger log
,记录器的名字以注入到的类的名字来命名,也可以使用 @Inject @LoggerName("…") Logger log
,记录器将接收指定的名字。注入后,可以使用 log
对象调用日志记录方法。
You can use @Inject Logger log
, where the logger gets named after the class you inject it to, or @Inject @LoggerName("…") Logger log
, where the logger will receive the specified name.
Once injected, you can use the log
object to invoke logging methods.
package com.example;
import org.jboss.logging.Logger;
@ApplicationScoped
class SimpleBean {
@Inject
Logger log; 1
@LoggerName("foo")
Logger fooLog; 2
public void ping() {
log.info("Simple!");
fooLog.info("Goes to _foo_ logger!");
}
}
1 | The FQCN of the declaring class is used as a logger name, for example, org.jboss.logging.Logger.getLogger(SimpleBean.class) will be used. |
2 | In this case, the name foo is used as a logger name, for example,org.jboss.logging.Logger.getLogger("foo") will be used. |
记录器实例在内部缓存。因此,当记录器被注入(例如,注入到 |
The logger instances are cached internally. Therefore, when a logger is injected, for example, into a |
Use log levels
Quarkus 提供不同的日志级别,这有助于开发人员根据事件的严重程度控制记录的信息量。
Quarkus provides different log levels, which helps developers control the amount of information logged based on the severity of the events.
OFF |
A special level to use in configuration in order to turn off logging. |
FATAL |
A critical service failure or complete inability to service requests of any kind. |
ERROR |
A significant disruption in a request or the inability to service a request. |
WARN |
A non-critical service error or problem that may not require immediate correction. |
INFO |
Service lifecycle events or important related very low-frequency information. |
DEBUG |
Messages that convey extra information regarding lifecycle or non-request-bound events, useful for debugging. |
TRACE |
Messages that convey extra per-request debugging information that may be very high frequency. |
ALL |
A special level to use in configuration to turn on logging for all messages, including custom levels. |
还可以为使用 java.util.logging
的应用程序和库配置以下级别:
You can also configure the following levels for applications and libraries that use java.util.logging
:
SEVERE |
Same as ERROR. |
WARNING |
Same as WARN. |
CONFIG |
Service configuration information. |
FINE |
Same as DEBUG. |
FINER |
Same as TRACE. |
FINEST |
Increased debug output compared to |
Numerical level value | Standard level name | Equivalent java.util.logging (JUL) level name |
---|---|---|
1100 |
FATAL |
Not applicable |
1000 |
ERROR |
SEVERE |
900 |
WARN |
WARNING |
800 |
INFO |
INFO |
700 |
Not applicable |
CONFIG |
500 |
DEBUG |
FINE |
400 |
TRACE |
FINER |
300 |
Not applicable |
FINEST |
Configure the log level, category, and format
JBoss 日志记录集成到 Quarkus 中,可通过一个设置所有可用扩展的配置文件为所有 supported logging APIs 提供一个统一配置。要调整运行时日志记录,请修改 application.properties
文件。
JBoss Logging, integrated into Quarkus, offers a unified configuration for all logging-apis through a single configuration file that sets up all available extensions.
To adjust runtime logging, modify the application.properties
file.
INFO
logging and include Hibernate DEBUG
logs:quarkus.log.level=INFO
quarkus.log.category."org.hibernate".level=DEBUG
在将日志级别设置为低于 DEBUG
时,你还必须调整最小日志级别。此设置可以是全局的,使用 quarkus.log.min-level
配置属性,或者按类别设置:
When you set the log level to below DEBUG
, you must also adjust the minimum log level.
This setting is either global, using the quarkus.log.min-level
configuration property, or per category:
quarkus.log.category."org.hibernate".min-level=TRACE
这为 Quarkus 需要生成支持代码设置了最低层级。必须在构建时设置最低日志级别,以便 Quarkus 为优化机会敞开大门,在不可用级别上进行日志记录可以简化。
This sets a floor level for which Quarkus needs to generate supporting code. The minimum log level must be set at build time so that Quarkus can open the door to optimization opportunities where logging on unusable levels can be elided.
将 INFO
设置为最低日志级别会将较低级别的检查(如 isTraceEnabled
)设置为 false
。这会识别永远不会执行的代码,如 if(logger.isDebug()) callMethod();
,并将其标记为“死点”。
Setting INFO
as the minimum logging level sets lower-level checks, such as isTraceEnabled
, to false
.
This identifies code like if(logger.isDebug()) callMethod();
that will never be executed and mark it as "dead."
如果你在命令行中添加这些属性,请确保正确转义 "
字符:
If you add these properties on the command line, ensure the "
character is escaped properly:
-Dquarkus.log.category.\"org.hibernate\".level=TRACE
所有潜在属性都列在 logging configuration reference 部分。
All potential properties are listed in the loggingConfigurationReference section.
Logging categories
日志记录按类别配置,每个类别独立配置。除非有更具体的子类别配置,否则类别配置会递归地应用于所有子类别。
Logging is configured on a per-category basis, with each category being configured independently. Configuration for a category applies recursively to all subcategories unless there is a more specific subcategory configuration.
所有日志记录类别的父级称为“根类别”。作为最终父级,此类别可能包含全局应用于所有其他类别的配置。这包括全局配置的处理程序和格式化程序。
The parent of all logging categories is called the "root category." As the ultimate parent, this category might contain a configuration that applies globally to all other categories. This includes the globally configured handlers and formatters.
quarkus.log.handlers=console,mylog
在此示例中,根类别配置为使用两个处理程序:console
和 mylog
。
In this example, the root category is configured to use two handlers: console
and mylog
.
quarkus.log.category."org.apache.kafka.clients".level=INFO
quarkus.log.category."org.apache.kafka.common.utils".level=INFO
此示例演示了如何配置类别 org.apache.kafka.clients
和 org.apache.kafka.common.utils
的最小日志级别。
This example shows how you can configure the minimal log level on the categories org.apache.kafka.clients
and org.apache.kafka.common.utils
.
有关更多信息,请参见 Logging configuration reference。
For more information, see Logging configuration reference.
如果你想为特定类别配置其他内容,请创建一个命名处理程序(如 quarkus.log.handler.[console|file|syslog].<your-handler-name>.*
),并使用 quarkus.log.category.<my-category>.handlers
为该类别设置此处理程序。
If you want to configure something extra for a specific category, create a named handler like quarkus.log.handler.[console|file|syslog].<your-handler-name>.*
and set it up for that category by using quarkus.log.category.<my-category>.handlers
.
一个示例用例可能希望对保存到文件的日志消息使用不同的时间戳格式,而不是用于其他处理程序的格式。
An example use case can be a desire to use a different timestamp format for log messages which are saved to a file than the format used for other handlers.
有关进一步说明,请参见 Attaching named handlers to a category 示例的输出。
For further demonstration, see the outputs of the category-named-handlers-example example.
Property Name | Default | Description |
---|---|---|
|
|
The level to use to configure the category named |
|
|
The minimum logging level to use to configure the category named |
|
|
Specify whether this logger should send its output to its parent logger. |
|
|
The names of the handlers that you want to attach to a specific category. |
The |
Root logger configuration
根记录器类别单独处理,并使用以下属性进行配置:
The root logger category is handled separately, and is configured by using the following properties:
Property Name | Default | Description |
---|---|---|
|
|
The default log level for every log category. |
|
|
The default minimum log level for every log category. |
-
The parent category is examined if no level configuration exists for a given logger category.
-
The root logger configuration is used if no specific configurations are provided for the category and any of its parent categories.
尽管根记录器的处理程序通常通过 Although the root logger’s handlers are usually configured directly via |
Logging format
Quarkus 默认使用基于模式的日志记录格式设置程序生成可读文本日志,但您也可以使用专用属性为每个日志处理程序配置格式。
Quarkus uses a pattern-based logging formatter that generates human-readable text logs by default, but you can also configure the format for each log handler by using a dedicated property.
对于控制台处理程序,该属性是 quarkus.log.console.format
。
For the console handler, the property is quarkus.log.console.format
.
日志记录格式字符串支持以下符号:
The logging format string supports the following symbols:
Symbol | Summary | Description |
---|---|---|
|
|
Renders a simple |
|
Category |
Renders the category name. |
|
Source class |
Renders the source class name.[Format sequences which examine caller information may affect performance] |
|
Date |
Renders a date with the given date format string, which uses the syntax defined by |
|
Exception |
Renders the thrown exception, if any. |
|
Source file |
Renders the source file name.[Format sequences which examine caller information may affect performance] |
|
Host name |
Renders the system simple host name. |
|
Qualified host name |
Renders the system’s fully qualified host name, which may be the same as the simple host name, depending on operating system configuration. |
|
Process ID |
Render the current process PID. |
|
Source location |
Renders the source location information, which includes source file name, line number, class name, and method name.[Format sequences which examine caller information may affect performance] |
|
Source line |
Renders the source line number.[Format sequences which examine caller information may affect performance] |
|
Full Message |
Renders the log message plus exception (if any). |
|
Source method |
Renders the source method name.[Format sequences which examine caller information may affect performance] |
|
Newline |
Renders the platform-specific line separator string. |
|
Process name |
Render the name of the current process. |
|
Level |
Render the log level of the message. |
|
Relative time |
Render the time in milliseconds since the start of the application log. |
|
Simple message |
Renders just the log message, with no exception trace. |
|
Thread name |
Render the thread name. |
|
Thread ID |
Render the thread ID. |
|
Time zone |
Set the time zone of the output to |
|
Mapped Diagnostic Context Value |
Renders the value from Mapped Diagnostic Context. |
|
Mapped Diagnostic Context Values |
Renders all the values from Mapped Diagnostic Context in format |
|
Nested Diagnostics context values |
Renders all the values from Nested Diagnostics Context in format |
Alternative console logging formats
更改控制台日志格式很有用,例如,当 Quarkus 应用程序的控制台输出被某个服务捕获,该服务处理并存储日志信息以备日后分析的时候。
Changing the console log format is useful, for example, when the console output of the Quarkus application is captured by a service that processes and stores the log information for later analysis.
JSON logging format
可以采用 quarkus-logging-json
扩展来添加对 JSON 日志格式及其相关配置的支持。
The quarkus-logging-json
extension may be employed to add support for the JSON logging format and its related configuration.
-
Add this extension to your build file as the following snippet illustrates:[source, xml] .pom.xml
<dependency> <groupId>io.quarkus</groupId> <artifactId>quarkus-logging-json</artifactId> </dependency>
implementation("io.quarkus:quarkus-logging-json")
默认情况下,此扩展的存在会替换控制台配置的输出格式配置,并将格式字符串和颜色设置(如果有)忽略。其他控制台配置项(包括控制异步日志和日志级别的选项)将继续应用。
By default, the presence of this extension replaces the output format configuration from the console configuration, and the format string and the color settings (if any) are ignored. The other console configuration items, including those controlling asynchronous logging and the log level, will continue to be applied.
对于某些情况来说,在开发模式下使用人类可读的(非结构化)日志,在生产模式下使用 JSON 日志(结构化)是有意义的。这可以使用不同的配置文件来实现,如下面的配置所示。
For some, it will make sense to use humanly readable (unstructured) logging in dev mode and JSON logging (structured) in production mode. This can be achieved using different profiles, as shown in the following configuration. . Disable JSON logging in application.properties for dev and test mode:[source, properties]
%dev.quarkus.log.console.json=false %test.quarkus.log.console.json=false
Configuration
使用受支持的属性配置 JSON 记录扩展以自定义其行为。
Configure the JSON logging extension using supported properties to customize its behavior.
Unresolved directive in logging.adoc - include::{generated-dir}/config/quarkus-logging-json.adoc[]
启用漂亮打印可能会导致某些处理器和 JSON 解析器失败。
Enabling pretty printing might cause certain processors and JSON parsers to fail.
打印详情可能会很昂贵,因为这些值是从调用程序检索的。详情包括源类名、源文件名、源方法名和源行号。 |
Printing the details can be expensive as the values are retrieved from the caller. The details include the source class name, source file name, source method name, and source line number. |
Log handlers
日志处理程序是一个负责向接收方发送日志事件的日志记录组件。Quarkus 包含几个不同的日志处理程序: console、file*和 *syslog。
A log handler is a logging component responsible for the emission of log events to a recipient. Quarkus includes several different log handlers: console, file, and syslog.
特色示例使用 `com.example`作为日志记录类别。
The featured examples use com.example
as a logging category.
Console log handler
控制台日志处理程序默认启用,并且它将所有日志事件定向到应用程序控制台,通常是系统的 stdout
。
The console log handler is enabled by default, and it directs all log events to the application’s console, usually the system’s stdout
.
-
A global configuration example:[source, properties]
quarkus.log.console.format=%d{yyyy-MM-dd HH:mm:ss} %-5p [%c] (%t) %s%e%n
-
A per-category configuration example:[source, properties]
quarkus.log.handler.console.my-console-handler.format=%d{yyyy-MM-dd HH:mm:ss} [com.example] %s%e%n quarkus.log.category."com.example".handlers=my-console-handler quarkus.log.category."com.example".use-parent-handlers=false
有关其配置的详细信息,请参阅 console logging configuration参考。
For details about its configuration, see the quarkus-core_section_quarkus-log-console reference.
File log handler
若要将事件记录到应用程序主机上的文件,请使用 Quarkus 文件日志处理程序。文件日志处理程序默认禁用,因此您必须先启用它。
To log events to a file on the application’s host, use the Quarkus file log handler. The file log handler is disabled by default, so you must first enable it.
Quarkus 文件日志处理程序支持日志文件轮换。
The Quarkus file log handler supports log file rotation.
日志文件轮换通过维护指定数量的备份日志文件,同时保持主日志文件为最新并易于管理,从而确保有效的日志文件管理。
Log file rotation ensures effective log file management over time by maintaining a specified number of backup log files, while keeping the primary log file up-to-date and manageable.
-
A global configuration example:[source, properties]
quarkus.log.file.enable=true quarkus.log.file.path=application.log quarkus.log.file.format=%d{yyyy-MM-dd HH:mm:ss} %-5p [%c] (%t) %s%e%n
-
A per-category configuration example:[source, properties]
quarkus.log.handler.file.my-file-handler.enable=true quarkus.log.handler.file.my-file-handler.path=application.log quarkus.log.handler.file.my-file-handler.format=%d{yyyy-MM-dd HH:mm:ss} [com.example] %s%e%n quarkus.log.category."com.example".handlers=my-file-handler quarkus.log.category."com.example".use-parent-handlers=false
有关其配置的详细信息,请参阅 file logging configuration参考。
For details about its configuration, see the quarkus-core_section_quarkus-log-file reference.
Syslog log handler
The syslog handler in Quarkus follows the Syslog protocol, which is used to send log messages on UNIX-like systems. It utilizes the protocol defined in RFC 5424.
默认情况下,禁用 syslog 处理程序。启用后,它会将所有日志事件发送到 syslog 服务器,通常是应用程序的本地 syslog 服务器。
By default, the syslog handler is disabled. When enabled, it sends all log events to a syslog server, typically the local syslog server for the application.
-
A global configuration example:[source, properties]
quarkus.log.syslog.enable=true quarkus.log.syslog.app-name=my-application quarkus.log.syslog.format=%d{yyyy-MM-dd HH:mm:ss} %-5p [%c] (%t) %s%e%n
-
A per-category configuration example:[source, properties]
quarkus.log.handler.syslog.my-syslog-handler.enable=true quarkus.log.handler.syslog.my-syslog-handler.app-name=my-application quarkus.log.handler.syslog.my-syslog-handler.format=%d{yyyy-MM-dd HH:mm:ss} [com.example] %s%e%n quarkus.log.category."com.example".handlers=my-syslog-handler quarkus.log.category."com.example".use-parent-handlers=false
有关其配置的详细信息,请参阅 Syslog logging configuration参考。
For details about its configuration, see the quarkus-core_section_quarkus-log-syslog reference.
Add a logging filter to your log handler
日志处理程序(例如控制台日志处理程序)可以与 filter链接,以确定是否应记录日志记录。
Log handlers, such as the console log handler, can be linked with a filter that determines whether a log record should be logged.
若要注册日志记录筛选器:
To register a logging filter:
-
Annotate a
final
class that implementsjava.util.logging.Filter
with@io.quarkus.logging.LoggingFilter
, and set thename
property:[source, java] .An example of writing a filter:
package com.example; import io.quarkus.logging.LoggingFilter; import java.util.logging.Filter; import java.util.logging.LogRecord; @LoggingFilter(name = "my-filter") public final class TestFilter implements Filter { private final String part; public TestFilter(@ConfigProperty(name = "my-filter.part") String part) { this.part = part; } @Override public boolean isLoggable(LogRecord record) { return !record.getMessage().contains(part); } }
在这个示例中,我们将包含特定文本的日志记录从控制台日志中排除。对于特定文本进行筛选不会进行硬编码;相反,它从 my-filter.part
配置属性中读取。
In this example, we exclude log records containing specific text from console logs.
The specific text to filter on is not hard-coded; instead, it is read from the my-filter.part
configuration property.
application.properties
:my-filter.part=TEST
-
Attach the filter to the corresponding handler using the
filter
configuration property, located inapplication.properties
:[source, properties]
quarkus.log.console.filter=my-filter
Examples of logging configurations
以下示例显示了一些可以在 Quarkus 中配置日志记录的方法:
The following examples show some of the ways in which you can configure logging in Quarkus:
quarkus.log.console.format=%d{HH:mm:ss} %-5p [%c{2.}] (%t) %s%e%n
quarkus.log.console.level=DEBUG
quarkus.console.color=false
quarkus.log.category."io.quarkus".level=INFO
如果在命令行中添加这些属性,请确保 |
If you add these properties in the command line, ensure |
quarkus.log.file.enable=true
# Send output to a trace.log file under the /tmp directory
quarkus.log.file.path=/tmp/trace.log
quarkus.log.file.level=TRACE
quarkus.log.file.format=%d{HH:mm:ss} %-5p [%c{2.}] (%t) %s%e%n
# Set 2 categories (io.quarkus.smallrye.jwt, io.undertow.request.security) to TRACE level
quarkus.log.min-level=TRACE
quarkus.log.category."io.quarkus.smallrye.jwt".level=TRACE
quarkus.log.category."io.undertow.request.security".level=TRACE
由于我们不会更改根记录器,控制台日志只将包含 |
As we don’t change the root logger, the console log will only contain |
# Send output to a trace.log file under the /tmp directory
quarkus.log.file.path=/tmp/trace.log
quarkus.log.console.format=%d{HH:mm:ss} %-5p [%c{2.}] (%t) %s%e%n
# Configure a named handler that logs to console
quarkus.log.handler.console."STRUCTURED_LOGGING".format=%e%n
# Configure a named handler that logs to file
quarkus.log.handler.file."STRUCTURED_LOGGING_FILE".enable=true
quarkus.log.handler.file."STRUCTURED_LOGGING_FILE".format=%e%n
# Configure the category and link the two named handlers to it
quarkus.log.category."io.quarkus.category".level=INFO
quarkus.log.category."io.quarkus.category".handlers=STRUCTURED_LOGGING,STRUCTURED_LOGGING_FILE
# configure a named file handler that sends the output to 'quarkus.log'
quarkus.log.handler.file.CONSOLE_MIRROR.enable=true
quarkus.log.handler.file.CONSOLE_MIRROR.path=quarkus.log
# attach the handler to the root logger
quarkus.log.handlers=CONSOLE_MIRROR
Centralized log management
使用集中式位置有效地收集、存储和分析来自应用程序的各种组件和实例的日志数据。
Use a centralized location to efficiently collect, store, and analyze log data from various components and instances of the application.
要将日志发送到 Graylog、Logstash 或 Fluentd 这样的集中式工具,请参阅 Quarkus Centralized log management 指南。
To send logs to a centralized tool such as Graylog, Logstash, or Fluentd, see the Quarkus Centralized log management guide.
Configure logging for @QuarkusTest
通过将 java.util.logging.manager
系统属性设置为 org.jboss.logmanager.LogManager
,为 @QuarkusTest
启用适当的日志记录。
Enable proper logging for @QuarkusTest
by setting the java.util.logging.manager
system property to org.jboss.logmanager.LogManager
.
系统属性必须在早期设置才能生效,因此建议在构建系统中配置它。
The system property must be set early on to be effective, so it is recommended to configure it in the build system.
java.util.logging.manager
system property in the Maven Surefire plugin configuration<build>
<plugins>
<plugin>
<artifactId>maven-surefire-plugin</artifactId>
<version>${surefire-plugin.version}</version>
<configuration>
<systemPropertyVariables>
<java.util.logging.manager>org.jboss.logmanager.LogManager</java.util.logging.manager> 1
<quarkus.log.level>DEBUG</quarkus.log.level> 2
<maven.home>${maven.home}</maven.home>
</systemPropertyVariables>
</configuration>
</plugin>
</plugins>
</build>
1 | Make sure the org.jboss.logmanager.LogManager is used. |
2 | Enable debug logging for all logging categories. |
对于 Gradle,请将以下配置添加到 build.gradle
文件:
For Gradle, add the following configuration to the build.gradle
file:
test {
systemProperty "java.util.logging.manager", "org.jboss.logmanager.LogManager"
}
See also Running @QuarkusTest
from an IDE.
Use other logging APIs
Quarkus 依赖 JBoss Logging 库来满足所有日志要求。
Quarkus relies on the JBoss Logging library for all the logging requirements.
假如你使用依赖于其他日志记录库(如 Apache Commons Logging、Log4j 或 SLF4J)的库,在这种情况下,将它们排除在依赖项之外,并使用 JBoss Logging 适配器之一。
Suppose you use libraries that depend on other logging libraries, such as Apache Commons Logging, Log4j, or SLF4J. In that case, exclude them from the dependencies and use one of the JBoss Logging adapters.
在生成本机可执行文件时,这一点尤其重要,因为在编译本机可执行文件时,你可能会遇到类似于以下的问题:
This is especially important when building native executables, as you could encounter issues similar to the following when compiling the native executable:
Caused by java.lang.ClassNotFoundException: org.apache.commons.logging.impl.LogFactoryImpl
日志记录实现未包含在本地可执行文件中,但你可以使用 JBoss Logging 适配器解决此问题。
The logging implementation is not included in the native executable, but you can resolve this issue using JBoss Logging adapters.
正如在下一章中所解释的,这些适配器适用于常用的开源日志记录组件。
These adapters are available for popular open-source logging components, as explained in the next chapter.
Add a logging adapter to your application
对于每个并非 jboss-logging
的日志记录 API:
For each logging API that is not jboss-logging
:
-
Add a logging adapter library to ensure that messages logged through these APIs are routed to the JBoss Log Manager backend.
Quarkus 扩展项依赖库的这一步骤并不必要,其中扩展项会自动处理它。
This step is unnecessary for libraries that are dependencies of a Quarkus extension where the extension handles it automatically. |
-
Apache Commons Logging:[source, xml] .pom.xml
<dependency> <groupId>org.jboss.logging</groupId> <artifactId>commons-logging-jboss-logging</artifactId> </dependency>
implementation("org.jboss.logging:commons-logging-jboss-logging")
-
Log4j:[source, xml] .pom.xml
<dependency> <groupId>org.jboss.logmanager</groupId> <artifactId>log4j-jboss-logmanager</artifactId> </dependency>
implementation("org.jboss.logmanager:log4j-jboss-logmanager")
-
Log4j 2:[source, xml] .pom.xml
<dependency> <groupId>org.jboss.logmanager</groupId> <artifactId>log4j2-jboss-logmanager</artifactId> </dependency>
implementation("org.jboss.logmanager:log4j2-jboss-logmanager")
不要包含任何 Log4j 依赖项,因为 Do not include any Log4j dependencies because the |
-
SLF4J:[source, xml] .pom.xml
<dependency> <groupId>org.jboss.slf4j</groupId> <artifactId>slf4j-jboss-logmanager</artifactId> </dependency>
implementation("org.jboss.slf4j:slf4j-jboss-logmanager")
-
Verify whether the logs generated by the added library adhere to the same format as the other Quarkus logs.
Use MDC to add contextual log information
Quarkus 覆盖日志映射诊断上下文 (MDC) 以提高与它的反应核心的兼容性。
Quarkus overrides the logging Mapped Diagnostic Context (MDC) to improve the compatibility with its reactive core.
Add and read MDC data
要在 MDC 中添加数据并将其提取到日志输出中,请执行以下操作:
To add data to the MDC and extract it in your log output:
-
Use the
MDC
class to set the data. -
Customize the log format to use
%X{mdc-key}
.
让我们考虑以下代码:
Let’s consider the following code:
io.quarkus.logging.Log
package me.sample;
import io.quarkus.logging.Log;
import jakarta.ws.rs.GET;
import jakarta.ws.rs.Path;
import org.jboss.logmanager.MDC;
import java.util.UUID;
@Path("/hello/jboss")
public class GreetingResourceJbossLogging {
@GET
@Path("/test")
public String greeting() {
MDC.put("request.id", UUID.randomUUID().toString());
MDC.put("request.path", "/hello/test");
Log.info("request received");
return "hello world!";
}
}
如果你使用以下行配置日志格式:
If you configure the log format with the following line:
quarkus.log.console.format=%d{HH:mm:ss} %-5p request.id=%X{request.id} request.path=%X{request.path} [%c{2.}] (%t) %s%n
你将获得包含 MDC 数据的消息:
You get messages containing the MDC data:
08:48:13 INFO request.id=c37a3a36-b7f6-4492-83a1-de41dbc26fe2 request.path=/hello/test [me.sa.GreetingResourceJbossLogging] (executor-thread-1) request received
MDC and supported logging APIs
MDC 类根据您使用的 API 稍有不同。但是,这些 API 非常相似:
Depending on the API you use, the MDC class is slightly different. However, the APIs are very similar:
-
Log4j 1 -
org.apache.log4j.MDC.put(key, value)
-
Log4j 2 -
org.apache.logging.log4j.ThreadContext.put(key, value)
-
SLF4J -
org.slf4j.MDC.put(key, value)
MDC propagation
在 Quarkus 中,MDC 供应商具有处理反应式上下文的特定实现,确保在反应式和异步处理期间传播 MDC 数据。
In Quarkus, the MDC provider has a specific implementation for handling the reactive context, ensuring that MDC data is propagated during reactive and asynchronous processing.
因此,您仍然可以在各种场景中访问 MDC 数据:
As a result, you can still access the MDC data in various scenarios:
-
After asynchronous calls, for example, when a REST client returns a Uni.
-
In code submitted to
org.eclipse.microprofile.context.ManagedExecutor
. -
In code executed with
vertx.executeBlocking()
.
如果适用,MDC 数据将存储在 _duplicated context_中,这是一个用于处理单个任务(请求)的隔离上下文。 |
If applicable, MDC data is stored in a duplicated context, which is an isolated context for processing a single task (request). |