Reduce Log4J API Exposures (#5189)

Reduce the number of places that expose Log4J classes as a part of the
interfaces for methods and classes. While Log4j remains the default we
still need to be able to function when the Log4J jars are removed from
the classpath.

Signed-off-by: Danno Ferrin <danno.ferrin@swirldslabs.com>
pull/5204/head
Danno Ferrin 2 years ago committed by GitHub
parent 62f4a51191
commit 3e35dba092
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 5
      acceptance-tests/tests/src/test/java/org/hyperledger/besu/tests/acceptance/privacy/PrivacyGroupAcceptanceTest.java
  2. 16
      besu/src/main/java/org/hyperledger/besu/Besu.java
  3. 18
      besu/src/main/java/org/hyperledger/besu/cli/BesuCommand.java
  4. 10
      besu/src/main/java/org/hyperledger/besu/cli/error/BesuParameterExceptionHandler.java
  5. 9
      besu/src/main/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOption.java
  6. 11
      besu/src/main/java/org/hyperledger/besu/cli/subcommands/RetestethSubCommand.java
  7. 3
      besu/src/test/java/org/hyperledger/besu/cli/BesuCommandTest.java
  8. 4
      besu/src/test/java/org/hyperledger/besu/cli/options/stable/LoggingLevelOptionTest.java
  9. 4
      consensus/merge/src/test/java/org/hyperledger/besu/consensus/merge/blockcreation/MergeReorgTest.java
  10. 14
      ethereum/api/src/main/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevel.java
  11. 4
      ethereum/api/src/test/java/org/hyperledger/besu/ethereum/api/jsonrpc/internal/methods/AdminChangeLogLevelTest.java
  12. 6
      ethereum/core/src/test/java/org/hyperledger/besu/ethereum/vm/AbstractRetryingTest.java
  13. 2
      ethereum/evmtool/build.gradle
  14. 2
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/B11rSubCommand.java
  15. 2
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/CodeValidateSubCommand.java
  16. 9
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/EvmToolCommand.java
  17. 11
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/StateTestSubCommand.java
  18. 8
      ethereum/evmtool/src/main/java/org/hyperledger/besu/evmtool/T8nSubCommand.java
  19. 16
      gradle/verification-metadata.xml
  20. 1
      gradle/versions.gradle
  21. 28
      util/src/main/java/org/hyperledger/besu/util/Log4j2ConfiguratorUtil.java
  22. 54
      util/src/main/java/org/hyperledger/besu/util/LogConfigurator.java

@ -24,7 +24,7 @@ import org.hyperledger.besu.tests.acceptance.dsl.privacy.PrivacyAcceptanceTestBa
import org.hyperledger.besu.tests.acceptance.dsl.privacy.PrivacyNode; import org.hyperledger.besu.tests.acceptance.dsl.privacy.PrivacyNode;
import org.hyperledger.besu.tests.acceptance.dsl.privacy.account.PrivacyAccountResolver; import org.hyperledger.besu.tests.acceptance.dsl.privacy.account.PrivacyAccountResolver;
import org.hyperledger.besu.tests.web3j.generated.EventEmitter; import org.hyperledger.besu.tests.web3j.generated.EventEmitter;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import org.hyperledger.enclave.testutil.EnclaveEncryptorType; import org.hyperledger.enclave.testutil.EnclaveEncryptorType;
import org.hyperledger.enclave.testutil.EnclaveType; import org.hyperledger.enclave.testutil.EnclaveType;
@ -34,7 +34,6 @@ import java.util.Arrays;
import java.util.Collection; import java.util.Collection;
import java.util.Optional; import java.util.Optional;
import org.apache.logging.log4j.Level;
import org.junit.Test; import org.junit.Test;
import org.junit.runner.RunWith; import org.junit.runner.RunWith;
import org.junit.runners.Parameterized; import org.junit.runners.Parameterized;
@ -99,7 +98,7 @@ public class PrivacyGroupAcceptanceTest extends PrivacyAcceptanceTestBase {
@Test @Test
public void nodeCanCreatePrivacyGroup() { public void nodeCanCreatePrivacyGroup() {
Log4j2ConfiguratorUtil.setLevel("", Level.DEBUG); LogConfigurator.setLevel("", "DEBUG");
final String privacyGroupId = final String privacyGroupId =
alice.execute( alice.execute(
privacyTransactions.createPrivacyGroup( privacyTransactions.createPrivacyGroup(

@ -62,7 +62,15 @@ public final class Besu {
} }
private static Logger setupLogging() { private static Logger setupLogging() {
try {
// This call is to test if log4j classes are available
((Log4J2LoggerFactory) Log4J2LoggerFactory.INSTANCE).newInstance("");
InternalLoggerFactory.setDefaultFactory(Log4J2LoggerFactory.INSTANCE); InternalLoggerFactory.setDefaultFactory(Log4J2LoggerFactory.INSTANCE);
} catch (Throwable t) {
System.out.printf(
"Could not set netty log4j logger factory: %s - %s%n",
t.getClass().getSimpleName(), t.getMessage());
}
try { try {
System.setProperty( System.setProperty(
"vertx.logger-delegate-factory-class-name", "vertx.logger-delegate-factory-class-name",
@ -70,10 +78,10 @@ public final class Besu {
System.setProperty( System.setProperty(
"log4j.configurationFactory", BesuLoggingConfigurationFactory.class.getName()); "log4j.configurationFactory", BesuLoggingConfigurationFactory.class.getName());
System.setProperty("log4j.skipJansi", String.valueOf(false)); System.setProperty("log4j.skipJansi", String.valueOf(false));
} catch (SecurityException e) { } catch (Throwable t) {
System.out.println( System.out.printf(
"Could not set logging system property as the security manager prevented it:" "Could not set logging system property: %s - %s%n",
+ e.getMessage()); t.getClass().getSimpleName(), t.getMessage());
} }
final Logger logger = LoggerFactory.getLogger(Besu.class); final Logger logger = LoggerFactory.getLogger(Besu.class);
Thread.setDefaultUncaughtExceptionHandler(slf4jExceptionHandler(logger)); Thread.setDefaultUncaughtExceptionHandler(slf4jExceptionHandler(logger));

@ -186,7 +186,7 @@ import org.hyperledger.besu.services.SecurityModuleServiceImpl;
import org.hyperledger.besu.services.StorageServiceImpl; import org.hyperledger.besu.services.StorageServiceImpl;
import org.hyperledger.besu.services.kvstore.InMemoryStoragePlugin; import org.hyperledger.besu.services.kvstore.InMemoryStoragePlugin;
import org.hyperledger.besu.util.InvalidConfigurationException; import org.hyperledger.besu.util.InvalidConfigurationException;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import org.hyperledger.besu.util.NetworkUtility; import org.hyperledger.besu.util.NetworkUtility;
import org.hyperledger.besu.util.PermissioningConfigurationValidator; import org.hyperledger.besu.util.PermissioningConfigurationValidator;
import org.hyperledger.besu.util.number.Fraction; import org.hyperledger.besu.util.number.Fraction;
@ -240,7 +240,6 @@ import net.consensys.quorum.mainnet.launcher.LauncherManager;
import net.consensys.quorum.mainnet.launcher.config.ImmutableLauncherConfig; import net.consensys.quorum.mainnet.launcher.config.ImmutableLauncherConfig;
import net.consensys.quorum.mainnet.launcher.exception.LauncherException; import net.consensys.quorum.mainnet.launcher.exception.LauncherException;
import net.consensys.quorum.mainnet.launcher.util.ParseArgsHelper; import net.consensys.quorum.mainnet.launcher.util.ParseArgsHelper;
import org.apache.logging.log4j.Level;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
import org.slf4j.Logger; import org.slf4j.Logger;
@ -1440,7 +1439,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
* @param args arguments to Besu command * @param args arguments to Besu command
* @return success or failure exit code. * @return success or failure exit code.
*/ */
@VisibleForTesting
public int parse( public int parse(
final IExecutionStrategy resultHandler, final IExecutionStrategy resultHandler,
final BesuParameterExceptionHandler parameterExceptionHandler, final BesuParameterExceptionHandler parameterExceptionHandler,
@ -1553,7 +1551,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
private void registerConverters() { private void registerConverters() {
commandLine.registerConverter(Address.class, Address::fromHexStringStrict); commandLine.registerConverter(Address.class, Address::fromHexStringStrict);
commandLine.registerConverter(Bytes.class, Bytes::fromHexString); commandLine.registerConverter(Bytes.class, Bytes::fromHexString);
commandLine.registerConverter(Level.class, Level::valueOf);
commandLine.registerConverter(MetricsProtocol.class, MetricsProtocol::fromString); commandLine.registerConverter(MetricsProtocol.class, MetricsProtocol::fromString);
commandLine.registerConverter(UInt256.class, (arg) -> UInt256.valueOf(new BigInteger(arg))); commandLine.registerConverter(UInt256.class, (arg) -> UInt256.valueOf(new BigInteger(arg)));
commandLine.registerConverter(Wei.class, (arg) -> Wei.of(Long.parseUnsignedLong(arg))); commandLine.registerConverter(Wei.class, (arg) -> Wei.of(Long.parseUnsignedLong(arg)));
@ -1796,14 +1793,14 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
*/ */
public void configureLogging(final boolean announce) { public void configureLogging(final boolean announce) {
// To change the configuration if color was enabled/disabled // To change the configuration if color was enabled/disabled
Log4j2ConfiguratorUtil.reconfigure(); LogConfigurator.reconfigure();
// set log level per CLI flags // set log level per CLI flags
final Level logLevel = loggingLevelOption.getLogLevel(); final String logLevel = loggingLevelOption.getLogLevel();
if (logLevel != null) { if (logLevel != null) {
if (announce) { if (announce) {
System.out.println("Setting logging level to " + logLevel.name()); System.out.println("Setting logging level to " + logLevel);
} }
Log4j2ConfiguratorUtil.setAllLevels("", logLevel); LogConfigurator.setLevel("", logLevel);
} }
} }
@ -3109,7 +3106,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
try { try {
besuPluginContext.stopPlugins(); besuPluginContext.stopPlugins();
runner.close(); runner.close();
Log4j2ConfiguratorUtil.shutdown(); LogConfigurator.shutdown();
} catch (final Exception e) { } catch (final Exception e) {
logger.error("Failed to stop Besu"); logger.error("Failed to stop Besu");
} }
@ -3306,7 +3303,6 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
* *
* @return instance of BesuParameterExceptionHandler * @return instance of BesuParameterExceptionHandler
*/ */
@VisibleForTesting
public BesuParameterExceptionHandler parameterExceptionHandler() { public BesuParameterExceptionHandler parameterExceptionHandler() {
return new BesuParameterExceptionHandler(this::getLogLevel); return new BesuParameterExceptionHandler(this::getLogLevel);
} }
@ -3454,7 +3450,7 @@ public class BesuCommand implements DefaultCommandValues, Runnable {
} }
@VisibleForTesting @VisibleForTesting
Level getLogLevel() { String getLogLevel() {
return loggingLevelOption.getLogLevel(); return loggingLevelOption.getLogLevel();
} }

@ -17,21 +17,20 @@ package org.hyperledger.besu.cli.error;
import java.io.PrintWriter; import java.io.PrintWriter;
import java.util.function.Supplier; import java.util.function.Supplier;
import org.apache.logging.log4j.Level;
import picocli.CommandLine; import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
/** The custom parameter exception handler for Besu PicoCLI. */ /** The custom parameter exception handler for Besu PicoCLI. */
public class BesuParameterExceptionHandler implements CommandLine.IParameterExceptionHandler { public class BesuParameterExceptionHandler implements CommandLine.IParameterExceptionHandler {
private final Supplier<Level> levelSupplier; private final Supplier<String> levelSupplier;
/** /**
* Instantiates a new Besu parameter exception handler. * Instantiates a new Besu parameter exception handler.
* *
* @param levelSupplier the logging level supplier * @param levelSupplier the logging level supplier
*/ */
public BesuParameterExceptionHandler(final Supplier<Level> levelSupplier) { public BesuParameterExceptionHandler(final Supplier<String> levelSupplier) {
this.levelSupplier = levelSupplier; this.levelSupplier = levelSupplier;
} }
@ -39,8 +38,9 @@ public class BesuParameterExceptionHandler implements CommandLine.IParameterExce
public int handleParseException(final CommandLine.ParameterException ex, final String[] args) { public int handleParseException(final CommandLine.ParameterException ex, final String[] args) {
final CommandLine cmd = ex.getCommandLine(); final CommandLine cmd = ex.getCommandLine();
final PrintWriter err = cmd.getErr(); final PrintWriter err = cmd.getErr();
final Level logLevel = levelSupplier.get(); final String logLevel = levelSupplier.get();
if (logLevel != null && Level.DEBUG.isMoreSpecificThan(logLevel)) { if (logLevel != null
&& (logLevel.equals("DEBUG") || logLevel.equals("TRACE") || logLevel.equals("ALL"))) {
ex.printStackTrace(err); ex.printStackTrace(err);
} else { } else {
err.println(ex.getMessage()); err.println(ex.getMessage());

@ -16,7 +16,6 @@ package org.hyperledger.besu.cli.options.stable;
import java.util.Set; import java.util.Set;
import org.apache.logging.log4j.Level;
import picocli.CommandLine; import picocli.CommandLine;
import picocli.CommandLine.Model.CommandSpec; import picocli.CommandLine.Model.CommandSpec;
import picocli.CommandLine.Spec; import picocli.CommandLine.Spec;
@ -38,7 +37,7 @@ public class LoggingLevelOption {
/** The Picocli CommandSpec. Visible for testing. Injected by Picocli framework at runtime. */ /** The Picocli CommandSpec. Visible for testing. Injected by Picocli framework at runtime. */
@Spec CommandSpec spec; @Spec CommandSpec spec;
private Level logLevel; private String logLevel;
/** /**
* Sets log level. * Sets log level.
@ -52,9 +51,9 @@ public class LoggingLevelOption {
public void setLogLevel(final String logLevel) { public void setLogLevel(final String logLevel) {
if ("FATAL".equalsIgnoreCase(logLevel)) { if ("FATAL".equalsIgnoreCase(logLevel)) {
System.out.println("FATAL level is deprecated"); System.out.println("FATAL level is deprecated");
this.logLevel = Level.ERROR; this.logLevel = "ERROR";
} else if (ACCEPTED_VALUES.contains(logLevel.toUpperCase())) { } else if (ACCEPTED_VALUES.contains(logLevel.toUpperCase())) {
this.logLevel = Level.getLevel(logLevel.toUpperCase()); this.logLevel = logLevel.toUpperCase();
} else { } else {
throw new CommandLine.ParameterException( throw new CommandLine.ParameterException(
spec.commandLine(), "Unknown logging value: " + logLevel); spec.commandLine(), "Unknown logging value: " + logLevel);
@ -66,7 +65,7 @@ public class LoggingLevelOption {
* *
* @return the log level * @return the log level
*/ */
public Level getLogLevel() { public String getLogLevel() {
return logLevel; return logLevel;
} }
} }

@ -24,12 +24,11 @@ import org.hyperledger.besu.cli.util.VersionProvider;
import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration; import org.hyperledger.besu.ethereum.api.jsonrpc.JsonRpcConfiguration;
import org.hyperledger.besu.ethereum.retesteth.RetestethConfiguration; import org.hyperledger.besu.ethereum.retesteth.RetestethConfiguration;
import org.hyperledger.besu.ethereum.retesteth.RetestethService; import org.hyperledger.besu.ethereum.retesteth.RetestethService;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.net.InetAddress; import java.net.InetAddress;
import java.nio.file.Path; import java.nio.file.Path;
import org.apache.logging.log4j.Level;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import picocli.CommandLine.Command; import picocli.CommandLine.Command;
@ -106,10 +105,10 @@ public class RetestethSubCommand implements Runnable {
private void prepareLogging() { private void prepareLogging() {
// set log level per CLI flags // set log level per CLI flags
final Level logLevel = loggingLevelOption.getLogLevel(); final String logLevel = loggingLevelOption.getLogLevel();
if (logLevel != null) { if (logLevel != null) {
System.out.println("Setting logging level to " + logLevel.name()); System.out.println("Setting logging level to " + logLevel);
Log4j2ConfiguratorUtil.setAllLevels("", logLevel); LogConfigurator.setLevel("", logLevel);
} }
} }
@ -132,7 +131,7 @@ public class RetestethSubCommand implements Runnable {
() -> { () -> {
try { try {
retestethService.close(); retestethService.close();
Log4j2ConfiguratorUtil.shutdown(); LogConfigurator.shutdown();
} catch (final Exception e) { } catch (final Exception e) {
LOG.error("Failed to stop Besu Retesteth"); LOG.error("Failed to stop Besu Retesteth");
} }

@ -123,7 +123,6 @@ import com.google.common.io.Resources;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import org.apache.commons.io.FileUtils; import org.apache.commons.io.FileUtils;
import org.apache.commons.text.StringEscapeUtils; import org.apache.commons.text.StringEscapeUtils;
import org.apache.logging.log4j.Level;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.toml.Toml; import org.apache.tuweni.toml.Toml;
import org.apache.tuweni.toml.TomlParseResult; import org.apache.tuweni.toml.TomlParseResult;
@ -4979,7 +4978,7 @@ public class BesuCommandTest extends CommandTestAbstract {
public void logLevelIsSetByLoggingOption() { public void logLevelIsSetByLoggingOption() {
final TestBesuCommand command = parseCommand("--logging", "WARN"); final TestBesuCommand command = parseCommand("--logging", "WARN");
assertThat(command.getLogLevel()).isEqualTo(Level.WARN); assertThat(command.getLogLevel()).isEqualTo("WARN");
} }
@Test @Test

@ -39,7 +39,7 @@ public class LoggingLevelOptionTest {
@Test @Test
public void fatalLevelEqualsToError() { public void fatalLevelEqualsToError() {
levelOption.setLogLevel("fatal"); levelOption.setLogLevel("fatal");
assertThat(levelOption.getLogLevel()).isEqualTo(Level.ERROR); assertThat(levelOption.getLogLevel()).isEqualTo("ERROR");
} }
@Test @Test
@ -49,7 +49,7 @@ public class LoggingLevelOptionTest {
.forEach( .forEach(
level -> { level -> {
levelOption.setLogLevel(level.name()); levelOption.setLogLevel(level.name());
assertThat(levelOption.getLogLevel()).isEqualTo(level); assertThat(levelOption.getLogLevel()).isEqualTo(level.name());
}); });
} }

@ -41,7 +41,7 @@ import org.hyperledger.besu.ethereum.mainnet.ProtocolSchedule;
import org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket; import org.hyperledger.besu.ethereum.mainnet.feemarket.BaseFeeMarket;
import org.hyperledger.besu.ethereum.mainnet.feemarket.LondonFeeMarket; import org.hyperledger.besu.ethereum.mainnet.feemarket.LondonFeeMarket;
import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive; import org.hyperledger.besu.ethereum.worldstate.WorldStateArchive;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.util.ArrayList; import java.util.ArrayList;
import java.util.List; import java.util.List;
@ -109,7 +109,7 @@ public class MergeReorgTest implements MergeGenesisConfigHelper {
@Test @Test
public void reorgsAcrossTDDToDifferentTargetsWhenNotFinal() { public void reorgsAcrossTDDToDifferentTargetsWhenNotFinal() {
// Add N blocks to chain from genesis, where total diff is < TTD // Add N blocks to chain from genesis, where total diff is < TTD
Log4j2ConfiguratorUtil.setLevelDebug(BlockHeaderValidator.class.getName()); LogConfigurator.setLevel(BlockHeaderValidator.class.getName(), "DEBUG");
List<Block> endOfWork = subChain(genesisState.getBlock().getHeader(), 10, Difficulty.of(100L)); List<Block> endOfWork = subChain(genesisState.getBlock().getHeader(), 10, Difficulty.of(100L));
endOfWork.stream().forEach(this::appendBlock); endOfWork.stream().forEach(this::appendBlock);
assertThat(blockchain.getChainHead().getHeight()).isEqualTo(10L); assertThat(blockchain.getChainHead().getHeight()).isEqualTo(10L);

@ -21,13 +21,12 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.util.Arrays; import java.util.Arrays;
import java.util.Optional; import java.util.Optional;
import java.util.Set; import java.util.Set;
import org.apache.logging.log4j.Level;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -45,12 +44,11 @@ public class AdminChangeLogLevel implements JsonRpcMethod {
@Override @Override
public JsonRpcResponse response(final JsonRpcRequestContext requestContext) { public JsonRpcResponse response(final JsonRpcRequestContext requestContext) {
try { try {
final String rawLogLevel = requestContext.getRequiredParameter(0, String.class); final String logLevel = requestContext.getRequiredParameter(0, String.class);
if (!VALID_PARAMS.contains(rawLogLevel)) { if (!VALID_PARAMS.contains(logLevel)) {
return new JsonRpcErrorResponse( return new JsonRpcErrorResponse(
requestContext.getRequest().getId(), JsonRpcError.INVALID_PARAMS); requestContext.getRequest().getId(), JsonRpcError.INVALID_PARAMS);
} }
final Level logLevel = Level.toLevel(rawLogLevel);
final Optional<String[]> optionalLogFilters = final Optional<String[]> optionalLogFilters =
requestContext.getOptionalParameter(1, String[].class); requestContext.getOptionalParameter(1, String[].class);
optionalLogFilters.ifPresentOrElse( optionalLogFilters.ifPresentOrElse(
@ -64,8 +62,8 @@ public class AdminChangeLogLevel implements JsonRpcMethod {
} }
} }
private void setLogLevel(final String logFilter, final Level logLevel) { private void setLogLevel(final String logFilter, final String logLevel) {
LOG.debug("Setting {} logging level to {} ", logFilter, logLevel.name()); LOG.debug("Setting {} logging level to {} ", logFilter, logLevel);
Log4j2ConfiguratorUtil.setAllLevels(logFilter, logLevel); LogConfigurator.setLevel(logFilter, logLevel);
} }
} }

@ -22,7 +22,7 @@ import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcError;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcErrorResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcResponse;
import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse; import org.hyperledger.besu.ethereum.api.jsonrpc.internal.response.JsonRpcSuccessResponse;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import org.apache.logging.log4j.Level; import org.apache.logging.log4j.Level;
import org.junit.Before; import org.junit.Before;
@ -40,7 +40,7 @@ public class AdminChangeLogLevelTest {
@Before @Before
public void before() { public void before() {
adminChangeLogLevel = new AdminChangeLogLevel(); adminChangeLogLevel = new AdminChangeLogLevel();
Log4j2ConfiguratorUtil.setAllLevels("", Level.INFO); LogConfigurator.setLevel("", "INFO");
} }
@Test @Test

@ -14,7 +14,7 @@
*/ */
package org.hyperledger.besu.ethereum.vm; package org.hyperledger.besu.ethereum.vm;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import org.junit.Before; import org.junit.Before;
import org.junit.Test; import org.junit.Test;
@ -61,7 +61,7 @@ public abstract class AbstractRetryingTest {
} catch (final RuntimeException | AssertionError e) { } catch (final RuntimeException | AssertionError e) {
if (!"trace".equalsIgnoreCase(originalRootLogLevel) if (!"trace".equalsIgnoreCase(originalRootLogLevel)
|| !"trace".equalsIgnoreCase(originalEvmLogLevel)) { || !"trace".equalsIgnoreCase(originalEvmLogLevel)) {
// try again, this time with more logging so we can capture more information. // try again, this time with more logging, so we can capture more information.
System.setProperty("root.log.level", "trace"); System.setProperty("root.log.level", "trace");
System.setProperty("evm.log.level", "trace"); System.setProperty("evm.log.level", "trace");
resetLogging(); resetLogging();
@ -73,7 +73,7 @@ public abstract class AbstractRetryingTest {
} }
private void resetLogging() { private void resetLogging() {
Log4j2ConfiguratorUtil.reconfigure(); LogConfigurator.reconfigure();
} }
/** Subclasses should implement this method to run the actual JUnit test. */ /** Subclasses should implement this method to run the actual JUnit test. */

@ -31,7 +31,6 @@ jar {
} }
dependencies { dependencies {
api 'org.slf4j:slf4j-api'
implementation project(':besu') implementation project(':besu')
implementation project(':config') implementation project(':config')
@ -56,7 +55,6 @@ dependencies {
implementation 'com.google.guava:guava' implementation 'com.google.guava:guava'
implementation 'info.picocli:picocli' implementation 'info.picocli:picocli'
implementation 'io.vertx:vertx-core' implementation 'io.vertx:vertx-core'
implementation 'org.apache.logging.log4j:log4j-core'
annotationProcessor 'com.google.dagger:dagger-compiler' annotationProcessor 'com.google.dagger:dagger-compiler'

@ -23,6 +23,7 @@ import org.hyperledger.besu.ethereum.core.BlockHeaderBuilder;
import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions; import org.hyperledger.besu.ethereum.mainnet.MainnetBlockHeaderFunctions;
import org.hyperledger.besu.ethereum.referencetests.BlockchainReferenceTestCaseSpec.ReferenceTestBlockHeader; import org.hyperledger.besu.ethereum.referencetests.BlockchainReferenceTestCaseSpec.ReferenceTestBlockHeader;
import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput; import org.hyperledger.besu.ethereum.rlp.BytesValueRLPOutput;
import org.hyperledger.besu.util.LogConfigurator;
import java.io.FileNotFoundException; import java.io.FileNotFoundException;
import java.io.FileOutputStream; import java.io.FileOutputStream;
@ -129,6 +130,7 @@ public class B11rSubCommand implements Runnable {
@Override @Override
public void run() { public void run() {
LogConfigurator.setLevel("", "OFF");
objectMapper.setDefaultPrettyPrinter( objectMapper.setDefaultPrettyPrinter(
(new DefaultPrettyPrinter()) (new DefaultPrettyPrinter())
.withSpacesInObjectEntries() .withSpacesInObjectEntries()

@ -20,6 +20,7 @@ import static org.hyperledger.besu.evmtool.CodeValidateSubCommand.COMMAND_NAME;
import org.hyperledger.besu.evm.code.CodeFactory; import org.hyperledger.besu.evm.code.CodeFactory;
import org.hyperledger.besu.evm.code.CodeInvalid; import org.hyperledger.besu.evm.code.CodeInvalid;
import org.hyperledger.besu.evm.code.EOFLayout; import org.hyperledger.besu.evm.code.EOFLayout;
import org.hyperledger.besu.util.LogConfigurator;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
@ -68,6 +69,7 @@ public class CodeValidateSubCommand implements Runnable {
@Override @Override
public void run() { public void run() {
LogConfigurator.setLevel("", "OFF");
if (cliCode.isEmpty() && codeFile == null) { if (cliCode.isEmpty() && codeFile == null) {
try (BufferedReader in = new BufferedReader(new InputStreamReader(input, UTF_8))) { try (BufferedReader in = new BufferedReader(new InputStreamReader(input, UTF_8))) {
checkCodeFromBufferedReader(in); checkCodeFromBufferedReader(in);

@ -41,7 +41,7 @@ import org.hyperledger.besu.evm.tracing.OperationTracer;
import org.hyperledger.besu.evm.tracing.StandardJsonTracer; import org.hyperledger.besu.evm.tracing.StandardJsonTracer;
import org.hyperledger.besu.evm.worldstate.WorldState; import org.hyperledger.besu.evm.worldstate.WorldState;
import org.hyperledger.besu.evm.worldstate.WorldUpdater; import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.io.BufferedWriter; import java.io.BufferedWriter;
import java.io.ByteArrayInputStream; import java.io.ByteArrayInputStream;
@ -60,7 +60,6 @@ import java.util.Optional;
import com.google.common.base.Joiner; import com.google.common.base.Joiner;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import io.vertx.core.json.JsonObject; import io.vertx.core.json.JsonObject;
import org.apache.logging.log4j.Level;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
@ -251,6 +250,7 @@ public class EvmToolCommand implements Runnable {
@Override @Override
public void run() { public void run() {
LogConfigurator.setLevel("", "OFF");
try { try {
final EvmToolComponent component = final EvmToolComponent component =
DaggerEvmToolComponent.builder() DaggerEvmToolComponent.builder()
@ -285,14 +285,9 @@ public class EvmToolCommand implements Runnable {
.blockHeaderFunctions(new MainnetBlockHeaderFunctions()) .blockHeaderFunctions(new MainnetBlockHeaderFunctions())
.buildBlockHeader(); .buildBlockHeader();
Log4j2ConfiguratorUtil.setAllLevels("", repeat == 0 ? Level.INFO : Level.OFF);
int remainingIters = this.repeat; int remainingIters = this.repeat;
Log4j2ConfiguratorUtil.setLevel(
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", Level.OFF);
final ProtocolSpec protocolSpec = final ProtocolSpec protocolSpec =
component.getProtocolSpec().apply(BlockHeaderBuilder.createDefault().buildBlockHeader()); component.getProtocolSpec().apply(BlockHeaderBuilder.createDefault().buildBlockHeader());
Log4j2ConfiguratorUtil.setLevel(
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", null);
final Transaction tx = final Transaction tx =
new Transaction( new Transaction(
0, 0,

@ -44,7 +44,7 @@ import org.hyperledger.besu.evm.tracing.StandardJsonTracer;
import org.hyperledger.besu.evm.worldstate.WorldState; import org.hyperledger.besu.evm.worldstate.WorldState;
import org.hyperledger.besu.evm.worldstate.WorldUpdater; import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import org.hyperledger.besu.evmtool.exception.UnsupportedForkException; import org.hyperledger.besu.evmtool.exception.UnsupportedForkException;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.io.BufferedReader; import java.io.BufferedReader;
import java.io.File; import java.io.File;
@ -62,7 +62,6 @@ import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper; import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import org.apache.logging.log4j.Level;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
@ -107,6 +106,7 @@ public class StateTestSubCommand implements Runnable {
@Override @Override
public void run() { public void run() {
LogConfigurator.setLevel("", "OFF");
final ObjectMapper stateTestMapper = new ObjectMapper(); final ObjectMapper stateTestMapper = new ObjectMapper();
stateTestMapper.disable(Feature.AUTO_CLOSE_SOURCE); stateTestMapper.disable(Feature.AUTO_CLOSE_SOURCE);
final JavaType javaType = final JavaType javaType =
@ -162,12 +162,7 @@ public class StateTestSubCommand implements Runnable {
} }
private void traceTestSpecs(final String test, final List<GeneralStateTestCaseEipSpec> specs) { private void traceTestSpecs(final String test, final List<GeneralStateTestCaseEipSpec> specs) {
Log4j2ConfiguratorUtil.setLevel( final var referenceTestProtocolSchedules = ReferenceTestProtocolSchedules.create();
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", Level.OFF);
final ReferenceTestProtocolSchedules referenceTestProtocolSchedules =
ReferenceTestProtocolSchedules.create();
Log4j2ConfiguratorUtil.setLevel(
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", null);
final OperationTracer tracer = // You should have picked Mercy. final OperationTracer tracer = // You should have picked Mercy.
parentCommand.showJsonResults parentCommand.showJsonResults

@ -54,7 +54,7 @@ import org.hyperledger.besu.evm.tracing.StandardJsonTracer;
import org.hyperledger.besu.evm.worldstate.WorldUpdater; import org.hyperledger.besu.evm.worldstate.WorldUpdater;
import org.hyperledger.besu.evmtool.exception.UnsupportedForkException; import org.hyperledger.besu.evmtool.exception.UnsupportedForkException;
import org.hyperledger.besu.plugin.data.TransactionType; import org.hyperledger.besu.plugin.data.TransactionType;
import org.hyperledger.besu.util.Log4j2ConfiguratorUtil; import org.hyperledger.besu.util.LogConfigurator;
import java.io.FileOutputStream; import java.io.FileOutputStream;
import java.io.FileReader; import java.io.FileReader;
@ -83,7 +83,6 @@ import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode; import com.fasterxml.jackson.databind.node.ObjectNode;
import com.fasterxml.jackson.databind.node.TextNode; import com.fasterxml.jackson.databind.node.TextNode;
import com.google.common.base.Stopwatch; import com.google.common.base.Stopwatch;
import org.apache.logging.log4j.Level;
import org.apache.tuweni.bytes.Bytes; import org.apache.tuweni.bytes.Bytes;
import org.apache.tuweni.bytes.Bytes32; import org.apache.tuweni.bytes.Bytes32;
import org.apache.tuweni.units.bigints.UInt256; import org.apache.tuweni.units.bigints.UInt256;
@ -187,6 +186,7 @@ public class T8nSubCommand implements Runnable {
@Override @Override
public void run() { public void run() {
LogConfigurator.setLevel("", "OFF");
final ObjectMapper objectMapper = new ObjectMapper(); final ObjectMapper objectMapper = new ObjectMapper();
objectMapper.setDefaultPrettyPrinter( objectMapper.setDefaultPrettyPrinter(
(new DefaultPrettyPrinter()) (new DefaultPrettyPrinter())
@ -245,13 +245,9 @@ public class T8nSubCommand implements Runnable {
return; return;
} }
Log4j2ConfiguratorUtil.setLevel(
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", Level.OFF);
final ReferenceTestProtocolSchedules referenceTestProtocolSchedules = final ReferenceTestProtocolSchedules referenceTestProtocolSchedules =
ReferenceTestProtocolSchedules.create( ReferenceTestProtocolSchedules.create(
new StubGenesisConfigOptions().chainId(BigInteger.valueOf(chainId))); new StubGenesisConfigOptions().chainId(BigInteger.valueOf(chainId)));
Log4j2ConfiguratorUtil.setLevel(
"org.hyperledger.besu.ethereum.mainnet.AbstractProtocolScheduleBuilder", null);
final MutableWorldState worldState = new DefaultMutableWorldState(initialWorldState); final MutableWorldState worldState = new DefaultMutableWorldState(initialWorldState);

@ -5355,6 +5355,22 @@
<sha256 value="8b4e86c53d2783608f1aea213d906c5bac5c0433e00b19239bb16764b9fa3736" origin="Generated by Gradle"/> <sha256 value="8b4e86c53d2783608f1aea213d906c5bac5c0433e00b19239bb16764b9fa3736" origin="Generated by Gradle"/>
</artifact> </artifact>
</component> </component>
<component group="org.slf4j" name="slf4j-nop" version="1.7.36">
<artifact name="slf4j-nop-1.7.36.jar">
<sha256 value="c214958b07816cb4412b30c7bdbd4308ffdc6ba2a83767b8f3a9229cbd9274d6" origin="Generated by Gradle"/>
</artifact>
<artifact name="slf4j-nop-1.7.36.pom">
<sha256 value="20a0f7c060020d75fef4470ae6948661d418ebd5ea4549c68abedf20ee86cb65" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="org.slf4j" name="slf4j-nop" version="2.0.6">
<artifact name="slf4j-nop-2.0.6.jar">
<sha256 value="7966dcd73078250f38595223b1e807cd7566188a56236def031e265426056fc8" origin="Generated by Gradle"/>
</artifact>
<artifact name="slf4j-nop-2.0.6.pom">
<sha256 value="cd38d631dd836a0820fc715b7c95629de95c89f6598a9b80188c71e120b02fe5" origin="Generated by Gradle"/>
</artifact>
</component>
<component group="org.slf4j" name="slf4j-parent" version="1.7.30"> <component group="org.slf4j" name="slf4j-parent" version="1.7.30">
<artifact name="slf4j-parent-1.7.30.pom"> <artifact name="slf4j-parent-1.7.30.pom">
<sha256 value="11647956e48a0c5bfb3ac33f6da7e83f341002b6857efd335a505b687be34b75" origin="Generated by Gradle"/> <sha256 value="11647956e48a0c5bfb3ac33f6da7e83f341002b6857efd335a505b687be34b75" origin="Generated by Gradle"/>

@ -193,6 +193,7 @@ dependencyManagement {
dependency 'org.rocksdb:rocksdbjni:7.7.3' dependency 'org.rocksdb:rocksdbjni:7.7.3'
dependency 'org.slf4j:slf4j-api:2.0.6' dependency 'org.slf4j:slf4j-api:2.0.6'
dependency 'org.slf4j:slf4j-nop:2.0.6'
dependency 'org.springframework.security:spring-security-crypto:5.7.2' dependency 'org.springframework.security:spring-security-crypto:5.7.2'

@ -14,6 +14,8 @@
*/ */
package org.hyperledger.besu.util; package org.hyperledger.besu.util;
import static java.util.Objects.requireNonNull;
import java.util.Map; import java.util.Map;
import java.util.Set; import java.util.Set;
@ -26,7 +28,7 @@ import org.apache.logging.slf4j.Log4jLoggerFactory;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
/** The Log4j2 configurator util. */ /** The Log4j2 configurator util. */
public class Log4j2ConfiguratorUtil { class Log4j2ConfiguratorUtil {
private Log4j2ConfiguratorUtil() {} private Log4j2ConfiguratorUtil() {}
@ -36,18 +38,20 @@ public class Log4j2ConfiguratorUtil {
* @param parentLogger the parent logger * @param parentLogger the parent logger
* @param level the level * @param level the level
*/ */
public static void setAllLevels(final String parentLogger, final Level level) { static void setAllLevels(final String parentLogger, final String level) {
// 1) get logger config // 1) get logger config
// 2) if exact match, use it, if not, create it. // 2) if exact match, use it, if not, create it.
// 3) set level on logger config // 3) set level on logger config
// 4) update child logger configs with level // 4) update child logger configs with level
// 5) update loggers // 5) update loggers
Level log4JLevel = Level.toLevel(level, null);
requireNonNull(log4JLevel);
final LoggerContext loggerContext = getLoggerContext(); final LoggerContext loggerContext = getLoggerContext();
final Configuration config = loggerContext.getConfiguration(); final Configuration config = loggerContext.getConfiguration();
boolean set = setLevel(parentLogger, level, config); boolean set = setLevel(parentLogger, log4JLevel, config);
for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) { for (final Map.Entry<String, LoggerConfig> entry : config.getLoggers().entrySet()) {
if (entry.getKey().startsWith(parentLogger)) { if (entry.getKey().startsWith(parentLogger)) {
set |= setLevel(entry.getValue(), level); set |= setLevel(entry.getValue(), log4JLevel);
} }
} }
if (set) { if (set) {
@ -60,8 +64,8 @@ public class Log4j2ConfiguratorUtil {
* *
* @param loggerName the logger name * @param loggerName the logger name
*/ */
public static void setLevelDebug(final String loggerName) { static void setLevelDebug(final String loggerName) {
setLevel(loggerName, Level.DEBUG); setLevel(loggerName, "DEBUG");
} }
/** /**
@ -70,11 +74,13 @@ public class Log4j2ConfiguratorUtil {
* @param loggerName the logger name * @param loggerName the logger name
* @param level the level * @param level the level
*/ */
public static void setLevel(final String loggerName, final Level level) { static void setLevel(final String loggerName, final String level) {
Level log4jLevel = Level.toLevel(level, null);
requireNonNull(log4jLevel);
final LoggerContext loggerContext = getLoggerContext(); final LoggerContext loggerContext = getLoggerContext();
if (Strings.isEmpty(loggerName)) { if (Strings.isEmpty(loggerName)) {
setRootLevel(loggerContext, level); setRootLevel(loggerContext, log4jLevel);
} else if (setLevel(loggerName, level, loggerContext.getConfiguration())) { } else if (setLevel(loggerName, log4jLevel, loggerContext.getConfiguration())) {
loggerContext.updateLoggers(); loggerContext.updateLoggers();
} }
} }
@ -111,7 +117,7 @@ public class Log4j2ConfiguratorUtil {
} }
/** Reconfigure. */ /** Reconfigure. */
public static void reconfigure() { static void reconfigure() {
getLoggerContext().reconfigure(); getLoggerContext().reconfigure();
} }
@ -122,7 +128,7 @@ public class Log4j2ConfiguratorUtil {
} }
/** Shutdown. */ /** Shutdown. */
public static void shutdown() { static void shutdown() {
getLoggerContext().terminate(); getLoggerContext().terminate();
} }
} }

@ -0,0 +1,54 @@
/*
* Copyright contributors to Hyperledger Besu.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on
* an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the
* specific language governing permissions and limitations under the License.
*
* SPDX-License-Identifier: Apache-2.0
*/
package org.hyperledger.besu.util;
import java.util.NoSuchElementException;
/** The library independent logger configurator util. */
@SuppressWarnings("CatchAndPrintStackTrace")
public interface LogConfigurator {
/**
* Sets level to specified logger.
*
* @param parentLogger the logger name
* @param level the level
*/
static void setLevel(final String parentLogger, final String level) {
try {
Log4j2ConfiguratorUtil.setAllLevels(parentLogger, level);
} catch (NoClassDefFoundError | ClassCastException | NoSuchElementException e) {
// This is expected when Log4j support is not in the classpath, so ignore
}
}
/** Reconfigure. */
static void reconfigure() {
try {
Log4j2ConfiguratorUtil.reconfigure();
} catch (NoClassDefFoundError | ClassCastException | NoSuchElementException e) {
// This is expected when Log4j support is not in the classpath, so ignore
}
}
/** Shutdown. */
static void shutdown() {
try {
Log4j2ConfiguratorUtil.shutdown();
} catch (NoClassDefFoundError | ClassCastException | NoSuchElementException e) {
// This is expected when Log4j support is not in the classpath, so ignore
}
}
}
Loading…
Cancel
Save