Java slf4j with log4j

Log4j 2 SLF4J Binding

The Log4j 2 SLF4J Binding allows applications coded to the SLF4J API to use Log4j 2 as the implementation.

Due to a break in compatibility in the SLF4J binding, as of release 2.19.0 two SLF4J to Log4j Adapters are provided.

  1. log4j-slf4j-impl should be used with SLF4J 1.7.x releases or older.
  2. log4j-slf4j2-impl should be used with SLF4J 2.0.x releases or newer.

Applications that take advantage of the Java Module System should use SLF4J 2.0.x and log4j-slf4j2-impl.

As of release 2.19.0 the log4j-slf4j18-impl module targetting the unreleased SLF4J 1.8.x series has been removed.

Requirements

The Log4j 2 SLF4J Binding has a dependency on the Log4j 2 API as well as the SLF4J API. For more information, see Runtime Dependencies.

Usage

The SLF4J binding provided in this component cause all the SLF4J APIs to be routed to Log4j 2. Simply include the Log4j 2 SLF4J Binding jar along with the Log4j 2 jars and SLF4J API jar to cause all SLF4J logging to be handled by Log4j 2.

Use of the Log4j 2 SLF4J Binding (log4j-slf4j-impl-2.0.jar) together with the SLF4J adapter (log4j-to-slf4j-2.0.jar) should never be attempted, as it will cause events to endlessly be routed between SLF4J and Log4j 2.

Copyright © 1999-2023 The Apache Software Foundation. All Rights Reserved.
Apache Logging, Apache Log4j, Log4j, Apache, the Apache feather logo, and the Apache Logging project logo are trademarks of The Apache Software Foundation.

Источник

Log4j2 with SLF4J Configuration

Learn to configure Log4j2 logging with SLF4J APIs. We will look at required dependencies, sample configuration and a demo to use the log statements.

1. Log4j2 and SLF4j Binding Dependencies

To make Log4j2 work with SLF4J, we need to include the following 3 dependencies. Click on the respective links to get the latest version of each.

  • log4j-slf4j-impl.jar – Log4j 2 SLF4J binding. It allows applications coded to the SLF4J API to use Log4j2 as the implementation.
  • log4j-api.jar – provides the adapter components required for implementers to create a logging implementation.
  • log4j-core.jar – core Log4j Implementation classes.

The Maven and Gradle dependencies can be copied as below.

 org.apache.logging.log4j log4j-api 2.20.0  org.apache.logging.log4j log4j-core 2.20.0  org.apache.logging.log4j log4j-slf4j-impl 2.20.0 

Next is to provide a log4j2.properties, log4j2.xml or log4j2.json file which will configure the required loggers and appenders. Place the configuration file are in the resources folder or application classpath. All log statements will log using these loggers.

We are taking the example for XML configuration and using console logging for demo purposes. You can use one of the other useful logging patterns as well.

Write the log statements in the application code with classes Logger and LoggerFactory. Both classes come from the package org.slf4j .

import org.slf4j.Logger; import org.slf4j.LoggerFactory; public class Main < public static void main(final String[] args) < Logger logger = LoggerFactory.getLogger(Main.class); logger.info("Hello World !!"); >> 

Run the main() method and observe the output in the console.

2021-12-13 22:08:14 INFO Main - Hello World !!

That’s all for log4j2 with slf4j configuration example.

Источник

Подключаем к нашему JavaRush проекту логирование (slf4f и log4j)

Java-университет

Что в целом логично. slf4j — это обёртка, а вокруг чего мы его обернули? Ничего? Ну вот и получили ошибку. Обернуть можно вокруг чего-то одного из списка: log4j, util.logging, NOP, System.err, JCL, logback. Подробнее в оригинальной инструкции. Рассмотрим на примере log4j и System.err: 1) Начнём с простого, с System.err. Для этого к предыдущей зависимости (slf4j-api) добавляем вот эту (slf4j-simple).

  org.slf4j slf4j-simple 1.7.30  

Версии берём одинаковые, на 10 мая 2021 это 1.7.30. Если будете брать зависимости с https://mvnrepository.com/ не забудьте удалить

А иначе ваши логи будут работать только в тестах. 2) Теперь попробуем настроить log4j, для этого нам нужно добавить 2 зависимости: сам log4j и прослойку между slf4j и log4j (slf4j-log4j12). Выглядит это так:

  org.slf4j slf4j-log4j12 1.7.30  log4j log4j 1.2.17  

Понятное дело, что (slf4j-simple) нам нужно удалить, чтобы slf4j не путался, с каким логгером ему работать. А (slf4j-api) оставить, так как это и есть slf4j. По поводу 2х добавленных зависимостей. log4j мы добавляем старый (от мая 2012, хз почему, можете поэксперементировать с другими). Версия у него 1.2.17. Чтобы slf4j смог с ним работать, нужна соответствующая прослойка — slf4j-log4j12, где последние символы (12) — означают версию log4j. При этом версия slf4j-api и slf4j-log4j12 должна быть 1.7.30 — последняя стабильная на текущий момент. После того, как вы подключили зависимости и обновили Maven проект. Для работы log4j нужно ещё 2 вещи: 1) Настроить конфигурационный файл. Читаем, выбираем, копируем. 2) Вчитать конфигурацию log4j перед работой:

 PropertyConfigurator.configure("d:\\Java\\JavaRushTasks\\4.JavaCollections\\log4j.properties"); 

ну или где там у вас файлик лежит. Если вы хотите видеть все логи — не забудьте поставить уровень логгирования ALL. Дописываем в резюме — log4j & slf4j. Вы восхитительны! Если помогло — лайк, подписка, колокольчик!)))

Источник

Читайте также:  Java процедурный язык программирования
Оцените статью