Log4j API :: Apache Log4j (original) (raw)
To log, you need a Logger instance which you will retrieve from the LogManager. These are all part of the log4j-api
module, which you can install as follows:
- Maven
- Gradle
<dependency>
<groupId>org.apache.logging.log4j</groupId>
<artifactId>log4j-api</artifactId>
<version>${log4j-api.version}</version>
</dependency>
implementation 'org.apache.logging.log4j:log4j-api:${log4j-api.version}'
You can use the Logger
instance to log by using methods like info()
, warn()
, error()
, etc. These methods are named after the log levels they represent, a way to categorize log events by severity. The log message can also contain placeholders written as {}
that will be replaced by the arguments passed to the method.
import org.apache.logging.log4j.Logger;
import org.apache.logging.log4j.LogManager;
public class DbTableService {
private static final Logger LOGGER = LogManager.getLogger(); (1)
public void truncateTable(String tableName) throws IOException {
LOGGER.warn("truncating table `{}`", tableName); (2)
db.truncate(tableName);
}
}
1 | The returned Logger instance is thread-safe and reusable. Unless explicitly provided as an argument, getLogger() associates the returned Logger with the enclosing class, that is, DbTableService in this example. |
---|---|
2 | The placeholder {} in the message will be replaced with the value of tableName |
The generated log event, which contain the user-provided log message and log level (i.e., WARN
), will be enriched with several other implicitly derived contextual information: timestamp, class & method name, line number, etc.
**What happens to the generated log event will vary significantly depending on the configuration used.**It can be pretty-printed to the console, written to a file, or get totally ignored due to insufficient severity or some other filtering.
Log levels are used to categorize log events by severity and control the verbosity of the logs. Log4j contains various predefined levels, but the most common are DEBUG
, INFO
, WARN
, and ERROR
. With them, you can filter out less important logs and focus on the most critical ones. Previously we used Logger#warn()
to log a warning message, which could mean that something is not right, but the application can continue. Log levels have a priority, and WARN
is less severe than ERROR
.
Exceptions are often also errors. In this case, we might use the ERROR
log level. Make sure to log exceptions that have diagnostics value. This is simply done by passing the exception as the last argument to the log method:
LOGGER.warn("truncating table `{}`", tableName);
try {
db.truncate(tableName);
} catch (IOException exception) {
LOGGER.error("failed truncating table `{}`", tableName, exception); (1)
throw new IOException("failed truncating table: " + tableName, exception);
}
1 | By using error() instead of warn(), we signal that the operation failed. |
---|
While there is only one placeholder in the message, we pass two arguments: tableName
and exception
. Log4j will attach the last extra argument of type Throwable
in a separate field to the generated log event.
| | Log messages are often used interchangeably with log events. While this simplification holds for several cases, it is not technically correct. A log event, capturing the logging context (level, logger name, instant, etc.) along with the log message, is generated by the logging implementation (e.g., Log4j Core) when a user issues a log using a logger, e.g., LOGGER.info("Hello, world!"). Hence, log events are compound objects containing log messages. Click for an introduction to log event fields Log events contain fields that can be classified into three categories: Some fields are provided explicitly, in a Logger method call. The most important are the log level and the log message, which is a description of what happened, and it is addressed to humans. Some fields are contextual (e.g., Thread Context) and are either provided explicitly by developers of other parts of the application, or is injected by Java instrumentation. The last category of fields is those that are computed automatically by the logging implementation employed. For clarity’s sake let us look at a log event formatted as JSON: { (1) "log.level": "INFO", "message": "Unable to insert data into my_table.", "error.type": "java.lang.RuntimeException", "error.message": null, "error.stack_trace": [ { "class": "com.example.Main", "method": "doQuery", "file.name": "Main.java", "file.line": 36 }, { "class": "com.example.Main", "method": "main", "file.name": "Main.java", "file.line": 25 } ], "marker": "SQL", "log.logger": "com.example.Main", (2) "tags": [ "SQL query" ], "labels": { "span_id": "3df85580-f001-4fb2-9e6e-3066ed6ddbb1", "trace_id": "1b1f8fc9-1a0c-47b0-a06f-af3c1dd1edf9" }, (3) "@timestamp": "2024-05-23T09:32:24.163Z", "log.origin.class": "com.example.Main", "log.origin.method": "doQuery", "log.origin.file.name": "Main.java", "log.origin.file.line": 36, "process.thread.id": 1, "process.thread.name": "main", "process.thread.priority": 5 } 1 Explicitly supplied fields: log.level The level of the event, either explicitly provided as an argument to the logger call, or implied by the name of the logger method message The log message that describes what happened error.* An optional Throwable explicitly passed as an argument to the logger call marker An optional marker explicitly passed as an argument to the logger call log.logger The logger name provided explicitly to LogManager.getLogger() or inferred by Log4j API 2 Contextual fields: 3 Logging backend specific fields. In case you are using Log4j Core, the following fields can be automatically generated: @timestamp The instant of the logger call log.origin.* The location of the logger call in the source code process.thread.* The name of the Java thread, where the logger is called | | ------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |