Проблемы при миграции с log4j1.2.17 на log4j2.13.0 с slf4j
Ниже приведены сделанные изменения. Журналы регистрируются в файле logging.log вместо файла журнала, упомянутого в файле log4j2.properties.
Заменен log4j-bundle-1.2.17.jar на log4j-api-2.13.0.jar и log4j-core-2.13.0.jar Заменен slf4j-log4j12-jar-1.7.2 на log4j-slf4j -impl-2.13.0.jar Сохранить slf4j-api-jar-1.7.2.jar как есть.
Код ниже находится в log4j1.2.17
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.log4j.LogManager;
import org.apache.log4j.PropertyConfigurator;
private final Logger log = LoggerFactory.getLogger(ABC.class);
Properties properties = new Properties();
try (InputStream inputStream = new FileInputStream(<Path to log4j.properties file>)) {
properties.load(inputStream);
}
properties.setProperty("log4j.appender.file.File", <Path to log file name>);
LogManager.resetConfiguration();
PropertyConfigurator.configure(properties);
Заменен на следующий код для log4j2
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.core.config.Configuration;
import org.apache.logging.log4j.core.config.ConfigurationSource;
import org.apache.logging.log4j.core.config.Configurator;
import org.apache.logging.log4j.core.config.properties.PropertiesConfigurationBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.apache.logging.log4j.core.LoggerContext;
private final Logger log = LoggerFactory.getLogger(ABC.class);
Properties properties = new Properties();
try (InputStream inputStream = new FileInputStream(<Path to log4j.properties file>)) {
properties.load(inputStream);
}
LoggerContext context = (LoggerContext)LogManager.getContext(false);
Configuration config = new PropertiesConfigurationBuilder() .setConfigurationSource(ConfigurationSource.NULL_SOURCE)
.setRootProperties(properties) .setLoggerContext(context) .build();
context.setConfiguration(config);
Configurator.initialize(config);
Ниже приведено содержимое файла log4j2.properties:
# Declare loggers
name=LoggingConfig
appenders=a_console, a_rolling
rootLogger.level=debug
rootLogger.appenderRefs=ar_console,ar_rolling
rootLogger.appenderRef.ar_console.ref=StdoutAppender
rootLogger.appenderRef.ar_rolling.ref=DailyRollingAppender
# Console logger
appender.a_console.type=Console
appender.a_console.name=StdoutAppender
appender.a_console.layout.type=PatternLayout
appender.a_console.layout.pattern=%d{ISO8601} [%t] %-5p (%F\:%L) - %m%n
# File logger
appender.a_rolling.type=RollingFile
appender.a_rolling.name=DailyRollingAppender
appender.a_rolling.layout.pattern=%d{ISO8601} [%t] %-5p (%F\:%L) - %m%n
appender.a_rolling.fileName=log4j2-sample.log
appender.a_rolling.filePattern=log4j2-sample-%d{yyyy-MM-dd}.log
appender.a_rolling.layout.type=PatternLayout
appender.a_rolling.policies.type=Policies
appender.a_rolling.policies.time.type=TimeBasedTriggeringPolicy
appender.a_rolling.policies.time.interval=1