From 3b23f5d06e2e045ed63690133d5272ff29fbce61 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 06:54:41 +0100 Subject: [PATCH 01/28] qa engine, audio, fluent logger. --- .../engine/audio/openAL/OpenALManager.java | 19 ++++++++++--------- .../audio/openAL/staticSound/OpenALSound.java | 2 +- .../streamingSound/OpenALStreamingSound.java | 2 +- 3 files changed, 12 insertions(+), 11 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java index 37fae3f642b..4396de68e60 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java @@ -64,15 +64,16 @@ public OpenALManager(AudioConfig config) throws OpenALException { ALCCapabilities alcCapabilities = ALC.createCapabilities(device); AL.createCapabilities(alcCapabilities); - logger.info("OpenAL {} initialized!", AL10.alGetString(AL10.AL_VERSION)); + logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_VERSION)).log("OpenAL {} initialized!"); - logger.info("Using OpenAL: {} by {}", AL10.alGetString(AL10.AL_RENDERER), AL10.alGetString(AL10.AL_VENDOR)); - logger.info("Using device: {}", ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER)); - logger.info("Available AL extensions: {}", AL10.alGetString(AL10.AL_EXTENSIONS)); - logger.info("Available ALC extensions: {}", ALC10.alcGetString(device, ALC10.ALC_EXTENSIONS)); - logger.info("Max mono sources: {}", ALC10.alcGetInteger(device, ALC11.ALC_MONO_SOURCES)); - logger.info("Max stereo sources: {}", ALC10.alcGetInteger(device, ALC11.ALC_STEREO_SOURCES)); - logger.info("Mixer frequency: {}", ALC10.alcGetInteger(device, ALC10.ALC_FREQUENCY)); + logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_RENDERER)).addArgument(() -> AL10.alGetString(AL10.AL_VENDOR)). + log("Using OpenAL: {} by {}"); + logger.atInfo().addArgument(() -> ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER)).log("Using device: {}"); + logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_EXTENSIONS)).log("Available AL extensions: {}"); + logger.atInfo().addArgument(() -> ALC10.alcGetString(device, ALC10.ALC_EXTENSIONS)).log("Available ALC extensions: {}"); + logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC11.ALC_MONO_SOURCES)).log("Max mono sources: {}"); + logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC11.ALC_STEREO_SOURCES)).log("Max stereo sources: {}"); + logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC10.ALC_FREQUENCY)).log("Mixer frequency: {}"); AL10.alDistanceModel(AL10.AL_INVERSE_DISTANCE_CLAMPED); @@ -260,7 +261,7 @@ private void notifyEndListeners(boolean interrupted) { try { entry.getValue().onAudioEnd(interrupted); } catch (Exception e) { - logger.error("onAudioEnd() notification failed for {}", entry.getValue(), e); + logger.atError().addArgument(() -> entry.getValue()).addArgument(e).log("onAudioEnd() notification failed for {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java b/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java index 95e4164e0ee..742cd18bef8 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java @@ -104,7 +104,7 @@ protected void doReload(StaticSoundData newData) { length = (float) size / channels / (bits / 8) / frequency; }); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java b/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java index af4bf3c8c12..da21a199386 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java @@ -123,7 +123,7 @@ protected void doReload(StreamingSoundData data) { try { GameThread.synch(this::initializeBuffers); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } From e9c4f14e098b74f5382072512e4a7c7d0f511f89 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 07:33:34 +0100 Subject: [PATCH 02/28] qa engine, config, fluent logger. --- .../terasology/engine/config/RenderingDebugConfig.java | 3 ++- .../engine/config/flexible/AutoConfigManager.java | 4 ++-- .../engine/config/flexible/AutoConfigTypeHandler.java | 10 +++++----- .../config/flexible/constraints/LocaleConstraint.java | 10 +++++----- .../flexible/constraints/NumberRangeConstraint.java | 9 +++++++-- .../config/flexible/constraints/StringConstraint.java | 8 +++++--- .../engine/config/flexible/ui/AutoConfigScreen.java | 2 +- .../config/flexible/ui/AutoConfigWidgetFactory.java | 2 +- 8 files changed, 28 insertions(+), 20 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java b/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java index ec86b76a588..b7050f3248c 100644 --- a/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java +++ b/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java @@ -108,6 +108,7 @@ public void setRenderSkeletons(boolean renderSkeletons) { @Override public void propertyChange(PropertyChangeEvent evt) { - logger.debug("Set {} property to {}.", evt.getPropertyName().toUpperCase(), evt.getNewValue()); + logger.atDebug().addArgument(() -> evt.getPropertyName().toUpperCase()).addArgument(evt.getNewValue()). + log("Set {} property to {}."); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java index c8c16e723ab..98102c81ebb 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java @@ -85,7 +85,7 @@ private void loadSettingsFromDisk(Class configClass, T T loadedConfig = (T) serializer.deserialize(TypeInfo.of(configClass), inputStream).get(); mergeConfig(configClass, loadedConfig, config); } catch (Exception e) { - logger.error("Error while loading config {} from disk", config.getId(), e); + logger.atError().addArgument(() -> config.getId()).addArgument(e).log("Error while loading config {} from disk"); } } @@ -116,7 +116,7 @@ private void saveConfigToDisk(AutoConfig config) { StandardOpenOption.CREATE)) { serializer.serialize(config, TypeInfo.of((Class) config.getClass()), output); } catch (IOException e) { - logger.error("Error while saving config {} to disk", config.getId(), e); + logger.atError().addArgument(() -> config.getId()).addArgument(e).log("Error while saving config {} to disk"); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java index 134081d2e84..5e9597556fc 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java @@ -43,7 +43,7 @@ protected PersistedData serializeNonNull(AutoConfig value, PersistedDataSerializ if (typeHandler.isPresent()) { fields.put(field.getName(), typeHandler.get().serialize(setting.get(), serializer)); } else { - logger.error("Cannot serialize type [{}]", setting.getValueType()); + logger.atError().addArgument(() -> setting.getValueType()).log("Cannot serialize type [{}]"); } } } catch (IllegalAccessException e) { @@ -65,7 +65,7 @@ public Optional deserialize(PersistedData data) { for (Map.Entry entry : data.getAsValueMap().entrySet()) { Field settingField = settingFields.get(entry.getKey()); if (settingField == null) { - logger.warn("Cannot to find setting field with name [{}]", entry.getKey()); + logger.atWarn().addArgument(() -> entry.getKey()).log("Cannot to find setting field with name [{}]"); continue; } try { @@ -77,11 +77,11 @@ public Optional deserialize(PersistedData data) { if (value.isPresent()) { setting.set(value.get()); } else { - logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(), - setting.getValueType()); + logger.atError().addArgument(() -> entry.getValue()).addArgument(setting.getValueType()). + log("Cannot deserialize value [{}] to type [{}]"); } } else { - logger.error("Cannot deserialize type [{}]", setting.getValueType()); + logger.atError().addArgument(() -> setting.getValueType()).log("Cannot deserialize type [{}]"); } } catch (IllegalAccessException e) { // ignore, AutoConfig.getSettingsFieldsIn return public fields. diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java index e5b7c7273ce..7efc4891ef9 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java @@ -32,11 +32,11 @@ public boolean isSatisfiedBy(Locale value) { @Override public void warnUnsatisfiedBy(Locale value) { - logger.warn("Locale {} should be one of {}", - value, - locales.stream() + logger.atWarn(). + addArgument(value). + addArgument(() -> locales.stream() .map(Locale::getLanguage) - .collect(Collectors.joining(",", "[", "]")) - ); + .collect(Collectors.joining(",", "[", "]"))). + log("Locale {} should be one of {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java index 22f4d83830a..318e8916bbc 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java @@ -97,7 +97,12 @@ public boolean isSatisfiedBy(T value) { */ @Override public void warnUnsatisfiedBy(T value) { - LOGGER.warn("Value {} is not in the range {}{}, {}{}", value, minInclusive ? "[" : "(", - min != null ? min : "UNBOUNDED", max != null ? max : "UNBOUNDED", maxInclusive ? "]" : ")"); + LOGGER.atWarn(). + addArgument(value). + addArgument(minInclusive ? "[" : "("). + addArgument(min != null ? min : "UNBOUNDED"). + addArgument(max != null ? max : "UNBOUNDED"). + addArgument(maxInclusive ? "]" : ")"). + log("Value {} is not in the range {}{}, {}{}"); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java index 4646f86191a..e4ef91cd6f5 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java @@ -50,10 +50,12 @@ public boolean isSatisfiedBy(String value) { @Override public void warnUnsatisfiedBy(String value) { - logger.warn("String [{}] does not match the conditions: {}", value, - predicates.stream() + logger.atWarn(). + addArgument(value). + addArgument(() -> predicates.stream() .filter(p -> !p.test(value)) .map(StringConstraint::getDescription) - .collect(Collectors.joining(",", "[", "]"))); + .collect(Collectors.joining(",", "[", "]"))). + log("String [{}] does not match the conditions: {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java index ea89a5fdb6c..c9800ec11f1 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java @@ -46,7 +46,7 @@ public void initialise() { if (widget.isPresent()) { mainContainer.addWidget(widget.get()); } else { - logger.warn("Cannot create widget for config: {}", config.getId()); + logger.atWarn().addArgument(() -> config.getId()).log("Cannot create widget for config: {}"); } } WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation()); diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java index c9fa7641b43..8b8d49e3896 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java @@ -79,7 +79,7 @@ public UIWidget buildWidgetFor(AutoConfig config) { Optional settingWidget = settingWidgetFactory.createWidgetFor(setting); if (!settingWidget.isPresent()) { - logger.error("Couldn't find a widget for the Setting [{}]", setting.getHumanReadableName()); + logger.atError().addArgument(() -> setting.getHumanReadableName()).log("Couldn't find a widget for the Setting [{}]"); continue; } From 496fcca05bff7bebfe7de0e434cc59d6962122d8 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 15:00:44 +0100 Subject: [PATCH 03/28] qa engine, core, fluent logger. --- .../engine/core/ComponentSystemManager.java | 4 +-- .../terasology/engine/core/PathManager.java | 4 +-- .../engine/core/TerasologyEngine.java | 30 +++++++++++-------- .../engine/core/modes/StateLoading.java | 2 +- .../modes/loadProcesses/InitialiseWorld.java | 6 ++-- .../core/modes/loadProcesses/JoinServer.java | 3 +- .../modes/loadProcesses/LoadEntities.java | 2 +- .../modes/loadProcesses/RegisterMods.java | 3 +- .../engine/core/module/ModuleInstaller.java | 4 +-- .../core/module/ModuleListDownloader.java | 4 +-- .../engine/core/module/ModuleManager.java | 5 ++-- .../common/ConfigurationSubsystem.java | 2 +- .../core/subsystem/config/BindsSubsystem.java | 6 ++-- .../subsystem/lwjgl/GLFWErrorCallback.java | 3 +- 14 files changed, 44 insertions(+), 34 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java index 025ca2a2dc3..973eb0bae6f 100644 --- a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java +++ b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java @@ -68,7 +68,7 @@ public void loadSystems(ModuleEnvironment environment, NetworkMode netMode) { ListMultimap> systemsByModule = ArrayListMultimap.create(); for (Class type : environment.getTypesAnnotatedWith(RegisterSystem.class)) { if (!ComponentSystem.class.isAssignableFrom(type)) { - logger.error("Cannot load {}, must be a subclass of ComponentSystem", type.getSimpleName()); + logger.atError().addArgument(type.getSimpleName()).log("Cannot load {}, must be a subclass of ComponentSystem"); continue; } Name moduleId = environment.getModuleProviding(type); @@ -177,7 +177,7 @@ public void register(ComponentSystem object) { context.get(EntityManager.class).getEventSystem().registerEventHandler(object); if (initialised) { - logger.warn("System {} registered post-init.", object.getClass().getName()); + logger.atWarn().addArgument(object.getClass().getName()).log("System {} registered post-init."); initialiseSystem(object); } } diff --git a/engine/src/main/java/org/terasology/engine/core/PathManager.java b/engine/src/main/java/org/terasology/engine/core/PathManager.java index 1c233d09b71..e13104d33ef 100644 --- a/engine/src/main/java/org/terasology/engine/core/PathManager.java +++ b/engine/src/main/java/org/terasology/engine/core/PathManager.java @@ -78,7 +78,7 @@ private static Path findInstallPath() { URI urlToSource = PathManager.class.getProtectionDomain().getCodeSource().getLocation().toURI(); Path codeLocation = Paths.get(urlToSource); installationSearchPaths.add(codeLocation); - LOGGER.info("PathManager: Initial code location is " + codeLocation.toAbsolutePath()); + LOGGER.atInfo().addArgument(codeLocation.toAbsolutePath()).log("PathManager: Initial code location is {}"); } catch (URISyntaxException e) { LOGGER.error("PathManager: Failed to convert code location to path.", e); } @@ -90,7 +90,7 @@ private static Path findInstallPath() { // Use the current directory as a fallback. Path currentDirectory = Paths.get("").toAbsolutePath(); installationSearchPaths.add(currentDirectory); - LOGGER.info("PathManager: Working directory is " + currentDirectory); + LOGGER.atInfo().addArgument(currentDirectory).log("PathManager: Working directory is {}"); for (Path startPath : installationSearchPaths) { Path installationPath = findNativesHome(startPath, 5); diff --git a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java index 0c81dce849e..404a6f02862 100644 --- a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java +++ b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java @@ -253,7 +253,7 @@ public void initialize() { } double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS); - logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds)); + logger.atInfo().addArgument(() -> String.format("%.2f", seconds)).log("Initialization completed in {}sec."); } private void verifyInitialisation() { @@ -266,16 +266,20 @@ private void verifyInitialisation() { * Logs software, environment and hardware information. */ private void logEnvironmentInfo() { - logger.info("{}", TerasologyVersion.getInstance()); - logger.info("Home path: {}", PathManager.getInstance().getHomePath()); - logger.info("Install path: {}", PathManager.getInstance().getInstallPath()); - logger.info("Java: {} in {}", System.getProperty("java.version"), System.getProperty("java.home")); - logger.info("Java VM: {}, version: {}", System.getProperty("java.vm.name"), System.getProperty("java.vm" + - ".version")); - logger.info("OS: {}, arch: {}, version: {}", System.getProperty("os.name"), System.getProperty("os.arch"), - System.getProperty("os.version")); - logger.info("Max. Memory: {} MiB", Runtime.getRuntime().maxMemory() / ONE_MEBIBYTE); - logger.info("Processors: {}", Runtime.getRuntime().availableProcessors()); + logger.atInfo().addArgument(() -> TerasologyVersion.getInstance()).log("{}"); + logger.atInfo().addArgument(() -> PathManager.getInstance().getHomePath()).log("Home path: {}"); + logger.atInfo().addArgument(() -> PathManager.getInstance().getInstallPath()).log("Install path: {}"); + logger.atInfo().addArgument(() -> System.getProperty("java.version")).addArgument(System.getProperty("java.home")). + log("Java: {} in {}"); + logger.atInfo().addArgument(() -> System.getProperty("java.vm.name")).addArgument(() -> System.getProperty("java.vm" + ".version")). + log("Java VM: {}, version: {}"); + logger.atInfo(). + addArgument(() -> System.getProperty("os.name")). + addArgument(() -> System.getProperty("os.arch")). + addArgument(() -> System.getProperty("os.version")). + log("OS: {}, arch: {}, version: {}"); + logger.atInfo().addArgument(() -> Runtime.getRuntime().maxMemory() / ONE_MEBIBYTE).log("Max. Memory: {} MiB"); + logger.atInfo().addArgument(() -> Runtime.getRuntime().availableProcessors()).log("Processors: {}"); if (NonNativeJVMDetector.JVM_ARCH_IS_NONNATIVE) { logger.warn("Running on a 32-bit JVM on a 64-bit system. This may limit performance."); } @@ -543,7 +547,7 @@ public void cleanup() { try { subsystem.preShutdown(); } catch (RuntimeException e) { - logger.error("Error preparing to shutdown {} subsystem", subsystem.getName(), e); + logger.atError().addArgument(() -> subsystem.getName()).addArgument(e).log("Error preparing to shutdown {} subsystem"); } } @@ -553,7 +557,7 @@ public void cleanup() { try { subsystem.shutdown(); } catch (RuntimeException e) { - logger.error("Error shutting down {} subsystem", subsystem.getName(), e); + logger.atError().addArgument(() -> subsystem.getName()).addArgument(e).log("Error shutting down {} subsystem"); } } } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java b/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java index d26f9619fb2..b10ec51239a 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java @@ -234,7 +234,7 @@ private void popStep() { current = null; if (!loadProcesses.isEmpty()) { current = loadProcesses.remove(); - logger.debug("{}", current.getMessage()); + logger.atDebug().addArgument(() -> current.getMessage()).log("{}"); current.begin(); } } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java index 41f853bde28..fbd40d75a79 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java @@ -94,7 +94,7 @@ public boolean step() { worldInfo.setSeed(random.nextString(16)); } - logger.info("World seed: \"{}\"", worldInfo.getSeed()); + logger.atInfo().addArgument(() -> worldInfo.getSeed()).log("World seed: \"{}\""); // TODO: Separate WorldRenderer from world handling in general WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class); @@ -105,8 +105,8 @@ public boolean step() { worldGenerator.setWorldSeed(worldInfo.getSeed()); context.put(WorldGenerator.class, worldGenerator); } catch (UnresolvedWorldGeneratorException e) { - logger.error("Unable to load world generator {}. Available world generators: {}", - worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators()); + logger.atError().addArgument(() -> worldInfo.getWorldGenerator()).addArgument(() -> worldGeneratorManager.getWorldGenerators()). + log("Unable to load world generator {}. Available world generators: {}"); context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator.")); return true; // We need to return true, otherwise the loading state will just call us again immediately } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java index 77a1dc0de69..44032823f3d 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java @@ -104,7 +104,8 @@ public boolean step() { context.get(GameEngine.class).changeState(mainMenu); return false; } else { - logger.info("Activating module: {}:{}", moduleInfo.getName(), moduleInfo.getVersion()); + logger.atInfo().addArgument(() -> moduleInfo.getName()).addArgument(() -> moduleInfo.getVersion()). + log("Activating module: {}:{}"); gameManifest.addModule(module.getId(), module.getVersion()); moduleSet.add(module); } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java index 785100b4f24..6b51c95236d 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java @@ -34,7 +34,7 @@ public boolean step() { boolean entityCreated = false; for (EntityRef entity : em.getAllEntities()) { entityCreated = true; - logger.error("Entity created before load: {}", entity.toFullDescription()); + logger.atError().addArgument(() -> entity.toFullDescription()).log("Entity created before load: {}"); } if (entityCreated) { throw new IllegalStateException("Entity creation detected during component system initialisation, game load aborting"); diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java index d8d42b639c3..e8bac12b0a0 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java @@ -68,7 +68,8 @@ public boolean step() { ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { - logger.info("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); + logger.atInfo().addArgument(() -> moduleInfo.getId()).addArgument(() -> moduleInfo.getVersion()). + log("Activating module: {}:{}"); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java index 3a258196e35..5dd1728367d 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java @@ -38,7 +38,7 @@ public class ModuleInstaller implements Callable> { @Override public List call() throws Exception { Map filesToDownload = getDownloadUrls(moduleList); - logger.info("Started downloading {} modules", filesToDownload.size()); + logger.atInfo().addArgument(() -> filesToDownload.size()).log("Started downloading {} modules"); MultiFileDownloader downloader = new MultiFileDownloader(filesToDownload, downloadProgressListener); List downloadedModulesPaths = downloader.call(); logger.info("Module download completed, loading the new modules..."); @@ -48,7 +48,7 @@ public List call() throws Exception { Module module = moduleManager.registerArchiveModule(filePath); newInstalledModules.add(module); } catch (IOException e) { - logger.warn("Could not load module {}", filePath.getFileName(), e); + logger.atWarn().addArgument(() -> filePath.getFileName()).addArgument(e).log("Could not load module {}"); } } logger.info("Finished loading the downloaded modules"); diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java index 7921b2e4b5e..88af4e8f6ef 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java @@ -59,13 +59,13 @@ public ModuleRegistry call() throws IOException { String json = gson.toJson(jObject); ModuleMetadata meta = metaReader.read(new StringReader(json)); - logger.debug("Read module {} - {}", meta.getId(), meta.getVersion()); + logger.atDebug().addArgument(() -> meta.getId()).addArgument(() -> meta.getVersion()).log("Read module {} - {}"); modules.add(new Module(meta, new EmptyFileSource(), Collections.emptyList(), new Reflections(), (c) -> false)); } int count = modules.size(); - logger.info("Retrieved {} {}", count, (count == 1) ? "entry" : "entries"); + logger.atInfo().addArgument(() -> count).addArgument(() -> (count == 1) ? "entry" : "entries").log("Retrieved {} {}"); } return modules; } diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java index 5538bb2057c..027fcda0d2b 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java @@ -173,9 +173,10 @@ private void loadModulesFromClassPath() { continue; } if (registry.add(module)) { - logger.info("Loaded {} from {}", module.getId(), path); + logger.atInfo().addArgument(() -> module.getId()).addArgument(() -> path).log("Loaded {} from {}"); } else { - logger.info("Module {} from {} was a duplicate; not registering this copy.", module.getId(), path); + logger.atInfo().addArgument(() -> module.getId()).addArgument(() -> path). + log("Module {} from {} was a duplicate; not registering this copy."); } } } diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java b/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java index 292571a5a46..d211194c8d0 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java @@ -66,7 +66,7 @@ public void preInitialise(Context rootContext) { checkServerIdentity(); // TODO: Move to display subsystem - logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); + logger.atInfo().addArgument(() -> config.renderConfigAsJson(config.getRendering())).log("Video Settings: {}"); rootContext.put(Config.class, config); //add facades diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java index 96125c3f173..97c059f60e8 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java @@ -251,11 +251,13 @@ private void registerAxisBinds(ModuleEnvironment environment) { BindableButton positiveButton = getBindButton(new SimpleUri(info.positiveButton())); BindableButton negativeButton = getBindButton(new SimpleUri(info.negativeButton())); if (positiveButton == null) { - logger.warn("Failed to register axis \"{}\", missing positive button \"{}\"", id, info.positiveButton()); + logger.atWarn().addArgument(() -> id).addArgument(() -> info.positiveButton()). + log("Failed to register axis \"{}\", missing positive button \"{}\""); continue; } if (negativeButton == null) { - logger.warn("Failed to register axis \"{}\", missing negative button \"{}\"", id, info.negativeButton()); + logger.atWarn().addArgument(() -> id).addArgument(() -> info.negativeButton()). + log("Failed to register axis \"{}\", missing negative button \"{}\""); continue; } try { diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java b/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java index 58022aba1db..da939b37952 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java @@ -15,6 +15,7 @@ public class GLFWErrorCallback implements GLFWErrorCallbackI { @Override public void invoke(int error, long description) { - logger.error("Received error. Code: {}, Description: {}", error, MemoryUtil.memASCII(description)); + logger.atError().addArgument(() -> error).addArgument(() -> MemoryUtil.memASCII(description)). + log("Received error. Code: {}, Description: {}"); } } From 6611111420690f09aa6c6dbf8dcc6ab8f45c351c Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 15:16:54 +0100 Subject: [PATCH 04/28] qa engine, entitySystem, fluent logger. --- .../entity/internal/PojoEntityManager.java | 6 ++++-- .../entitySystem/event/internal/EventSystemImpl.java | 12 ++++++------ .../entitySystem/metadata/ComponentLibrary.java | 6 ++++-- .../engine/entitySystem/metadata/EventLibrary.java | 3 ++- .../engine/entitySystem/metadata/EventMetadata.java | 3 ++- 5 files changed, 18 insertions(+), 12 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java index b5715fba7cd..10573b47d91 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java @@ -526,7 +526,8 @@ public T addComponent(long entityId, T component) { if (!oldComponent.isPresent()) { notifyComponentAdded(getEntity(entityId), component.getClass()); } else { - logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId); + logger.atError().addArgument(() -> component.getClass()).addArgument(() -> entityId). + log("Adding a component ({}) over an existing component for entity {}"); notifyComponentChanged(getEntity(entityId), component.getClass()); } @@ -580,7 +581,8 @@ public void saveComponent(long entityId, Component component) { .map(pool -> pool.getComponentStore().put(entityId, component)); if (!oldComponent.isPresent()) { - logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId); + logger.atError().addArgument(() -> component.getClass()).addArgument(() -> entityId). + log("Saving a component ({}) that doesn't belong to this entity {}"); } if (eventSystem != null) { EntityRef entityRef = getEntity(entityId); diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java index 5c95213c4d5..72df42bc85b 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java @@ -83,7 +83,7 @@ public void process() { @Override public void registerEvent(ResourceUrn uri, Class eventType) { eventIdMap.put(uri, eventType); - logger.debug("Registering event {}", eventType.getSimpleName()); + logger.atDebug().addArgument(() -> eventType.getSimpleName()).log("Registering event {}"); for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) { if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) { childEvents.put(parent, eventType); @@ -95,11 +95,11 @@ public void registerEvent(ResourceUrn uri, Class eventType) { public void registerEventHandler(ComponentSystem handler) { Class handlerClass = handler.getClass(); if (!Modifier.isPublic(handlerClass.getModifiers())) { - logger.error("Cannot register handler {}, must be public", handlerClass.getName()); + logger.atError().addArgument(() -> handlerClass.getName()).log("Cannot register handler {}, must be public"); return; } - logger.debug("Registering event handler {}", handlerClass.getName()); + logger.atDebug().addArgument(() -> handlerClass.getName()).log("Registering event handler {}"); for (Method method : handlerClass.getMethods()) { ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class); if (receiveEventAnnotation != null) { @@ -129,7 +129,7 @@ public void registerEventHandler(ComponentSystem handler) { logger.debug("Found method: {}", method); if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) { - logger.error("Invalid event handler method: {}", method.getName()); + logger.atError().addArgument(() -> method.getName()).log("Invalid event handler method: {}"); return; } @@ -137,8 +137,8 @@ public void registerEventHandler(ComponentSystem handler) { List> componentParams = Lists.newArrayList(); for (int i = 2; i < types.length; ++i) { if (!Component.class.isAssignableFrom(types[i])) { - logger.error("Invalid event handler method: {} - {} is not a component class", - method.getName(), types[i]); + logger.atError().addArgument(() -> method.getName()).addArgument(types[i]). + log("Invalid event handler method: {} - {} is not a component class"); return; } requiredComponents.add((Class) types[i]); diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java index 18995d9d801..96302d714ef 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java @@ -46,11 +46,13 @@ public ComponentLibrary createCopyUsingCopyStrategy(Class type, CopyStrat try { info = new ComponentMetadata<>(uri, type, factory, copyStrategies); } catch (NoSuchMethodException e) { - logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); + logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). + log("Unable to register class {}: Default Constructor Required"); return null; } catch (NoClassDefFoundError e) { // log what class was not found so that diagnosis is easier - logger.error("Class not found, {}", type.getSimpleName(), e); + logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). + log("Class not found, {}"); throw e; } return info; diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java index 2b90088af09..4a6397c1896 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java @@ -30,7 +30,8 @@ public EventLibrary(ModuleEnvironment environment, ReflectFactory reflectFactory try { return new EventMetadata<>(type, copyStrategies, factory, uri); } catch (NoSuchMethodException e) { - logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); + logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). + log("Unable to register class {}: Default Constructor Required"); return null; } } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java index 2a73a84f75d..14f32cf21eb 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java @@ -38,7 +38,8 @@ public EventMetadata(Class simpleClass, CopyStrategyLibrary copyStrategies, R skipInstigator = simpleClass.getAnnotation(BroadcastEvent.class).skipInstigator(); } if (networkEventType != NetworkEventType.NONE && !isConstructable() && !Modifier.isAbstract(simpleClass.getModifiers())) { - logger.error("Event '{}' is a network event but lacks a default constructor - will not be replicated", this); + logger.atError().addArgument(() -> this). + log("Event '{}' is a network event but lacks a default constructor - will not be replicated"); } } From 23e58ccf36a83aee8de40254cc589f2bad7b0519 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 15:20:41 +0100 Subject: [PATCH 05/28] qa engine, game, fluent logger. --- .../main/java/org/terasology/engine/game/GameManifest.java | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/game/GameManifest.java b/engine/src/main/java/org/terasology/engine/game/GameManifest.java index c0681e58f54..7653da4b535 100644 --- a/engine/src/main/java/org/terasology/engine/game/GameManifest.java +++ b/engine/src/main/java/org/terasology/engine/game/GameManifest.java @@ -188,13 +188,14 @@ public void addModule(Name id, Version version) { public String mainWorldDisplayName(WorldGeneratorManager manager) { var world = getWorldInfo(TerasologyConstants.MAIN_WORLD); if (world == null) { - logger.warn("{} has no MAIN_WORLD", this); + logger.atWarn().addArgument(() -> this).log("{} has no MAIN_WORLD"); return "ERROR: No main world"; } SimpleUri generatorUri = world.getWorldGenerator(); var generator = manager.getWorldGeneratorInfo(generatorUri); if (generator == null) { - logger.warn("{}: {} has no generator for {}", this, manager, generatorUri); + logger.atWarn().addArgument(() -> this).addArgument(() -> manager).addArgument(() -> generatorUri). + log("{}: {} has no generator for {}"); return "ERROR: No generator found for " + generatorUri; } return generator.getDisplayName(); From c182e76ba5b7e8e1b59a9d6b090c8ed8d8172d7c Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 18:21:46 +0100 Subject: [PATCH 06/28] qa engine, identity, fluent logger. --- .../identity/storageServiceClient/StorageServiceWorker.java | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java b/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java index ea132b41212..e4199df0938 100644 --- a/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java +++ b/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java @@ -71,10 +71,10 @@ private synchronized void performAction(Action action, StorageServiceWorkerStatu throw new RuntimeException("StorageServiceWorker is not in the required status"); } status = StorageServiceWorkerStatus.WORKING; - logger.info("Performing action {}", action.getClass().getSimpleName()); + logger.atInfo().addArgument(() -> action.getClass().getSimpleName()).log("Performing action {}"); new Thread(() -> { action.perform(this); - logger.info("Completed action {}", action.getClass().getSimpleName()); + logger.atInfo().addArgument(() -> action.getClass().getSimpleName()).log("Completed action {}"); }).start(); } From cf8482328d9663ec8f5cc00cec984f1dc081275e Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 18:22:09 +0100 Subject: [PATCH 07/28] qa engine, input, fluent logger. --- .../engine/input/lwjgl/LwjglControllerDevice.java | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java index e63aeff998e..1a62d114d25 100644 --- a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java +++ b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java @@ -107,20 +107,20 @@ private void onJoystickConnectDisconnect(int jid, int event) { private void handleJoystickConnect(int jid) { if (GLFW.glfwJoystickIsGamepad(jid)) { gamepadIds.add(jid); - logger.info("JoyStick connected: {}", GLFW.glfwGetJoystickName(jid)); + logger.atInfo().addArgument(() -> GLFW.glfwGetJoystickName(jid)).log("JoyStick connected: {}"); } else { joystickIds.add(jid); - logger.info("Gamepad connected: {}", GLFW.glfwGetGamepadName(jid)); + logger.atInfo().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Gamepad connected: {}"); } } private void handleJoystickDisconnect(int jid) { if (GLFW.glfwJoystickIsGamepad(jid)) { gamepadIds.remove(jid); - logger.info("JoyStick disconnected: {}", GLFW.glfwGetJoystickName(jid)); + logger.atInfo().addArgument(() -> GLFW.glfwGetJoystickName(jid)).log("JoyStick disconnected: {}"); } else { joystickIds.remove(jid); - logger.info("Gamepad disconnected: {}", GLFW.glfwGetGamepadName(jid)); + logger.atInfo().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Gamepad disconnected: {}"); } } @@ -186,7 +186,7 @@ public Queue getInputQueue() { buttonIndex++; } } else { - logger.error("Cannot get states for {}", GLFW.glfwGetGamepadName(jid)); + logger.atError().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Cannot get states for {}"); } } From f0b2bab94d0483e1b0a4e308f207b0450dbe7b4a Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 19:26:49 +0100 Subject: [PATCH 08/28] qa engine, logic, fluent logger. --- .../actions/conditions/ConditionAction.java | 11 ++-- .../logic/behavior/core/ActionNode.java | 6 ++- .../logic/behavior/core/DecoratorNode.java | 6 ++- .../characters/CharacterSoundSystem.java | 2 +- .../logic/characters/CharacterSystem.java | 52 ++++++++++--------- .../ClientCharacterPredictionSystem.java | 5 +- .../engine/logic/console/ConsoleImpl.java | 16 +++--- .../console/commandSystem/MethodCommand.java | 19 ++++--- .../console/commands/ServerCommands.java | 4 +- .../logic/debug/ChunkEventErrorLogger.java | 4 +- .../inventory/ItemPickupAuthoritySystem.java | 2 +- .../engine/logic/players/PlayerSystem.java | 2 +- 12 files changed, 73 insertions(+), 56 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java index 06df94007fc..9f9e13d44b8 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java @@ -98,7 +98,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi secondValue = ""; break; default: - logger.error("Unsupported guard value type: {}", tokens[0]); + logger.atError().addArgument(() -> tokens[0]).log("Unsupported guard value type: {}"); secondValue = ""; } @@ -115,7 +115,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = (Boolean) fieldValue != Boolean.parseBoolean(secondValue); break; default: - logger.error("Unsupported operation for boolean values: {}", tokens[2]); + logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for boolean values: {}"); } @@ -142,7 +142,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = ((Number) fieldValue).doubleValue() < Double.parseDouble(secondValue); break; default: - logger.error("Unsupported operation for numeric values: {}", tokens[2]); + logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for numeric values: {}"); } @@ -157,7 +157,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = !fieldValue.equals(secondValue); break; default: - logger.error("Unsupported operation for strings: {}", tokens[2]); + logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for strings: {}"); } } else { @@ -190,7 +190,8 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi break; default: - logger.error("Unknown field type or operation: {} {}", fieldValue.getClass(), tokens[2]); + logger.atError().addArgument(() -> fieldValue.getClass()).addArgument(() -> tokens[2]). + log("Unknown field type or operation: {} {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java index 7fb687008a1..65df48d3c42 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java @@ -56,7 +56,8 @@ public void construct(Actor actor) { try { action.construct(actor); } catch (Exception e) { - logger.debug("Exception while running construct() of action {} from entity {}: ", action, actor.getEntity(), e); + logger.atDebug().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e). + log("Exception while running construct() of action {} from entity {}: "); } } } @@ -67,7 +68,8 @@ public BehaviorState execute(Actor actor) { try { return action.modify(actor, BehaviorState.UNDEFINED); } catch (Exception e) { - logger.debug("Exception while running action {} from entity {}: ", action, actor.getEntity(), e); + logger.atDebug().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e). + log("Exception while running action {} from entity {}: "); // TODO maybe returning UNDEFINED would be more fitting? return BehaviorState.FAILURE; } diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java index 9ad31ff6703..29cc0c133e5 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java @@ -48,7 +48,8 @@ public void construct(Actor actor) { try { action.construct(actor); } catch (Exception e) { - logger.info("Exception while running construct() of action {} from entity {}:", action, actor.getEntity()); + logger.atInfo().addArgument(() -> action).addArgument(() -> actor.getEntity()). + log("Exception while running construct() of action {} from entity {}:"); } } } @@ -80,7 +81,8 @@ public BehaviorState execute(Actor actor) { try { modifiedState = action.modify(actor, lastState); } catch (Exception e) { - logger.info("Exception while running action {} from entity {}: {}", action, actor.getEntity(), e.getStackTrace()); + logger.atInfo().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e.getStackTrace()). + log("Exception while running action {} from entity {}: {}"); // TODO maybe returning UNDEFINED would be more canonical? return BehaviorState.FAILURE; } diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java index 7a370b141a7..7429cd75040 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java @@ -60,7 +60,7 @@ public void onFootstep(FootstepEvent event, EntityRef entity, LocationComponent Block block = worldProvider.getBlock(blockPos); if (block != null) { if (block.getSounds() == null) { - logger.error("Block '{}' has no sounds", block.getURI()); + logger.atError().addArgument(() -> block.getURI()).log("Block '{}' has no sounds"); } else if (!block.getSounds().getStepSounds().isEmpty()) { footstepSounds = block.getSounds().getStepSounds(); } diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java index ec3dd3ca18d..973043da893 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java @@ -155,7 +155,7 @@ public String getDamageTypeName(Prefab damageType) { return damageType.getComponent(DisplayNameComponent.class).name; } else { String damageTypeName = damageType.getName(); - logger.info("{} is missing a readable DisplayName", damageTypeName); + logger.atInfo().addArgument(damageTypeName).log("{} is missing a readable DisplayName"); //damageType.getName() returns a ResourceUrn String such as "engine:directDamage" //The following calls change the damage type to be more readable //For instance, "engine:directDamage" becomes "Direct Damage" @@ -308,42 +308,46 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques LocationComponent location = camera.getComponent(LocationComponent.class); Vector3f direction = location.getWorldDirection(new Vector3f()); if (!(event.getDirection().equals(direction, 0.0001f))) { - logger.error("Direction at client {} was different than direction at server {}", event.getDirection(), direction); + logger.atError().addArgument(() -> event.getDirection()).addArgument(direction). + log("Direction at client {} was different than direction at server {}"); } // Assume the exact same value in case there are rounding mistakes: direction = event.getDirection(); Vector3f originPos = location.getWorldPosition(new Vector3f()); if (!(event.getOrigin().equals(originPos, 0.0001f))) { - logger.info("Player {} seems to have cheated: It stated that it performed an action from {} but the predicted position is {}", - getPlayerNameFromCharacter(character), event.getOrigin(), originPos); + logger.atInfo(). + addArgument(() -> getPlayerNameFromCharacter(character)). + addArgument(() -> event.getOrigin()). + addArgument(() -> originPos). + log("Player {} seems to have cheated: It stated that it performed an action from {} but the predicted position is {}"); return false; } if (event.isOwnedEntityUsage()) { if (!event.getUsedOwnedEntity().exists()) { - logger.info("Denied activation attempt by {} since the used entity does not exist on the authority", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since the used entity does not exist on the authority"); return false; } if (!networkSystem.getOwnerEntity(event.getUsedOwnedEntity()).equals(networkSystem.getOwnerEntity(character))) { - logger.info("Denied activation attempt by {} since it does not own the entity at the authority", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since it does not own the entity at the authority"); return false; } } else { // check for cheats so that data can later be trusted: if (event.getUsedOwnedEntity().exists()) { - logger.info("Denied activation attempt by {} since it is not properly marked as owned entity usage", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since it is not properly marked as owned entity usage"); return false; } } if (event.isEventWithTarget()) { if (!event.getTarget().exists()) { - logger.info("Denied activation attempt by {} since the target does not exist on the authority", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since the target does not exist on the authority"); return false; // can happen if target existed on client } @@ -360,8 +364,8 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques HitResult result = physics.rayTrace(originPos, direction, interactionRange, Sets.newHashSet(character), DEFAULTPHYSICSFILTER); if (!result.isHit()) { - logger.info("Denied activation attempt by {} since at the authority there was nothing to activate at that place", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since at the authority there was nothing to activate at that place"); return false; } EntityRef hitEntity = result.getEntity(); @@ -371,31 +375,31 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques * server entity dump. When certain fields don't get replicated, then wrong entity might get hin in the * hit test. */ - logger.info("Denied activation attempt by {} since at the authority another entity would have been activated", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since at the authority another entity would have been activated"); return false; } if (!(event.getHitPosition().equals(result.getHitPoint(), 0.0001f))) { - logger.info("Denied activation attempt by {} since at the authority the object got hit at a differnt position", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since at the authority the object got hit at a differnt position"); return false; } } else { // In order to trust the data later we need to verify it even if it should be correct if no one cheats: if (event.getTarget().exists()) { - logger.info("Denied activation attempt by {} since the event was not properly labeled as having a target", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since the event was not properly labeled as having a target"); return false; } if (event.getHitPosition() != null) { - logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit position", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since the event was not properly labeled as having a hit position"); return false; } if (event.getHitNormal() != null) { - logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit delta", - getPlayerNameFromCharacter(character)); + logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). + log("Denied activation attempt by {} since the event was not properly labeled as having a hit delta"); return false; } } diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java index 62baef30dc1..678f050baf8 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java @@ -84,7 +84,8 @@ public void onDestroy(final BeforeDeactivateComponent event, final EntityRef ent @ReceiveEvent(components = {CharacterMovementComponent.class, LocationComponent.class, AliveCharacterComponent.class}) public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity) { if (entity.equals(localPlayer.getCharacterEntity())) { - logger.trace("Received new state, sequence number: {}, buffered input size {}", state.getSequenceNumber(), inputs.size()); + logger.atTrace().addArgument(() -> state.getSequenceNumber()).addArgument(() -> inputs.size()). + log("Received new state, sequence number: {}, buffered input size {}"); playerStates.remove(entity); authoritiveState = state; @@ -98,7 +99,7 @@ public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity newState = stepState(input, newState, entity); } } - logger.trace("Resultant input size {}", inputs.size()); + logger.atTrace().addArgument(() -> inputs.size()).log("Resultant input size {}"); characterMovementSystemUtility.setToState(entity, newState); // TODO: soft correct predicted state predictedState = newState; diff --git a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java index a587391a8e1..d613363f3fa 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java @@ -63,13 +63,17 @@ public void registerCommand(ConsoleCommand command) { Name commandName = command.getName(); if (commandRegistry.containsKey(commandName)) { - logger.warn("Command with name '{}' already registered by class '{}', skipping '{}'", - commandName, commandRegistry.get(commandName).getSource().getClass().getCanonicalName(), - command.getSource().getClass().getCanonicalName()); + logger.atWarn(). + addArgument(() -> commandName). + addArgument(() -> commandRegistry.get(commandName).getSource().getClass().getCanonicalName()). + addArgument(() -> command.getSource().getClass().getCanonicalName()). + log("Command with name '{}' already registered by class '{}', skipping '{}'"); } else { commandRegistry.put(commandName, command); - logger.debug("Command '{}' successfully registered for class '{}'.", commandName, - command.getSource().getClass().getCanonicalName()); + logger.atDebug(). + addArgument(() -> commandName). + addArgument(() -> command.getSource().getClass().getCanonicalName()). + log("Command '{}' successfully registered for class '{}'."); } } @@ -135,7 +139,7 @@ public void addMessage(String message, MessageType type, boolean newLine) { @Override public void addMessage(Message message) { String uncoloredText = FontUnderline.strip(FontColor.stripColor(message.getMessage())); - logger.info("[{}] {}", message.getType(), uncoloredText); + logger.atInfo().addArgument(() -> message.getType()).addArgument(() -> uncoloredText).log("[{}] {}"); messageHistory.add(message); for (ConsoleSubscriber subscriber : messageSubscribers) { subscriber.onNewConsoleMessage(message); diff --git a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java index 235a8f4f1a2..606b8a0b563 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java @@ -74,20 +74,23 @@ public static void registerAvailable(Object provider, Console console, Context c Set commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); for (Method method : commandMethods) { if (!hasSenderAnnotation(method)) { - logger.error("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a " + - "NullPointerException", method.getName(), provider.getClass().getSimpleName()); + logger.atError().addArgument(() -> method.getName()).addArgument(() -> provider.getClass().getSimpleName()). + log("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a NullPointerException"); } - logger.debug("Registering command method {} in class {}", method.getName(), - method.getDeclaringClass().getCanonicalName()); + logger.atDebug().addArgument(() -> method.getName()).addArgument(() -> method.getDeclaringClass().getCanonicalName()). + log("Registering command method {} in class {}"); try { SpecificAccessibleObject specificMethod = new SpecificAccessibleObject<>(method, provider); MethodCommand command = referringTo(specificMethod, context); console.registerCommand(command); - logger.debug("Registered command method {} in class {}", method.getName(), - method.getDeclaringClass().getCanonicalName()); + logger.atDebug().addArgument(() -> method.getName()).addArgument(() -> method.getDeclaringClass().getCanonicalName()). + log("Registered command method {} in class {}"); } catch (RuntimeException t) { - logger.error("Failed to load command method {} in class {}", method.getName(), - method.getDeclaringClass().getCanonicalName(), t); + logger.atError(). + addArgument(() -> method.getName()). + addArgument(() -> method.getDeclaringClass().getCanonicalName()). + addArgument(() -> t). + log("Failed to load command method {} in class {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java b/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java index 6eb41fae231..78617b27008 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java @@ -68,7 +68,7 @@ public String shutdownServer(@Sender EntityRef sender) { EntityRef clientInfo = sender.getComponent(ClientComponent.class).clientInfo; DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class); - logger.info("Shutdown triggered by {}", name.name); + logger.atInfo().addArgument(() -> name.name).log("Shutdown triggered by {}"); gameEngine.shutdown(); @@ -165,7 +165,7 @@ private String kick(EntityRef clientEntity) { EntityRef clientInfo = clientEntity.getComponent(ClientComponent.class).clientInfo; DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class); - logger.info("Kicking user {}", name.name); + logger.atInfo().addArgument(() -> name.name).log("Kicking user {}"); networkSystem.forceDisconnect(client); return "User kick triggered for '" + name.name + "'"; diff --git a/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java b/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java index 7345a4d25c8..a611ec1d200 100644 --- a/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java +++ b/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java @@ -25,14 +25,14 @@ public class ChunkEventErrorLogger extends BaseComponentSystem { @ReceiveEvent(components = WorldComponent.class) public void onNewChunk(OnChunkLoaded chunkAvailable, EntityRef worldEntity) { if (!loadedChunks.add(chunkAvailable.getChunkPos())) { - logger.error("Multiple loads of chunk {}", chunkAvailable.getChunkPos()); + logger.atError().addArgument(() -> chunkAvailable.getChunkPos()).log("Multiple loads of chunk {}"); } } @ReceiveEvent(components = WorldComponent.class) public void onRemoveChunk(BeforeChunkUnload chunkUnload, EntityRef worldEntity) { if (!loadedChunks.remove(chunkUnload.getChunkPos())) { - logger.error("Unload event for not loaded chunk {}", chunkUnload.getChunkPos()); + logger.atError().addArgument(() -> chunkUnload.getChunkPos()).log("Unload event for not loaded chunk {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java b/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java index a50324e917e..b61a26f07b3 100644 --- a/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java @@ -82,7 +82,7 @@ public void updateExtentsOnBlockItemBoxShape(OnAddedComponent event, EntityRef i BlockFamily blockFamily = blockItemComponent.blockFamily; if (blockFamily == null) { - LOGGER.warn("Prefab {} does not have a block family", itemEntity.getParentPrefab().getName()); + LOGGER.atWarn().addArgument(() -> itemEntity.getParentPrefab().getName()).log("Prefab {} does not have a block family"); return; } diff --git a/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java b/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java index c8f958c9340..627ce16a9bd 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java @@ -155,7 +155,7 @@ public void onConnect(ConnectedEvent connected, EntityRef entity) { private void restoreCharacter(EntityRef entity, EntityRef character) { Client clientListener = networkSystem.getOwner(entity); - LOGGER.info(clientListener.toString()); + LOGGER.atInfo().addArgument(() -> clientListener.toString()).log("{}"); updateRelevanceEntity(entity, clientListener.getViewDistance().getChunkDistance()); ClientComponent client = entity.getComponent(ClientComponent.class); From d5a0dba783274662f20a0131f46fb5cff9b9d1b2 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 19:54:17 +0100 Subject: [PATCH 09/28] qa engine, network, fluent logger. --- .../internal/ClientConnectionHandler.java | 11 +++++++--- .../engine/network/internal/NetClient.java | 8 +++++--- .../network/internal/NetworkSystemImpl.java | 19 ++++++++++-------- .../engine/network/internal/ServerImpl.java | 20 +++++++++++++------ 4 files changed, 38 insertions(+), 20 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java index 4c4713f3c25..8ea7d34a4a7 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java @@ -160,8 +160,12 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext, joinStatus.setCurrentActivity( "Downloading " + moduleDataHeader.getId() + ":" + moduleDataHeader.getVersion() + " (" + sizeString + "," + missingModules.size() + " modules remain)"); - logger.info("Downloading {}: {} ({}, {} modules remain)", moduleDataHeader.getId(), moduleDataHeader.getVersion(), - sizeString, missingModules.size()); + logger.atInfo(). + addArgument(() -> moduleDataHeader.getId()). + addArgument(() -> moduleDataHeader.getVersion()). + addArgument(() -> sizeString). + addArgument(() -> missingModules.size()). + log("Downloading {}: {} ({}, {} modules remain)"); receivingModule = moduleDataHeader; lengthReceived = 0; try { @@ -176,7 +180,8 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext, } } } else { - logger.error("Received unwanted module {}:{} from server", moduleDataHeader.getId(), moduleDataHeader.getVersion()); + logger.atError().addArgument(() -> moduleDataHeader.getId()).addArgument(() -> moduleDataHeader.getVersion()). + log("Received unwanted module {}:{} from server"); joinStatus.setErrorMessage("Module download error"); channelHandlerContext.channel().close(); } diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java index 7b9ab767e9e..94726b79382 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java @@ -363,7 +363,7 @@ public boolean isLocal() { } void send(NetData.NetMessage data) { - logger.trace("Sending packet with size {}", data.getSerializedSize()); + logger.atTrace().addArgument(() -> data.getSerializedSize()).log("Sending packet with size {}"); sentMessages.incrementAndGet(); sentBytes.addAndGet(data.getSerializedSize()); channel.writeAndFlush(data); @@ -507,7 +507,8 @@ private void processEvents(NetData.NetMessage message) { Event event = eventSerializer.deserialize(eventMessage.getEvent()); EventMetadata metadata = eventLibrary.getMetadata(event.getClass()); if (metadata.getNetworkEventType() != NetworkEventType.SERVER) { - logger.warn("Received non-server event '{}' from client '{}'", metadata, getName()); + logger.atWarn().addArgument(() -> metadata).addArgument(() -> getName()). + log("Received non-server event '{}' from client '{}'"); continue; } if (!lagCompensated && metadata.isLagCompensated()) { @@ -524,7 +525,8 @@ private void processEvents(NetData.NetMessage message) { if (Objects.equal(networkSystem.getOwner(target), this)) { target.send(event); } else { - logger.warn("Received event {} for non-owned entity {} from {}", event, target, this); + logger.atWarn().addArgument(() -> event).addArgument(target).addArgument(() -> this). + log("Received event {} for non-owned entity {} from {}"); } } } catch (DeserializationException e) { diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java index 441db9994cb..84fadef009b 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java @@ -183,7 +183,7 @@ public void host(int port, boolean dedicatedServer) throws HostingFailedExceptio logger.info("Started server on port {}", port); if (config.getServerMOTD() != null) { - logger.info("Server MOTD is \"{}\"", config.getServerMOTD()); + logger.atInfo().addArgument(() -> config.getServerMOTD()).log("Server MOTD is \"{}\""); } else { logger.info("No server MOTD is defined"); } @@ -239,7 +239,7 @@ public JoinStatus join(String address, int port) throws InterruptedException { return connectionHandler.getJoinStatus(); } } else { - logger.warn("Failed to connect to server", connectCheck.cause()); + logger.atWarn().addArgument(connectCheck.cause()).log("Failed to connect to server"); connectCheck.channel().closeFuture().awaitUninterruptibly(); clientGroup.shutdownGracefully(shutdownQuietMs, shutdownTimeoutMs, TimeUnit.MILLISECONDS) .syncUninterruptibly(); @@ -538,7 +538,8 @@ public void unregisterNetworkEntity(EntityRef entity) { if (mode != NetworkMode.CLIENT) { NetworkComponent netComponent = entity.getComponent(NetworkComponent.class); if (netComponent != null) { - logger.debug("Unregistering network entity: {} with netId {}", entity, netComponent.getNetworkId()); + logger.atDebug().addArgument(entity).addArgument(netComponent.getNetworkId()). + log("Unregistering network entity: {} with netId {}"); netIdToEntityId.remove(netComponent.getNetworkId()); if (mode.isServer()) { for (NetClient client : netClientList) { @@ -826,7 +827,7 @@ private void processRemovedClient(Client client) { } clientList.remove(client); clientPlayerLookup.remove(client.getEntity()); - logger.info("Client disconnected: {}", client.getName()); + logger.atInfo().addArgument(() -> client.getName()).log("Client disconnected: {}"); storageManager.deactivatePlayer(client); client.getEntity().send(new DisconnectedEvent()); client.disconnect(); @@ -855,7 +856,7 @@ private void processNewClient(NetClient client) { connectClient(client); // log after connect so that the name has been set: - logger.info("New client entity: {}", client.getEntity()); + logger.atInfo().addArgument(() -> client.getEntity()).log("New client entity: {}"); for (EntityRef netEntity : entityManager.getEntitiesWith(NetworkComponent.class)) { NetworkComponent netComp = netEntity.getComponent(NetworkComponent.class); if (netComp.getNetworkId() != NULL_NET_ID) { @@ -972,7 +973,8 @@ private Map, Integer> generateIds(ClassLibrary classLi int fieldId = 0; for (FieldMetadata field : metadata.getFields()) { if (fieldId >= 256) { - logger.error("Class {} has too many fields (>255), serialization will be incomplete", metadata.getId()); + logger.atError().addArgument(() -> metadata.getId()). + log("Class {} has too many fields (>255), serialization will be incomplete"); break; } field.setId((byte) fieldId); @@ -1000,11 +1002,12 @@ private Map, Integer> applySerializationInfo(List info.getName()). + log("Server has unknown field '{}' on '{}'"); } } } else { - logger.error("Server has unknown class '{}'", info.getName()); + logger.atError().addArgument(() -> info.getName()).log("Server has unknown class '{}'"); } } return idTable; diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java index f4a8dc7ad1f..a56a21ccb05 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java @@ -193,7 +193,7 @@ private void processReceivedChunks() { } private void send(NetData.NetMessage data) { - logger.trace("Sending with size {}", data.getSerializedSize()); + logger.atTrace().addArgument(() -> data.getSerializedSize()).log("Sending with size {}"); channel.writeAndFlush(data); } @@ -232,7 +232,10 @@ private void processEvent(NetData.EventMessage message) { if (target.exists()) { target.send(event); } else { - logger.info("Dropping event {} for unavailable entity {}", event.getClass().getSimpleName(), target); + logger.atInfo(). + addArgument(() -> event.getClass().getSimpleName()). + addArgument(target). + log("Dropping event {} for unavailable entity {}"); } } catch (DeserializationException e) { logger.error("Failed to deserialize event", e); @@ -346,7 +349,7 @@ private void processBlockRegistrations(NetData.NetMessage message) { } blockManager.receiveFamilyRegistration(family, registrationMap); } catch (BlockUriParseException e) { - logger.error("Received invalid block uri {}", blockFamily.getBlockUri(0)); + logger.atError().addArgument(() -> blockFamily.getBlockUri(0)).log("Received invalid block uri {}"); } } } @@ -357,7 +360,8 @@ private void updateEntity(NetData.UpdateEntityMessage updateEntity) { if (currentEntity.exists()) { NetworkComponent netComp = currentEntity.getComponent(NetworkComponent.class); if (netComp == null) { - logger.error("Updating entity with no network component: {}, expected netId {}", currentEntity, updateEntity.getNetId()); + logger.atError().addArgument(() -> currentEntity).addArgument(() -> updateEntity.getNetId()). + log("Updating entity with no network component: {}, expected netId {}"); return; } if (netComp.getNetworkId() != updateEntity.getNetId()) { @@ -371,10 +375,14 @@ private void updateEntity(NetData.UpdateEntityMessage updateEntity) { logger.error("Failed to associated new block entity"); } if (netComp.getNetworkId() != updateEntity.getNetId()) { - logger.error("Network ID lost in update: {}, {} -> {}", currentEntity, updateEntity.getNetId(), netComp.getNetworkId()); + logger.atError(). + addArgument(() -> currentEntity). + addArgument(() -> updateEntity.getNetId()). + addArgument(() -> netComp.getNetworkId()). + log("Network ID lost in update: {}, {} -> {}"); } } else { - logger.warn("Received update for non-existent entity {}", updateEntity.getNetId()); + logger.atWarn().addArgument(() -> updateEntity.getNetId()).log("Received update for non-existent entity {}"); } } From 3f69b34034dfc95bccd238cb30b8e12464a705a5 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 19:54:30 +0100 Subject: [PATCH 10/28] qa engine, particles, fluent logger. --- .../engine/particles/updating/ParticleUpdaterImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java index 2e0b05925f8..dd5f1a3cadf 100644 --- a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java +++ b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java @@ -125,7 +125,8 @@ public void initialize() { for (Class type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) { if (!ParticleSystemFunction.class.isAssignableFrom(type)) { - logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", type.getSimpleName()); + logger.atError().addArgument(() -> type.getSimpleName()). + log("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction"); } else { try { ParticleSystemFunction function = (ParticleSystemFunction) type.newInstance(); From c1230d3b985518d32a7355344af434958d46920b Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 19:54:43 +0100 Subject: [PATCH 11/28] qa engine, persistence, fluent logger. --- .../persistence/internal/GlobalStoreLoader.java | 4 ++-- .../serializers/ComponentSerializer.java | 15 ++++++++------- .../persistence/serializers/EventSerializer.java | 2 +- .../serializers/NetworkEntitySerializer.java | 10 +++++++--- .../persistence/serializers/PrefabSerializer.java | 3 ++- .../serializers/WorldSerializerImpl.java | 2 +- 6 files changed, 21 insertions(+), 15 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java index d6f5f73d9d8..998a88d16e7 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java +++ b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java @@ -93,7 +93,7 @@ private Prefab loadPrefab(EntityData.Prefab prefabData, Map prefabData.getParentName()).addArgument(e).log("Failed to load prefab {}"); return null; } } @@ -112,7 +112,7 @@ private void loadComponentMapping(EntityData.GlobalStore globalStore) { if (componentMetadata != null) { componentIdTable.put(componentMetadata.getType(), index); } else { - logger.warn("Unable to resolve component '{}'", globalStore.getComponentClass(index)); + logger.atWarn().addArgument(globalStore.getComponentClass(index)).log("Unable to resolve component '{}'"); } } diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java index f458f84674b..d6695ced682 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java @@ -100,7 +100,7 @@ public Component deserialize(EntityData.Component componentData, Module context) Component component = componentMetadata.newInstance(); return deserializeOnto(component, componentData, componentMetadata, FieldSerializeCheck.NullCheck.newInstance()); } else { - logger.warn("Unable to deserialize unknown component type: {}", componentData.getType()); + logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); } return null; } @@ -159,7 +159,7 @@ public Component deserializeOnto(Component target, EntityData.Component componen if (componentMetadata != null) { return deserializeOnto(target, componentData, componentMetadata, fieldCheck); } else { - logger.warn("Unable to deserialize unknown component type: {}", componentData.getType()); + logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); } return target; } @@ -179,7 +179,8 @@ private Component deserializeOnto(Component targetComponen if (fieldInfo != null) { dataMap.put(fieldInfo, new ProtobufPersistedData(field.getValue())); } else if (field.hasName()) { - logger.warn("Cannot deserialize unknown field '{}' onto '{}'", field.getName(), componentMetadata.getId()); + logger.atWarn().addArgument(() -> field.getName()).addArgument(() -> componentMetadata.getId()). + log("Cannot deserialize unknown field '{}' onto '{}'"); } } serializer.deserializeOnto(targetComponent, dataMap, fieldCheck); @@ -207,7 +208,7 @@ public EntityData.Component serialize(Component component) { public EntityData.Component serialize(Component component, FieldSerializeCheck check) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(component.getClass()); if (componentMetadata == null) { - logger.error("Unregistered component type: {}", component.getClass()); + logger.atError().addArgument(() -> component.getClass()).log("Unregistered component type: {}"); return null; } EntityData.Component.Builder componentMessage = EntityData.Component.newBuilder(); @@ -262,7 +263,7 @@ public EntityData.Component serialize(Component base, Component delta) { public EntityData.Component serialize(Component base, Component delta, FieldSerializeCheck check) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(base.getClass()); if (componentMetadata == null) { - logger.error("Unregistered component type: {}", base.getClass()); + logger.atError().addArgument(() -> base.getClass()).log("Unregistered component type: {}"); return null; } @@ -325,7 +326,7 @@ public ComponentMetadata getComponentMetadata(EntityData.Co } } if (metadata == null) { - logger.warn("Unable to deserialize unknown component with id: {}", componentData.getTypeIndex()); + logger.atWarn().addArgument(() -> componentData.getTypeIndex()).log("Unable to deserialize unknown component with id: {}"); return null; } return metadata; @@ -337,7 +338,7 @@ public ComponentMetadata getComponentMetadata(EntityData.Co metadata = componentLibrary.resolve(componentData.getType()); } if (metadata == null) { - logger.warn("Unable to deserialize unknown component type: {}", componentData.getType()); + logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); return null; } return metadata; diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java index 585e4ce2875..98d7f15d526 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java @@ -154,7 +154,7 @@ public Class getEventClass(EntityData.Event eventData) { } } if (metadata == null) { - logger.warn("Unable to deserialize unknown event with id: {}", eventData.getType()); + logger.atWarn().addArgument(() -> eventData.getType()).log("Unable to deserialize unknown event with id: {}"); return null; } return metadata.getType(); diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java index 4d1a78492ae..e104ab2b299 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java @@ -130,7 +130,7 @@ private void serializeComponentDelta(Component oldComponent, Component newCompon boolean componentInitial) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(oldComponent.getClass()); if (componentMetadata == null) { - logger.error("Unregistered component type: {}", oldComponent.getClass()); + logger.atError().addArgument(() -> oldComponent.getClass()).log("Unregistered component type: {}"); return; } @@ -165,7 +165,7 @@ private void serializeComponentFull(Component component, boolean ignoreIfNoField boolean componentInitial) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(component.getClass()); if (componentMetadata == null) { - logger.error("Unregistered component type: {}", component.getClass()); + logger.atError().addArgument(() -> component.getClass()).log("Unregistered component type: {}"); return; } @@ -218,7 +218,11 @@ public void deserializeOnto(MutableComponentContainer entity, EntityData.PackedE byte fieldId = entityData.getFieldIds().byteAt(fieldPos); ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId); if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) { - logger.trace("Deserializing field {} of component {} as value {}", fieldMetadata, metadata, entityData.getFieldValue(fieldPos)); + logger.atTrace(). + addArgument(() -> fieldMetadata). + addArgument(() -> metadata). + addArgument(entityData.getFieldValue(fieldPos)). + log("Deserializing field {} of component {} as value {}"); serializer.deserializeOnto(component, fieldMetadata, new ProtobufPersistedData(entityData.getFieldValue(fieldPos))); } fieldPos++; diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java index b42865e041c..1bb95f1b201 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java @@ -155,7 +155,8 @@ private void applyComponentChanges(Module context, EntityData.Prefab prefabData, } } } else if (componentData.hasType()) { - logger.warn("Prefab '{}' contains unknown component '{}'", prefabData.getName(), componentData.getType()); + logger.atWarn().addArgument(() -> prefabData.getName()).addArgument(() -> componentData.getType()). + log("Prefab '{}' contains unknown component '{}'"); } } } diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java index 6b2cecdf94c..514efd4cd19 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java @@ -157,7 +157,7 @@ private void createPrefab(EntityData.Prefab prefabData) { PrefabData protoPrefab = prefabSerializer.deserialize(prefabData); Assets.generateAsset(new ResourceUrn(prefabData.getName()), protoPrefab, Prefab.class); } catch (Exception e) { - logger.error("Failed to create prefab {}", prefabData.getName()); + logger.atError().addArgument(() -> prefabData.getName()).log("Failed to create prefab {}"); } } From 3cd99367b8c07e1ff71343c9033b7cbf70ab6eb1 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 20:13:44 +0100 Subject: [PATCH 12/28] qa engine, physics, fluent logger. --- .../org/terasology/engine/physics/bullet/BulletPhysics.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java index 2cf69fb9a91..cc2ba46f464 100644 --- a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java +++ b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java @@ -241,7 +241,8 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Col hitNormalWorld, voxelPosition); } else { //we hit something we don't understand, assume its nothing and log a warning - logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); + logger.atWarn().addArgument(() -> collisionObject.userData). + log("Unidentified object was hit in the physics engine: {}"); } } @@ -305,7 +306,8 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Set hitNormalWorld, voxelPosition); } else { //we hit something we don't understand, assume its nothing and log a warning - logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); + logger.atWarn().addArgument(() -> collisionObject.userData). + log("Unidentified object was hit in the physics engine: {}"); } } } From c3c6c4b571b6b00086625276a9c0c91f30a439ec Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 20:13:57 +0100 Subject: [PATCH 13/28] qa engine, recording, fluent logger. --- .../engine/recording/EventSystemReplayImpl.java | 11 ++++++----- 1 file changed, 6 insertions(+), 5 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java index 986ea7c2430..b502e278468 100644 --- a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java +++ b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java @@ -276,7 +276,7 @@ private EntityRef getEntityRef(RecordedEvent recordedEvent) { @Override public void registerEvent(ResourceUrn uri, Class eventType) { eventIdMap.put(uri, eventType); - logger.debug("Registering event {}", eventType.getSimpleName()); + logger.atDebug().addArgument(() -> eventType.getSimpleName()).log("Registering event {}"); for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) { if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) { childEvents.put(parent, eventType); @@ -303,11 +303,11 @@ private boolean shouldAddToLibrary(Class eventType) { public void registerEventHandler(ComponentSystem handler) { Class handlerClass = handler.getClass(); if (!Modifier.isPublic(handlerClass.getModifiers())) { - logger.error("Cannot register handler {}, must be public", handlerClass.getName()); + logger.atError().addArgument(() -> handlerClass.getName()).log("Cannot register handler {}, must be public"); return; } - logger.debug("Registering event handler {}", handlerClass.getName()); + logger.atDebug().addArgument(() -> handlerClass.getName()).log("Registering event handler {}"); for (Method method : handlerClass.getMethods()) { ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class); if (receiveEventAnnotation != null) { @@ -336,7 +336,7 @@ public void registerEventHandler(ComponentSystem handler) { logger.debug("Found method: {}", method); if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) { - logger.error("Invalid event handler method: {}", method.getName()); + logger.atError().addArgument(() -> method.getName()).log("Invalid event handler method: {}"); return; } @@ -344,7 +344,8 @@ public void registerEventHandler(ComponentSystem handler) { List> componentParams = Lists.newArrayList(); for (int i = 2; i < types.length; ++i) { if (!Component.class.isAssignableFrom(types[i])) { - logger.error("Invalid event handler method: {} - {} is not a component class", method.getName(), types[i]); + logger.atError().addArgument(() -> method.getName()).addArgument(types[i]). + log("Invalid event handler method: {} - {} is not a component class"); return; } requiredComponents.add((Class) types[i]); From 87fae23df19e069174d6c46f420fc2d366ba87c0 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 22:21:24 +0100 Subject: [PATCH 14/28] qa engine, registry, fluent logger. --- .../org/terasology/engine/registry/InjectionHelper.java | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java b/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java index 75e3282cee5..e0295a5c831 100644 --- a/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java +++ b/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java @@ -73,8 +73,10 @@ public static void inject(final Object object) { logger.error("Failed to inject value {} into field {} of {}", value, field, object, e); } } else { - logger.warn("{} wanted {} injected but CoreRegistry has none.", - object.getClass().getSimpleName(), field.getType().getSimpleName()); + logger.atWarn(). + addArgument(() -> object.getClass().getSimpleName()). + addArgument(() -> field.getType().getSimpleName()). + log("{} wanted {} injected but CoreRegistry has none."); } } From f4487b895a8cd9456e3a4f4d20442d178599a7c7 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 21:12:32 +0100 Subject: [PATCH 15/28] qa engine, rendering, fluent logger. --- .../engine/rendering/ShaderManagerLwjgl.java | 10 +++--- .../engine/rendering/dag/AbstractNode.java | 24 +++++++------- .../engine/rendering/dag/ModuleRendering.java | 6 ++-- .../engine/rendering/dag/RenderGraph.java | 31 +++++++++++-------- .../dag/RenderTaskListGenerator.java | 27 +++++++++------- .../rendering/logic/FloatingTextRenderer.java | 2 +- .../rendering/logic/SkeletonRenderer.java | 2 +- .../rendering/nui/asset/UIDeltaFormat.java | 5 ++- .../engine/rendering/nui/asset/UIFormat.java | 5 +-- .../utils/NUIEditorMenuTreeBuilder.java | 2 +- .../nui/internal/NUIManagerInternal.java | 6 ++-- .../gameDetailsScreen/GameDetailsScreen.java | 9 ++++-- .../videoSettings/VideoSettingsScreen.java | 2 +- .../rendering/nui/skin/UISkinFormat.java | 3 +- .../nui/widgets/UIButtonWebBrowser.java | 6 ++-- .../types/object/ObjectLayoutBuilder.java | 4 +-- .../types/object/SubtypeLayoutBuilder.java | 3 +- .../engine/rendering/opengl/GLSLMaterial.java | 5 +-- .../engine/rendering/opengl/GLSLShader.java | 9 +++--- .../engine/rendering/opengl/OpenGLMesh.java | 4 +-- .../rendering/opengl/OpenGLSkeletalMesh.java | 2 +- .../rendering/opengl/OpenGLTexture.java | 5 +-- .../rendering/world/WorldRendererImpl.java | 7 +++-- 23 files changed, 104 insertions(+), 75 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java b/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java index c1048143efc..c5ae2930f4f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java +++ b/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java @@ -49,11 +49,11 @@ public void initShaders() { private void logCapabilities() { logger.info("Loading Terasology shader manager..."); - logger.info("LWJGL: {} / {}", Version.getVersion(), Platform.get().getName()); - logger.info("GL_VENDOR: {}", GL11.glGetString(GL11.GL_VENDOR)); - logger.info("GL_RENDERER: {}", GL11.glGetString(GL11.GL_RENDERER)); - logger.info("GL_VERSION: {}", GL11.glGetString(GL11.GL_VERSION)); - logger.info("SHADING_LANGUAGE VERSION: {}", GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION)); + logger.atInfo().addArgument(() -> Version.getVersion()).addArgument(() -> Platform.get().getName()).log("LWJGL: {} / {}"); + logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_VENDOR)).log("GL_VENDOR: {}"); + logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_RENDERER)).log("GL_RENDERER: {}"); + logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_VERSION)).log("GL_VERSION: {}"); + logger.atInfo().addArgument(() -> GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION)).log("SHADING_LANGUAGE VERSION: {}"); int[] extension = new int[1]; GL30.glGetIntegerv(GL30.GL_NUM_EXTENSIONS, extension); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java index 1f84907ce68..3a3265dfce3 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java @@ -204,8 +204,8 @@ public boolean addOutputBufferPairConnection(int id, BufferPair bufferPair) { } if (localBufferPairConnection.getData() != null) { - logger.warn("Adding output buffer pair to slot id {} of {} node overwrites data of existing connection: {}", - id, this.nodeUri, localBufferPairConnection); + logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(localBufferPairConnection). + log("Adding output buffer pair to slot id {} of {} node overwrites data of existing connection: {}"); } localBufferPairConnection.setData(bufferPair); success = true; @@ -241,8 +241,8 @@ public boolean addOutputBufferPairConnection(int id, BufferPairConnection from) } if (localBufferPairConnection.getData() != null) { - logger.warn("Adding output buffer pair connection to slot id {} of {} node overwrites data of existing connection: {}", - id, this.nodeUri, localBufferPairConnection); + logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(localBufferPairConnection). + log("Adding output buffer pair connection to slot id {} of {} node overwrites data of existing connection: {}"); } localBufferPairConnection.setData(from.getData()); @@ -303,8 +303,8 @@ protected boolean addOutputFboConnection(int id, FBO fboData) { FboConnection fboConnection = (FboConnection) outputConnections.get(connectionUri); if (fboConnection.getData() != null) { - logger.warn("Adding output fbo data to slot id {} of {} node overwrites data of existing connection: {}", - id, this.nodeUri, fboConnection); + logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(fboConnection). + log("Adding output fbo data to slot id {} of {} node overwrites data of existing connection: {}"); } fboConnection.setData(fboData); @@ -443,7 +443,8 @@ public int getNumberOfOutputConnections() { public DependencyConnection getInputConnection(String name) { DependencyConnection connection = inputConnections.get(name); if (connection == null) { - logger.error("Getting input connection named {} returned null. No such input connection in {}", name, this); + logger.atError().addArgument(name).addArgument(this). + log("Getting input connection named {} returned null. No such input connection in {}"); // throw new NullPointerException(errorMessage); } return connection; @@ -453,7 +454,8 @@ public DependencyConnection getInputConnection(String name) { public DependencyConnection getOutputConnection(String name) { DependencyConnection connection = outputConnections.get(name); if (connection == null) { - logger.error("Getting output connection named {} returned null. No such output connection in {}.", name, this); + logger.atError().addArgument(name).addArgument(this). + log("Getting output connection named {} returned null. No such output connection in {}."); // throw new NullPointerException(errorMessage); } return connection; @@ -472,7 +474,7 @@ public List getOutputConnectionsList() { } public void disconnectInputFbo(int inputId) { - logger.info("Disconnecting {} input Fbo number {}", this.getUri(), inputId); + logger.atInfo().addArgument(() -> this.getUri()).addArgument(inputId).log("Disconnecting {} input Fbo number {}"); DependencyConnection connectionToDisconnect = this.inputConnections.get(FboConnection.getConnectionName(inputId, this.nodeUri)); if (connectionToDisconnect != null) { // TODO make it reconnectInputFboToOutput @@ -547,8 +549,8 @@ public void dispose() { */ protected void addDesiredStateChange(StateChange stateChange) { if (stateChange.isTheDefaultInstance()) { - logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})", - stateChange.getClass().getSimpleName(), this); + logger.atError().addArgument(() -> stateChange.getClass().getSimpleName()).addArgument(this). + log("Attempted to add default state change {} to the set of desired state changes. (Node: {})"); } desiredStateChanges.add(stateChange); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java b/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java index 271f304ec8e..bc25fb341c3 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java @@ -118,9 +118,11 @@ protected FBO generateWithDimensions(FboConfig fboConfig, FBO.Dimensions dimensi // At this stage it's unclear what should be done in this circumstances as I (manu3d) do not know what // the effects of using an incomplete FrameBuffer are. Throw an exception? Live with visual artifacts? if (fbo.getStatus() == FBO.Status.INCOMPLETE) { - logger.error("FBO {} is incomplete. Look earlier in the log for details.", fboConfig.getName()); + logger.atError().addArgument(() -> fboConfig.getName()). + log("FBO {} is incomplete. Look earlier in the log for details."); } else if (fbo.getStatus() == FBO.Status.UNEXPECTED) { - logger.error("FBO {} has generated an unexpected status code. Look earlier in the log for details.", fboConfig.getName()); + logger.atError().addArgument(() -> fboConfig.getName()). + log("FBO {} has generated an unexpected status code. Look earlier in the log for details."); } return fbo; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java index 7a0ac809d39..9e1e37951e4 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java @@ -52,8 +52,8 @@ public void addNode(Node node) { } if (akaNodeMap.containsKey(nodeAka)) { Node aNode = akaNodeMap.get(nodeAka); - logger.info("Node {} also known as {} already matches existing node with uri {} - attempting replacing...", - nodeUri, nodeAka, aNode.getUri()); + logger.atInfo().addArgument(nodeUri).addArgument(nodeAka).addArgument(() -> aNode.getUri()). + log("Node {} also known as {} already matches existing node with uri {} - attempting replacing..."); replaceNode(aNode, node); } else { nodeMap.put(nodeUri, node); @@ -149,7 +149,8 @@ private void connect(Node... nodeList) { if (!graph.hasEdgeConnecting(fromNode, toNode)) { graph.putEdge(fromNode, toNode); } else { - logger.warn("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri()); + logger.atWarn().addArgument(fromNode.getUri()).addArgument(toNode.getUri()). + log("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri()); } } @@ -169,7 +170,8 @@ public void disconnect(Node fromNode, Node toNode) { Preconditions.checkNotNull(toNode, "toNode cannot be null!"); if (!graph.hasEdgeConnecting(fromNode, toNode)) { - logger.warn("Trying to disconnect two nodes that aren't connected, {} and {}", fromNode.getUri(), toNode.getUri()); + logger.atWarn().addArgument(() -> fromNode.getUri()).addArgument(() -> toNode.getUri()). + log("Trying to disconnect two nodes that aren't connected, {} and {}"); } graph.removeEdge(fromNode, toNode); @@ -275,8 +277,8 @@ private void connectFbo(Node toNode, int inputFboId, DependencyConnection fromCo } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", - toNode.getUri(), inputFboId, fromConnection.getName()); + logger.atInfo().addArgument(() -> toNode.getUri()).addArgument(inputFboId).addArgument(() -> fromConnection.getName()). + log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections.."); DependencyConnection localConnection = toNode.getInputFboConnection(inputFboId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -302,7 +304,8 @@ public void connectFbo(Node fromNode, int outputId, Node toNode, int inputId) { // if (!areConnected(fromNode, toNode)) { // connect(fromNode, toNode); // } - logger.debug("Connected {} to {}.", fromNode.getOutputFboConnection(outputId), toNode); + logger.atDebug().addArgument(() -> fromNode.getOutputFboConnection(outputId)).addArgument(toNode). + log("Connected {} to {}."); } public void reconnectFbo(Node fromNode, int outputId, Node toNode, int inputId) { @@ -339,8 +342,8 @@ private void connectBufferPair(Node toNode, int inputConnectionId, DependencyCon } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", - toNode.getUri(), inputConnectionId, fromConnection.getName()); + logger.atInfo().addArgument(() -> toNode.getUri()).addArgument(inputConnectionId).addArgument(() -> fromConnection.getName()). + log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections.."); DependencyConnection localConnection = toNode.getInputBufferPairConnection(inputConnectionId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -401,7 +404,8 @@ public void connectBufferPair(Node fromNode, int outputId, Node toNode, int inpu // if (!areConnected(fromNode, toNode)) { // connect(fromNode, toNode); // } - logger.debug("Connected {} to {}.", fromNode.getOutputBufferPairConnection(outputId), toNode); + logger.atDebug().addArgument(() -> fromNode.getOutputBufferPairConnection(outputId)).addArgument(toNode). + log("Connected {} to {}."); } /** @@ -529,13 +533,14 @@ public void reconnectInputToOutput(String fromNodeUri, int outputId, Node toNode */ private void reconnectInputToOutput(Node toNode, int inputId, DependencyConnection fromConnection, ConnectionType connectionType, boolean disconnectPrevious) { - logger.debug("Attempting reconnection of {} to {}'s output.", toNode.getUri(), fromConnection.getParentNode()); + logger.atDebug().addArgument(() -> toNode.getUri()).addArgument(() -> fromConnection.getParentNode()). + log("Attempting reconnection of {} to {}'s output."); Node fromNode; fromNode = findNode(fromConnection.getParentNode()); if (!fromConnection.getConnectedConnections().isEmpty()) { - logger.warn("WARNING: destination connection ({}) is already connected to ({})", - fromConnection, fromConnection.getConnectedConnections()); + logger.atWarn().addArgument(fromConnection).addArgument(() -> fromConnection.getConnectedConnections()). + log("WARNING: destination connection ({}) is already connected to ({})"); // TODO update the hashmap to string to be pretty // throw new RuntimeException("Could not reconnect, destination connection (" + fromConnection + ") is already connected to (" // + fromConnection.getConnectedConnections() + "). Remove connection first."); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java index 387d780f709..d00ad950fde 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java @@ -48,15 +48,15 @@ private void logIntermediateRendererListForDebugging(List orderedNodes) { if (node.isEnabled()) { // printing out node name - logger.info("----- {}", node.getClass().getSimpleName()); + logger.atInfo().addArgument(() -> node.getClass().getSimpleName()).log("----- {}"); // printing out individual desired state changes for (StateChange desiredStateChange : node.getDesiredStateChanges()) { - logger.info("{}", desiredStateChange); + logger.atInfo().addArgument(desiredStateChange).log("{}"); } // printing out process() statement - logger.info("{}: process()", node); + logger.atInfo().addArgument(node).log("{}: process()"); } } } @@ -167,15 +167,20 @@ public List generateFrom(List orderedNodes) { long endTimeInNanoSeconds = System.nanoTime(); // if (logger.isDebugEnabled()) { - logger.debug("===== INTERMEDIATE RENDERER LIST ========================="); + logger.atDebug().log("===== INTERMEDIATE RENDERER LIST ========================="); logIntermediateRendererListForDebugging(orderedNodes); - logger.debug("===== RENDERER TASK LIST ================================="); + logger.atDebug().log("===== RENDERER TASK LIST ================================="); logList(taskList); - logger.debug("----------------------------------------------------------"); - logger.debug("Task list generated in {} ms", String.format("%.3f", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f)); - logger.debug("{} nodes, {} enabled - {} tasks (excluding marker tasks) out of {} potential tasks.", - nodeList.size(), enabledNodes, taskList.size() - enabledNodes, potentialTasks); - logger.debug("----------------------------------------------------------"); + logger.atDebug().log("----------------------------------------------------------"); + logger.atDebug().addArgument(() -> String.format("%.3f", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f)). + log("Task list generated in {} ms"); + logger.atDebug(). + addArgument(() -> nodeList.size()). + addArgument(enabledNodes). + addArgument(taskList.size() - enabledNodes). + addArgument(potentialTasks). + log("{} nodes, {} enabled - {} tasks (excluding marker tasks) out of {} potential tasks."); + logger.atDebug().log("----------------------------------------------------------"); // } return taskList; @@ -183,7 +188,7 @@ public List generateFrom(List orderedNodes) { private void logList(List list) { for (Object object : list) { - logger.debug("{}", object); + logger.atDebug().addArgument(object).log("{}"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java b/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java index 965e924b9ec..c8abc1a308f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java @@ -77,7 +77,7 @@ private void render(Iterable floatingTextEntities) { LocationComponent location = entity.getComponent(LocationComponent.class); if (location == null) { - logger.warn("location component is not defined can't render text: {}", floatingText.text); + logger.atWarn().addArgument(() -> floatingText.text).log("location component is not defined can't render text: {}"); continue; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java b/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java index 4a12ee09c69..845edd2c6ff 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java @@ -307,7 +307,7 @@ public void renderOpaque() { boneTransform.mul(bone.getInverseBindMatrix()); boneTransforms[bone.getIndex()] = boneTransform.transpose(); } else { - logger.warn("Unable to resolve bone \"{}\"", bone.getName()); + logger.atWarn().addArgument(() -> bone.getName()).log("Unable to resolve bone \"{}\""); boneTransforms[bone.getIndex()] = new Matrix4f(); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java index c02dc4bc04b..f0bce128267 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java @@ -47,7 +47,10 @@ public void apply(AssetDataFile input, UIData assetData) throws IOException { if (skin.isPresent()) { assetData.getRootWidget().setSkin(skin.get()); } else { - logger.warn("Failed to load skin {} for the delta file {}", skinUri, input.getFilename()); + logger.atWarn(). + addArgument(skinUri). + addArgument(() -> input.getFilename()). + log("Failed to load skin {} for the delta file {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java index 567132e2eea..37b30f544ce 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java @@ -175,7 +175,7 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC if (id != null) { FieldMetadata fieldMetadata = elementMetadata.getField(ID_FIELD); if (fieldMetadata == null) { - logger.warn("UIWidget type {} lacks id field", elementMetadata.getId()); + logger.atWarn().addArgument(() -> elementMetadata.getId()).log("UIWidget type {} lacks id field"); } else { fieldMetadata.setValue(element, id); } @@ -218,7 +218,8 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC field.setValue(element, context.deserialize(jsonObject.get(field.getSerializationName()), field.getType())); } } catch (RuntimeException e) { - logger.error("Failed to deserialize field {} of {}", field.getName(), type, e); + logger.atError().addArgument(() -> field.getName()).addArgument(type).addArgument(e). + log("Failed to deserialize field {} of {}"); } } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java index 2ccbb245d56..016b40dec37 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java @@ -259,7 +259,7 @@ private void populateContextMenu(JsonTree node, MenuTree addTree, boolean isSkin } } } else { - logger.warn("Could not get class for node {}", node.getValue()); + logger.atWarn().addArgument(() -> node.getValue()).log("Could not get class for node {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java index 70c8e046633..af2ee4ce3e9 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java @@ -365,7 +365,8 @@ public T createScreen(ResourceUrn screenUri, Class root.getClass()).addArgument(expectedType). + log("Screen '{}' is a '{}' and not a '{}'"); } } return null; @@ -490,7 +491,8 @@ public T addOverlay(ResourceUrn overlayUri, Class e addOverlay(overlay, overlayUri); return overlay; } else { - logger.error("Screen '{}' is a '{}' and not a '{}'", overlayUri, root.getClass(), expectedType); + logger.atError().addArgument(overlayUri).addArgument(() -> root.getClass()).addArgument(expectedType). + log("Screen '{}' is a '{}' and not a '{}'"); } } return null; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java index dc06e16d0f4..31d98494b45 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java @@ -354,16 +354,19 @@ private void loadGameModules() { if (module != null) { return ModuleSelectionInfo.strictVersion(module); } else { - logger.warn("Can't find module in your classpath - {}:{}", nameVersion.getName(), nameVersion.getVersion()); + logger.atWarn().addArgument(() -> nameVersion.getName()).addArgument(() -> nameVersion.getVersion()). + log("Can't find module in your classpath - {}:{}"); module = moduleManager.getRegistry().getLatestModuleVersion(nameVersion.getName()); if (module != null) { - logger.debug("Get the latest available version of module {} in your classpath", nameVersion.getName()); + logger.atDebug().addArgument(() -> nameVersion.getName()). + log("Get the latest available version of module {} in your classpath"); errors.add(String.format("Can't find module %s:%s in your classpath; " + "loaded description for the latest available version.", nameVersion.getName(), nameVersion.getVersion())); return ModuleSelectionInfo.latestVersion(module); } - logger.error("Can't find any versions of module {} in your classpath!", nameVersion.getName()); + logger.atError().addArgument(() -> nameVersion.getName()). + log("Can't find any versions of module {} in your classpath!"); errors.add(String.format("Can't find any versions of module %s in your classpath!", nameVersion.getName())); return ModuleSelectionInfo.unavailableVersion(nameVersion.getName().toString(), nameVersion.getVersion().toString()); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java index 591957f3dba..47f6a08632a 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java @@ -355,7 +355,7 @@ public boolean onKeyEvent(NUIKeyEvent event) { } public void saveSettings() { - logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); + logger.atInfo().addArgument(() -> config.renderConfigAsJson(config.getRendering())).log("Video Settings: {}"); // TODO: add a dirty flag that checks if recompiling is needed CoreRegistry.get(ShaderManager.class).recompileAllShaders(); triggerBackAnimation(); diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java index 9d47574896f..39ac38f581d 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java @@ -145,7 +145,8 @@ public void apply(UISkinBuilder builder) { builder.setElementClass(metadata.getType()); entry.getValue().apply(builder); } else { - logger.warn("Failed to resolve UIWidget class {}, skipping style information", entry.getKey()); + logger.atWarn().addArgument(() -> entry.getKey()). + log("Failed to resolve UIWidget class {}, skipping style information"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java index 108fb31036d..8a32043ca2b 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java @@ -68,7 +68,7 @@ public class UIButtonWebBrowser extends UIButton { try { desktop.browse(new URI(this.url)); } catch (IOException | URISyntaxException e) { - logger.warn("Can't open {} in default browser of your system.", this.url); + logger.atWarn().addArgument(() -> this.url).log("Can't open {} in default browser of your system."); showErrorPopup("Can't open " + this.url + " in default browser of your system."); } } else { @@ -83,7 +83,7 @@ public class UIButtonWebBrowser extends UIButton { runtime.exec(createCommand("xdg-open", this.url)); } } catch (IOException e) { - logger.warn("Can't recognize your OS and open the url {}.", this.url); + logger.atWarn().addArgument(() -> this.url).log("Can't recognize your OS and open the url {}."); showErrorPopup("Can't recognize your OS and open the url " + this.url); } } @@ -125,7 +125,7 @@ private void showConfirmationPopup() { confirmUrlPopup.setCheckbox(webBrowserConfig, this.url); } } catch (MalformedURLException e) { - logger.error("{} is malformed", this.url, e); + logger.atError().addArgument(() -> this.url).addArgument(e).log("{} is malformed"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java index 14268507bed..22c763f0da7 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java @@ -192,8 +192,8 @@ private void populateConstructorParameters(Binding binding, library.getBaseTypeWidget((Binding) argumentBinding, parameterType); if (!optionalWidget.isPresent()) { - LOGGER.warn("Could not create widget for parameter of type {} of constructor {}", - parameter, selectedConstructor.get()); + LOGGER.atWarn().addArgument(parameter).addArgument(() -> selectedConstructor.get()). + log("Could not create widget for parameter of type {} of constructor {}"); continue; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java index b45b7ed9129..76d1ee0803c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java @@ -147,7 +147,8 @@ protected void onSet() { .orElse(baseTypeWidgetBuilder); if (builder == null) { - LOGGER.error("Could not find widget for type {}, editing as base type {}", get(), baseType); + LOGGER.atError().addArgument(() -> get()).addArgument(baseType). + log("Could not find widget for type {}, editing as base type {}"); return; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java index 3a65a2d0bc3..090cf99d3ed 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java @@ -156,7 +156,7 @@ public final void doReload(MaterialData data) { rebindVariables(data); }); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } @@ -228,7 +228,8 @@ public void activateFeature(ShaderProgramFeature feature) { activeFeaturesMask = ShaderProgramFeature.getBitset(activeFeatures); activeFeaturesChanged = true; } else { - logger.error("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn()); + logger.atError().addArgument(feature).addArgument(() -> getUrn()).addArgument(() -> shader.getUrn()). + log("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn()); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java index 3d65a79a6fc..749fb9e072e 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java @@ -278,7 +278,8 @@ private void registerAllShaderPermutations() { disposalAction.vertexPrograms.put(featureHash, vertShaderId); } - logger.debug("Compiled {} permutations for {}.", allPermutations.size(), getUrn()); + logger.atDebug().addArgument(() -> allPermutations.size()).addArgument(() -> getUrn()). + log("Compiled {} permutations for {}."); } private String assembleShader(int type, Set features) { @@ -364,7 +365,7 @@ private int compileShader(int type, Set features) { protected void doReload(ShaderData data) { try { GameThread.synch(() -> { - logger.debug("Recompiling shader {}.", getUrn()); + logger.atDebug().addArgument(() -> getUrn()).log("Recompiling shader {}."); disposalAction.disposeData(); shaderProgramBase = data; @@ -376,11 +377,11 @@ protected void doReload(ShaderData data) { try { registerAllShaderPermutations(); } catch (RuntimeException e) { - logger.warn("{}", e.getMessage()); + logger.atWarn().addArgument(() -> e.getMessage()).log("{}"); } }); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java index 0a52d1f7e67..833a1bc589f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java @@ -54,7 +54,7 @@ protected void doReload(MeshData newData) { try { GameThread.synch(() -> buildMesh(newData)); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } @@ -86,7 +86,7 @@ public void render() { } GL30.glBindVertexArray(0); } else { - logger.error("Attempted to render disposed mesh: {}", getUrn()); + logger.atError().addArgument(() -> getUrn()).log("Attempted to render disposed mesh: {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java index e9a83c48efd..2e53f93539c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java @@ -112,7 +112,7 @@ protected void doReload(SkeletalMeshData newData) { GL30.glBindVertexArray(0); }); } catch (InterruptedException e) { - logger.error("Failed to reload {}", getUrn(), e); + logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java index 13a89423715..049304ee9be 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java @@ -82,7 +82,8 @@ protected void doReload(TextureData data) { resources.graphicsManager.disposeTexture(newId); } else { resources.id = newId; - logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); + logger.atDebug().addArgument(() -> getUrn()).addArgument(resources.id). + log("Bound texture '{}' - {}"); } } }); @@ -104,7 +105,7 @@ protected void doReload(TextureData data) { resources.graphicsManager.disposeTexture(newId); } else { resources.id = newId; - logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); + logger.atDebug().addArgument(() -> getUrn()).addArgument(resources.id).log("Bound texture '{}' - {}"); } } }); diff --git a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java index e8a1472d271..46f8727370f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java +++ b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java @@ -205,9 +205,10 @@ private void initRenderingModules() { for (ModuleRendering moduleRenderingInstance : renderingModuleRegistry.getOrderedRenderingModules()) { if (moduleRenderingInstance.isEnabled()) { - logger.info("\nInitialising rendering class {} from {} module.\n", - moduleRenderingInstance.getClass().getSimpleName(), - moduleRenderingInstance.getProvidingModule()); + logger.atInfo(). + addArgument(moduleRenderingInstance.getClass().getSimpleName()). + addArgument(moduleRenderingInstance.getProvidingModule()). + log("\nInitialising rendering class {} from {} module.\n"); moduleRenderingInstance.initialise(); } } From 1a7fe0b689cc9795eecd8907c3ef6b99ec63b78d Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 22:22:05 +0100 Subject: [PATCH 16/28] qa engine, utilities, fluent logger. --- engine/src/main/java/org/terasology/engine/utilities/Jvm.java | 4 ++-- .../engine/utilities/concurrency/TaskProcessor.java | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/utilities/Jvm.java b/engine/src/main/java/org/terasology/engine/utilities/Jvm.java index 6a11745d3df..bdca4a848b8 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/Jvm.java +++ b/engine/src/main/java/org/terasology/engine/utilities/Jvm.java @@ -28,12 +28,12 @@ public static void logClasspath(Logger aLogger) { Matcher asMavenCache = MAVEN_CACHE.matcher(pathEntry); if (asGradleCache.matches()) { if (asGradleCache.group(1).contains(interestingGroup)) { - aLogger.debug("{}gradle:{}", indent, asGradleCache.group(2)); + aLogger.atDebug().addArgument(indent).addArgument(() -> asGradleCache.group(2)).log("{}gradle:{}"); } else { elidedCount++; } } else if (asMavenCache.matches()) { - aLogger.debug("{}maven:{}", indent, asMavenCache.group(1)); + aLogger.atDebug().addArgument(indent).addArgument(() -> asMavenCache.group(1)).log("{}maven:{}"); } else { String place = pathEntry; if (pathEntry.startsWith(projectRoot)) { diff --git a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java index b0e55dc1a60..5b41d908a35 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java +++ b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java @@ -42,7 +42,7 @@ public void run() { logger.error("Thread interrupted", e); } catch (RuntimeException e) { ThreadMonitor.addError(e); - logger.error("Error in thread {}", Thread.currentThread().getName(), e); + logger.atError().addArgument(Thread.currentThread().getName()).addArgument(e).log("Error in thread {}"); } catch (Error e) { GameThread.asynch(() -> { throw e; // re-throw on game thread to terminate the entire application From 2a293e53047e6cae6496c65e5d801f14e3ce2d2a Mon Sep 17 00:00:00 2001 From: soloturn Date: Sat, 2 Dec 2023 22:22:17 +0100 Subject: [PATCH 17/28] qa engine, world, fluent logger. --- .../engine/world/block/family/BlockFamilyLibrary.java | 4 ++-- .../engine/world/block/internal/BlockManagerImpl.java | 8 +++++--- .../chunks/localChunkProvider/LocalChunkProvider.java | 4 ++-- .../world/chunks/pipeline/ChunkProcessingPipeline.java | 3 ++- .../engine/world/generation/FacetedWorldConfigurator.java | 2 +- .../terasology/engine/world/generation/WorldBuilder.java | 3 ++- .../world/generator/internal/WorldGeneratorManager.java | 3 ++- .../engine/world/viewer/layers/FacetLayers.java | 2 +- 8 files changed, 17 insertions(+), 12 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java b/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java index a7db1027ebb..8f55f529166 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java +++ b/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java @@ -37,7 +37,7 @@ public BlockFamilyLibrary(ModuleEnvironment moduleEnvironment, Context context) for (Class entry : moduleEnvironment.getTypesAnnotatedWith(RegisterBlockFamily.class)) { if (!BlockFamily.class.isAssignableFrom(entry)) { - logger.error("Cannot load {}, must be a subclass of BlockFamily", entry.getSimpleName()); + logger.atError().addArgument(() -> entry.getSimpleName()).log("Cannot load {}, must be a subclass of BlockFamily"); continue; } RegisterBlockFamily registerInfo = entry.getAnnotation(RegisterBlockFamily.class); @@ -96,7 +96,7 @@ public Optional get(Class type) { return result; } catch (Exception e) { - logger.error("Failed to load blockFamily {}", blockFamily, e); + logger.atError().addArgument(blockFamily).addArgument(e).log("Failed to load blockFamily {}"); } return null; } diff --git a/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java b/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java index 113b3494529..46832c13fc2 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java +++ b/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java @@ -95,7 +95,8 @@ public void initialise(List registeredBlockFamilies, if (id != null) { block.setId(id); } else { - logger.error("Missing id for block {} in provided family {}", block.getURI(), family.get().getURI()); + logger.atError().addArgument(() -> block.getURI()).addArgument(() -> family.get().getURI()). + log("Missing id for block {} in provided family {}"); if (generateNewIds) { block.setId(getNextId()); } else { @@ -156,7 +157,8 @@ public void receiveFamilyRegistration(BlockUri familyUri, Map r if (id != null) { block.setId((short) id.intValue()); } else { - logger.error("Missing id for block {} in registered family {}", block.getURI(), familyUri); + logger.atError().addArgument(() -> block.getURI()).addArgument(() -> familyUri). + log("Missing id for block {} in registered family {}"); block.setId(UNKNOWN_ID); } } @@ -189,7 +191,7 @@ protected void registerFamily(BlockFamily family) { private void registerBlock(Block block, RegisteredState newState) { if (block.getId() != UNKNOWN_ID) { - logger.info("Registered Block {} with id {}", block, block.getId()); + logger.atInfo().addArgument(() -> block).addArgument(() -> block.getId()).log("Registered Block {} with id {}"); newState.blocksById.put(block.getId(), block); newState.idByUri.put(block.getURI(), block.getId()); } else { diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java index 9862d75fc75..2e0f4becd0f 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java @@ -301,7 +301,7 @@ private boolean unloadChunkInternal(Vector3ic pos) { try { unloadRequestTaskMaster.put(new ChunkUnloadRequest(chunk, this)); } catch (InterruptedException e) { - logger.error("Failed to enqueue unload request for {}", chunk.getPosition(), e); + logger.atError().addArgument(() -> chunk.getPosition()).addArgument(e).log("Failed to enqueue unload request for {}"); } return true; @@ -311,7 +311,7 @@ void gatherBlockPositionsForDeactivate(Chunk chunk) { try { deactivateBlocksQueue.put(createBatchBlockEventMappings(chunk)); } catch (InterruptedException e) { - logger.error("Failed to queue deactivation of blocks for {}", chunk.getPosition()); + logger.atError().addArgument(() -> chunk.getPosition()).log("Failed to queue deactivation of blocks for {}"); } } diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java b/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java index d560a103ae2..72ab6ff8b9e 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java @@ -116,7 +116,8 @@ private void onStageDone(PositionFuture future, ChunkProcessingInfo chunk chunkProcessingInfo.getChunkTaskProvider() == null ? "Generation or Loading" : chunkProcessingInfo.getChunkTaskProvider().getName(); - logger.error("ChunkTask at position {} and stage [{}] catch error: ", chunkProcessingInfo.getPosition(), stageName, e); + logger.atError().addArgument(chunkProcessingInfo.getPosition()).addArgument(stageName).addArgument(e.getMessage()). + log("ChunkTask at position {} and stage [{}] catch error: {}"); chunkProcessingInfo.getExternalFuture().setException(e); } catch (CancellationException ignored) { } diff --git a/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java b/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java index 5972217e14d..7151438d351 100644 --- a/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java +++ b/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java @@ -30,7 +30,7 @@ public FacetedWorldConfigurator(List providersList) { for (ConfigurableFacetProvider provider : providersList) { Component old = properties.put(provider.getConfigurationName(), provider.getConfiguration()); if (old != null) { - logger.warn("Duplicate property key: {}", provider.getConfigurationName()); + logger.atWarn().addArgument(() -> provider.getConfigurationName()).log("Duplicate property key: {}"); } } this.providers = providersList; diff --git a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java index 4152d645ea3..bf5c888367e 100644 --- a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java +++ b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java @@ -184,7 +184,8 @@ private ListMultimap, FacetProvider> determineProvid if (requires != null) { for (Facet facet : requires.value()) { if (!facets.contains(facet.value())) { - logger.error("Facet provider for {} is missing. It is required by {}", facet.value(), provider.getClass()); + logger.atError().addArgument(() -> facet.value()).addArgument(() -> provider.getClass()). + log("Facet provider for {} is missing. It is required by {}"); throw new IllegalStateException("Missing facet provider"); } } diff --git a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java index 832498c5a8e..92597629c4d 100644 --- a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java +++ b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java @@ -70,7 +70,8 @@ public void refresh() { } } } catch (Exception e) { - logger.error("Error loading world generator in module {}, skipping", module.getId(), e); + logger.atError().addArgument(() -> module.getId()).addArgument(e). + log("Error loading world generator in module {}, skipping"); } } else { logger.warn("Could not resolve dependencies for module: {}", module); diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java b/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java index 99dd18ceb68..5cdbc3ad7bf 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java @@ -78,7 +78,7 @@ private static Collection createLayersFor(Class facetClass.getName()).log("No layers found for facet {}"); } return result; From be19e627907ef544ee511f9cbf323902ad5344e1 Mon Sep 17 00:00:00 2001 From: soloturn Date: Mon, 12 Feb 2024 09:36:48 +0100 Subject: [PATCH 18/28] review feedback pr introduce local varaible where necessary, otherwise ignore warning for the sake of shorter log message line. --- .../engine/audio/openAL/OpenALManager.java | 16 +++++----- .../flexible/AutoConfigTypeHandler.java | 10 +++---- .../constraints/StringConstraint.java | 9 +++--- .../config/flexible/ui/AutoConfigScreen.java | 2 +- .../flexible/ui/AutoConfigWidgetFactory.java | 2 +- .../engine/core/ComponentSystemManager.java | 2 +- .../terasology/engine/core/PathManager.java | 2 +- .../engine/core/TerasologyEngine.java | 29 +++++++++---------- .../engine/core/modes/StateLoading.java | 2 +- .../modes/loadProcesses/InitialiseWorld.java | 6 ++-- .../engine/core/module/ModuleInstaller.java | 2 +- .../core/module/ModuleListDownloader.java | 4 +-- .../engine/core/module/ModuleManager.java | 5 ++-- .../subsystem/lwjgl/GLFWErrorCallback.java | 4 +-- .../entity/internal/PojoEntityManager.java | 6 ++-- .../event/internal/EventSystemImpl.java | 4 +-- .../metadata/ComponentLibrary.java | 3 +- .../terasology/engine/game/GameManifest.java | 5 ++-- .../logic/characters/CharacterSystem.java | 2 +- .../internal/GlobalStoreLoader.java | 5 ++-- .../pipeline/ChunkProcessingPipeline.java | 3 +- .../internal/WorldGeneratorManager.java | 3 +- .../world/viewer/layers/FacetLayers.java | 2 +- 23 files changed, 59 insertions(+), 69 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java index 4396de68e60..2778f95fc3d 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java @@ -52,6 +52,7 @@ public class OpenALManager implements AudioManager { private final Map, AudioEndListener> endListeners = Maps.newHashMap(); + @SuppressWarnings("PMD.GuardLogStatement") public OpenALManager(AudioConfig config) throws OpenALException { logger.info("Initializing OpenAL audio manager"); @@ -66,14 +67,13 @@ public OpenALManager(AudioConfig config) throws OpenALException { logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_VERSION)).log("OpenAL {} initialized!"); - logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_RENDERER)).addArgument(() -> AL10.alGetString(AL10.AL_VENDOR)). - log("Using OpenAL: {} by {}"); - logger.atInfo().addArgument(() -> ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER)).log("Using device: {}"); - logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_EXTENSIONS)).log("Available AL extensions: {}"); - logger.atInfo().addArgument(() -> ALC10.alcGetString(device, ALC10.ALC_EXTENSIONS)).log("Available ALC extensions: {}"); - logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC11.ALC_MONO_SOURCES)).log("Max mono sources: {}"); - logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC11.ALC_STEREO_SOURCES)).log("Max stereo sources: {}"); - logger.atInfo().addArgument(() -> ALC10.alcGetInteger(device, ALC10.ALC_FREQUENCY)).log("Mixer frequency: {}"); + logger.info("Using OpenAL: {} by {}", AL10.alGetString(AL10.AL_RENDERER), AL10.alGetString(AL10.AL_VENDOR)); + logger.info("Using device: {}", ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER)); + logger.info("Available AL extensions: {}", AL10.alGetString(AL10.AL_EXTENSIONS)); + logger.info("Available ALC extensions: {}", ALC10.alcGetString(device, ALC10.ALC_EXTENSIONS)); + logger.info("Max mono sources: {}", ALC10.alcGetInteger(device, ALC11.ALC_MONO_SOURCES)); + logger.info("Max stereo sources: {}", ALC10.alcGetInteger(device, ALC11.ALC_STEREO_SOURCES)); + logger.info("Mixer frequency: {}", ALC10.alcGetInteger(device, ALC10.ALC_FREQUENCY)); AL10.alDistanceModel(AL10.AL_INVERSE_DISTANCE_CLAMPED); diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java index 5e9597556fc..060e5b8a2f7 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java @@ -43,7 +43,7 @@ protected PersistedData serializeNonNull(AutoConfig value, PersistedDataSerializ if (typeHandler.isPresent()) { fields.put(field.getName(), typeHandler.get().serialize(setting.get(), serializer)); } else { - logger.atError().addArgument(() -> setting.getValueType()).log("Cannot serialize type [{}]"); + logger.error("Cannot serialize type [{}]", setting.getValueType()); //NOPMD } } } catch (IllegalAccessException e) { @@ -65,7 +65,7 @@ public Optional deserialize(PersistedData data) { for (Map.Entry entry : data.getAsValueMap().entrySet()) { Field settingField = settingFields.get(entry.getKey()); if (settingField == null) { - logger.atWarn().addArgument(() -> entry.getKey()).log("Cannot to find setting field with name [{}]"); + logger.warn("Cannot to find setting field with name [{}]", entry.getKey()); //NOPMD continue; } try { @@ -77,11 +77,11 @@ public Optional deserialize(PersistedData data) { if (value.isPresent()) { setting.set(value.get()); } else { - logger.atError().addArgument(() -> entry.getValue()).addArgument(setting.getValueType()). - log("Cannot deserialize value [{}] to type [{}]"); + logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(), + setting.getValueType()); //NOPMD } } else { - logger.atError().addArgument(() -> setting.getValueType()).log("Cannot deserialize type [{}]"); + logger.error("Cannot deserialize type [{}]", setting.getValueType()); //NOPMD } } catch (IllegalAccessException e) { // ignore, AutoConfig.getSettingsFieldsIn return public fields. diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java index e4ef91cd6f5..faf91707441 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/StringConstraint.java @@ -49,13 +49,12 @@ public boolean isSatisfiedBy(String value) { } @Override + @SuppressWarnings("PMD.GuardLogStatement") public void warnUnsatisfiedBy(String value) { - logger.atWarn(). - addArgument(value). - addArgument(() -> predicates.stream() + logger.warn("String [{}] does not match the conditions: {}", value, + predicates.stream() .filter(p -> !p.test(value)) .map(StringConstraint::getDescription) - .collect(Collectors.joining(",", "[", "]"))). - log("String [{}] does not match the conditions: {}"); + .collect(Collectors.joining(",", "[", "]"))); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java index c9800ec11f1..c91d45e7e79 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigScreen.java @@ -46,7 +46,7 @@ public void initialise() { if (widget.isPresent()) { mainContainer.addWidget(widget.get()); } else { - logger.atWarn().addArgument(() -> config.getId()).log("Cannot create widget for config: {}"); + logger.warn("Cannot create widget for config: {}", config.getId()); //NOPMD } } WidgetUtil.trySubscribe(this, "close", button -> triggerBackAnimation()); diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java index 8b8d49e3896..4640420804c 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/ui/AutoConfigWidgetFactory.java @@ -79,7 +79,7 @@ public UIWidget buildWidgetFor(AutoConfig config) { Optional settingWidget = settingWidgetFactory.createWidgetFor(setting); if (!settingWidget.isPresent()) { - logger.atError().addArgument(() -> setting.getHumanReadableName()).log("Couldn't find a widget for the Setting [{}]"); + logger.error("Couldn't find a widget for the Setting [{}]", setting.getHumanReadableName()); //NOPMD continue; } diff --git a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java index 973eb0bae6f..4e4fbfbd6f7 100644 --- a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java +++ b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java @@ -68,7 +68,7 @@ public void loadSystems(ModuleEnvironment environment, NetworkMode netMode) { ListMultimap> systemsByModule = ArrayListMultimap.create(); for (Class type : environment.getTypesAnnotatedWith(RegisterSystem.class)) { if (!ComponentSystem.class.isAssignableFrom(type)) { - logger.atError().addArgument(type.getSimpleName()).log("Cannot load {}, must be a subclass of ComponentSystem"); + logger.error("Cannot load {}, must be a subclass of ComponentSystem", type.getSimpleName()); //NOPMD continue; } Name moduleId = environment.getModuleProviding(type); diff --git a/engine/src/main/java/org/terasology/engine/core/PathManager.java b/engine/src/main/java/org/terasology/engine/core/PathManager.java index e13104d33ef..b66107c882e 100644 --- a/engine/src/main/java/org/terasology/engine/core/PathManager.java +++ b/engine/src/main/java/org/terasology/engine/core/PathManager.java @@ -90,7 +90,7 @@ private static Path findInstallPath() { // Use the current directory as a fallback. Path currentDirectory = Paths.get("").toAbsolutePath(); installationSearchPaths.add(currentDirectory); - LOGGER.atInfo().addArgument(currentDirectory).log("PathManager: Working directory is {}"); + LOGGER.info("PathManager: Working directory is {}", currentDirectory); for (Path startPath : installationSearchPaths) { Path installationPath = findNativesHome(startPath, 5); diff --git a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java index 404a6f02862..7cb6964c88f 100644 --- a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java +++ b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java @@ -265,21 +265,18 @@ private void verifyInitialisation() { /** * Logs software, environment and hardware information. */ + @SuppressWarnings("PMD.GuardLogStatement") private void logEnvironmentInfo() { - logger.atInfo().addArgument(() -> TerasologyVersion.getInstance()).log("{}"); - logger.atInfo().addArgument(() -> PathManager.getInstance().getHomePath()).log("Home path: {}"); - logger.atInfo().addArgument(() -> PathManager.getInstance().getInstallPath()).log("Install path: {}"); - logger.atInfo().addArgument(() -> System.getProperty("java.version")).addArgument(System.getProperty("java.home")). - log("Java: {} in {}"); - logger.atInfo().addArgument(() -> System.getProperty("java.vm.name")).addArgument(() -> System.getProperty("java.vm" + ".version")). - log("Java VM: {}, version: {}"); - logger.atInfo(). - addArgument(() -> System.getProperty("os.name")). - addArgument(() -> System.getProperty("os.arch")). - addArgument(() -> System.getProperty("os.version")). - log("OS: {}, arch: {}, version: {}"); - logger.atInfo().addArgument(() -> Runtime.getRuntime().maxMemory() / ONE_MEBIBYTE).log("Max. Memory: {} MiB"); - logger.atInfo().addArgument(() -> Runtime.getRuntime().availableProcessors()).log("Processors: {}"); + logger.info("{}", TerasologyVersion.getInstance()); + logger.info("Home path: {}", PathManager.getInstance().getHomePath()); + logger.info("Install path: {}", PathManager.getInstance().getInstallPath()); + logger.info("Java: {} in {}", System.getProperty("java.version"), System.getProperty("java.home")); + logger.info("Java VM: {}, version: {}", System.getProperty("java.vm.name"), System.getProperty("java.vm" + + ".version")); + logger.info("OS: {}, arch: {}, version: {}", System.getProperty("os.name"), System.getProperty("os.arch"), + System.getProperty("os.version")); + logger.info("Max. Memory: {} MiB", Runtime.getRuntime().maxMemory() / ONE_MEBIBYTE); + logger.info("Processors: {}", Runtime.getRuntime().availableProcessors()); if (NonNativeJVMDetector.JVM_ARCH_IS_NONNATIVE) { logger.warn("Running on a 32-bit JVM on a 64-bit system. This may limit performance."); } @@ -547,7 +544,7 @@ public void cleanup() { try { subsystem.preShutdown(); } catch (RuntimeException e) { - logger.atError().addArgument(() -> subsystem.getName()).addArgument(e).log("Error preparing to shutdown {} subsystem"); + logger.error("Error preparing to shutdown {} subsystem", subsystem.getName(), e); //NOPMD } } @@ -557,7 +554,7 @@ public void cleanup() { try { subsystem.shutdown(); } catch (RuntimeException e) { - logger.atError().addArgument(() -> subsystem.getName()).addArgument(e).log("Error shutting down {} subsystem"); + logger.error("Error shutting down {} subsystem", subsystem.getName(), e); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java b/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java index b10ec51239a..57102bb17e1 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/StateLoading.java @@ -234,7 +234,7 @@ private void popStep() { current = null; if (!loadProcesses.isEmpty()) { current = loadProcesses.remove(); - logger.atDebug().addArgument(() -> current.getMessage()).log("{}"); + logger.debug("{}", current.getMessage()); //NOPMD current.begin(); } } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java index fbd40d75a79..db4757090bf 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java @@ -94,7 +94,7 @@ public boolean step() { worldInfo.setSeed(random.nextString(16)); } - logger.atInfo().addArgument(() -> worldInfo.getSeed()).log("World seed: \"{}\""); + logger.info("World seed: \"{}\"", worldInfo.getSeed()); //NOPMD // TODO: Separate WorldRenderer from world handling in general WorldGeneratorManager worldGeneratorManager = context.get(WorldGeneratorManager.class); @@ -105,8 +105,8 @@ public boolean step() { worldGenerator.setWorldSeed(worldInfo.getSeed()); context.put(WorldGenerator.class, worldGenerator); } catch (UnresolvedWorldGeneratorException e) { - logger.atError().addArgument(() -> worldInfo.getWorldGenerator()).addArgument(() -> worldGeneratorManager.getWorldGenerators()). - log("Unable to load world generator {}. Available world generators: {}"); + logger.error("Unable to load world generator {}. Available world generators: {}", + worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators()); //NOPMD context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator.")); return true; // We need to return true, otherwise the loading state will just call us again immediately } diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java index 5dd1728367d..cffc6a9f17f 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java @@ -48,7 +48,7 @@ public List call() throws Exception { Module module = moduleManager.registerArchiveModule(filePath); newInstalledModules.add(module); } catch (IOException e) { - logger.atWarn().addArgument(() -> filePath.getFileName()).addArgument(e).log("Could not load module {}"); + logger.warn("Could not load module {}", filePath.getFileName(), e); //NOPMD } } logger.info("Finished loading the downloaded modules"); diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java index 88af4e8f6ef..e5bcce91c70 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleListDownloader.java @@ -59,13 +59,13 @@ public ModuleRegistry call() throws IOException { String json = gson.toJson(jObject); ModuleMetadata meta = metaReader.read(new StringReader(json)); - logger.atDebug().addArgument(() -> meta.getId()).addArgument(() -> meta.getVersion()).log("Read module {} - {}"); + logger.debug("Read module {} - {}", meta.getId(), meta.getVersion()); //NOPMD modules.add(new Module(meta, new EmptyFileSource(), Collections.emptyList(), new Reflections(), (c) -> false)); } int count = modules.size(); - logger.atInfo().addArgument(() -> count).addArgument(() -> (count == 1) ? "entry" : "entries").log("Retrieved {} {}"); + logger.info("Retrieved {} {}", count, (count == 1) ? "entry" : "entries"); //NOPMD } return modules; } diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java index 027fcda0d2b..77d0dc23593 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleManager.java @@ -173,10 +173,9 @@ private void loadModulesFromClassPath() { continue; } if (registry.add(module)) { - logger.atInfo().addArgument(() -> module.getId()).addArgument(() -> path).log("Loaded {} from {}"); + logger.info("Loaded {} from {}", module.getId(), path); //NOPMD } else { - logger.atInfo().addArgument(() -> module.getId()).addArgument(() -> path). - log("Module {} from {} was a duplicate; not registering this copy."); + logger.info("Module {} from {} was a duplicate; not registering this copy.", module.getId(), path); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java b/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java index da939b37952..391916a84e2 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/lwjgl/GLFWErrorCallback.java @@ -14,8 +14,8 @@ public class GLFWErrorCallback implements GLFWErrorCallbackI { private static final Logger logger = LoggerFactory.getLogger("GLFW"); @Override + @SuppressWarnings("PMD.GuardLogStatement") public void invoke(int error, long description) { - logger.atError().addArgument(() -> error).addArgument(() -> MemoryUtil.memASCII(description)). - log("Received error. Code: {}, Description: {}"); + logger.error("Received error. Code: {}, Description: {}", error, MemoryUtil.memASCII(description)); } } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java index 10573b47d91..267952ff887 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/entity/internal/PojoEntityManager.java @@ -526,8 +526,7 @@ public T addComponent(long entityId, T component) { if (!oldComponent.isPresent()) { notifyComponentAdded(getEntity(entityId), component.getClass()); } else { - logger.atError().addArgument(() -> component.getClass()).addArgument(() -> entityId). - log("Adding a component ({}) over an existing component for entity {}"); + logger.error("Adding a component ({}) over an existing component for entity {}", component.getClass(), entityId); //NOPMD notifyComponentChanged(getEntity(entityId), component.getClass()); } @@ -581,8 +580,7 @@ public void saveComponent(long entityId, Component component) { .map(pool -> pool.getComponentStore().put(entityId, component)); if (!oldComponent.isPresent()) { - logger.atError().addArgument(() -> component.getClass()).addArgument(() -> entityId). - log("Saving a component ({}) that doesn't belong to this entity {}"); + logger.error("Saving a component ({}) that doesn't belong to this entity {}", component.getClass(), entityId); //NOPMD } if (eventSystem != null) { EntityRef entityRef = getEntity(entityId); diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java index 72df42bc85b..b4b7647485b 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java @@ -137,8 +137,8 @@ public void registerEventHandler(ComponentSystem handler) { List> componentParams = Lists.newArrayList(); for (int i = 2; i < types.length; ++i) { if (!Component.class.isAssignableFrom(types[i])) { - logger.atError().addArgument(() -> method.getName()).addArgument(types[i]). - log("Invalid event handler method: {} - {} is not a component class"); + logger.error("Invalid event handler method: {} - {} is not a component class", + method.getName(), types[i]); //NOPMD return; } requiredComponents.add((Class) types[i]); diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java index 96302d714ef..37c06572ea3 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java @@ -46,8 +46,7 @@ public ComponentLibrary createCopyUsingCopyStrategy(Class type, CopyStrat try { info = new ComponentMetadata<>(uri, type, factory, copyStrategies); } catch (NoSuchMethodException e) { - logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). - log("Unable to register class {}: Default Constructor Required"); + logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); //NOPMD return null; } catch (NoClassDefFoundError e) { // log what class was not found so that diagnosis is easier diff --git a/engine/src/main/java/org/terasology/engine/game/GameManifest.java b/engine/src/main/java/org/terasology/engine/game/GameManifest.java index 7653da4b535..c0681e58f54 100644 --- a/engine/src/main/java/org/terasology/engine/game/GameManifest.java +++ b/engine/src/main/java/org/terasology/engine/game/GameManifest.java @@ -188,14 +188,13 @@ public void addModule(Name id, Version version) { public String mainWorldDisplayName(WorldGeneratorManager manager) { var world = getWorldInfo(TerasologyConstants.MAIN_WORLD); if (world == null) { - logger.atWarn().addArgument(() -> this).log("{} has no MAIN_WORLD"); + logger.warn("{} has no MAIN_WORLD", this); return "ERROR: No main world"; } SimpleUri generatorUri = world.getWorldGenerator(); var generator = manager.getWorldGeneratorInfo(generatorUri); if (generator == null) { - logger.atWarn().addArgument(() -> this).addArgument(() -> manager).addArgument(() -> generatorUri). - log("{}: {} has no generator for {}"); + logger.warn("{}: {} has no generator for {}", this, manager, generatorUri); return "ERROR: No generator found for " + generatorUri; } return generator.getDisplayName(); diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java index 973043da893..5f233831092 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java @@ -155,7 +155,7 @@ public String getDamageTypeName(Prefab damageType) { return damageType.getComponent(DisplayNameComponent.class).name; } else { String damageTypeName = damageType.getName(); - logger.atInfo().addArgument(damageTypeName).log("{} is missing a readable DisplayName"); + logger.info("{} is missing a readable DisplayName", damageTypeName); //damageType.getName() returns a ResourceUrn String such as "engine:directDamage" //The following calls change the damage type to be more readable //For instance, "engine:directDamage" becomes "Direct Damage" diff --git a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java index 998a88d16e7..b7c58fba2a6 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java +++ b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java @@ -108,11 +108,12 @@ private Prefab createPrefab(EntityData.Prefab prefabData) { private void loadComponentMapping(EntityData.GlobalStore globalStore) { Map, Integer> componentIdTable = Maps.newHashMap(); for (int index = 0; index < globalStore.getComponentClassCount(); ++index) { - ComponentMetadata componentMetadata = componentLibrary.resolve(globalStore.getComponentClass(index)); + String componentClass = globalStore.getComponentClass(index); + ComponentMetadata componentMetadata = componentLibrary.resolve(componentClass); if (componentMetadata != null) { componentIdTable.put(componentMetadata.getType(), index); } else { - logger.atWarn().addArgument(globalStore.getComponentClass(index)).log("Unable to resolve component '{}'"); + logger.warn("Unable to resolve component '{}'", componentClass); } } diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java b/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java index 72ab6ff8b9e..34726ff03ba 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/pipeline/ChunkProcessingPipeline.java @@ -116,8 +116,7 @@ private void onStageDone(PositionFuture future, ChunkProcessingInfo chunk chunkProcessingInfo.getChunkTaskProvider() == null ? "Generation or Loading" : chunkProcessingInfo.getChunkTaskProvider().getName(); - logger.atError().addArgument(chunkProcessingInfo.getPosition()).addArgument(stageName).addArgument(e.getMessage()). - log("ChunkTask at position {} and stage [{}] catch error: {}"); +logger.error("ChunkTask at position {} and stage [{}] catch error: ", chunkProcessingInfo.getPosition(), stageName, e); //NOPMD chunkProcessingInfo.getExternalFuture().setException(e); } catch (CancellationException ignored) { } diff --git a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java index 92597629c4d..00a33cbff17 100644 --- a/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java +++ b/engine/src/main/java/org/terasology/engine/world/generator/internal/WorldGeneratorManager.java @@ -70,8 +70,7 @@ public void refresh() { } } } catch (Exception e) { - logger.atError().addArgument(() -> module.getId()).addArgument(e). - log("Error loading world generator in module {}, skipping"); + logger.error("Error loading world generator in module {}, skipping", module.getId(), e); //NOPMD } } else { logger.warn("Could not resolve dependencies for module: {}", module); diff --git a/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java b/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java index 5cdbc3ad7bf..d815bcdd74e 100644 --- a/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java +++ b/engine/src/main/java/org/terasology/engine/world/viewer/layers/FacetLayers.java @@ -78,7 +78,7 @@ private static Collection createLayersFor(Class facetClass.getName()).log("No layers found for facet {}"); + logger.warn("No layers found for facet {}", facetClass.getName()); //NOPMD } return result; From e9fad3d9584bacf32a3911c598f25a3e9ae11623 Mon Sep 17 00:00:00 2001 From: soloturn Date: Mon, 12 Feb 2024 11:34:53 +0100 Subject: [PATCH 19/28] feedback fluent-logger pr. except to make log line shorter. Co-authored-by: jdrueckert --- .../engine/audio/openAL/OpenALManager.java | 5 ++-- .../audio/openAL/staticSound/OpenALSound.java | 2 +- .../streamingSound/OpenALStreamingSound.java | 2 +- .../config/flexible/AutoConfigManager.java | 4 +-- .../constraints/LocaleConstraint.java | 11 +++---- .../engine/core/TerasologyEngine.java | 2 +- .../engine/core/module/ModuleInstaller.java | 2 +- .../common/ConfigurationSubsystem.java | 2 +- .../event/internal/EventSystemImpl.java | 8 ++--- .../entitySystem/metadata/EventLibrary.java | 3 +- .../entitySystem/metadata/EventMetadata.java | 3 +- .../actions/conditions/ConditionAction.java | 11 ++++--- .../logic/behavior/core/ActionNode.java | 6 ++-- .../logic/behavior/core/DecoratorNode.java | 6 ++-- .../characters/CharacterSoundSystem.java | 2 +- .../ClientCharacterPredictionSystem.java | 5 ++-- .../engine/logic/console/ConsoleImpl.java | 2 +- .../console/commands/ServerCommands.java | 4 +-- .../logic/debug/ChunkEventErrorLogger.java | 4 +-- .../inventory/ItemPickupAuthoritySystem.java | 2 +- .../engine/logic/players/PlayerSystem.java | 2 +- .../network/internal/NetworkSystemImpl.java | 7 ++--- .../engine/network/internal/ServerImpl.java | 2 +- .../updating/ParticleUpdaterImpl.java | 3 +- .../internal/GlobalStoreLoader.java | 2 +- .../serializers/EventSerializer.java | 2 +- .../serializers/PrefabSerializer.java | 3 +- .../serializers/WorldSerializerImpl.java | 2 +- .../engine/physics/bullet/BulletPhysics.java | 6 ++-- .../recording/EventSystemReplayImpl.java | 11 ++++--- .../engine/rendering/dag/AbstractNode.java | 6 ++-- .../engine/rendering/dag/RenderGraph.java | 25 +++++++--------- .../dag/RenderTaskListGenerator.java | 30 ++++++++----------- .../rendering/logic/FloatingTextRenderer.java | 2 +- .../rendering/logic/SkeletonRenderer.java | 2 +- .../engine/rendering/nui/asset/UIFormat.java | 5 ++-- .../utils/NUIEditorMenuTreeBuilder.java | 2 +- .../nui/internal/NUIManagerInternal.java | 6 ++-- .../videoSettings/VideoSettingsScreen.java | 2 +- .../nui/widgets/UIButtonWebBrowser.java | 6 ++-- .../engine/rendering/opengl/GLSLMaterial.java | 5 ++-- .../engine/rendering/opengl/GLSLShader.java | 9 +++--- .../engine/rendering/opengl/OpenGLMesh.java | 4 +-- .../rendering/opengl/OpenGLSkeletalMesh.java | 2 +- .../rendering/opengl/OpenGLTexture.java | 3 +- .../utilities/concurrency/TaskProcessor.java | 2 +- .../block/family/BlockFamilyLibrary.java | 4 +-- .../block/internal/BlockManagerImpl.java | 8 ++--- .../LocalChunkProvider.java | 4 +-- 49 files changed, 112 insertions(+), 141 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java index 2778f95fc3d..573d8192338 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/OpenALManager.java @@ -65,8 +65,7 @@ public OpenALManager(AudioConfig config) throws OpenALException { ALCCapabilities alcCapabilities = ALC.createCapabilities(device); AL.createCapabilities(alcCapabilities); - logger.atInfo().addArgument(() -> AL10.alGetString(AL10.AL_VERSION)).log("OpenAL {} initialized!"); - + logger.info("OpenAL {} initialized!", AL10.alGetString(AL10.AL_VERSION)); logger.info("Using OpenAL: {} by {}", AL10.alGetString(AL10.AL_RENDERER), AL10.alGetString(AL10.AL_VENDOR)); logger.info("Using device: {}", ALC10.alcGetString(device, ALC10.ALC_DEVICE_SPECIFIER)); logger.info("Available AL extensions: {}", AL10.alGetString(AL10.AL_EXTENSIONS)); @@ -261,7 +260,7 @@ private void notifyEndListeners(boolean interrupted) { try { entry.getValue().onAudioEnd(interrupted); } catch (Exception e) { - logger.atError().addArgument(() -> entry.getValue()).addArgument(e).log("onAudioEnd() notification failed for {}"); + logger.error("onAudioEnd() notification failed for {}", entry.getValue(), e); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java b/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java index 742cd18bef8..16e272881d9 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/staticSound/OpenALSound.java @@ -104,7 +104,7 @@ protected void doReload(StaticSoundData newData) { length = (float) size / channels / (bits / 8) / frequency; }); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java b/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java index da21a199386..cd7ddd6bb56 100644 --- a/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java +++ b/engine/src/main/java/org/terasology/engine/audio/openAL/streamingSound/OpenALStreamingSound.java @@ -123,7 +123,7 @@ protected void doReload(StreamingSoundData data) { try { GameThread.synch(this::initializeBuffers); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java index 98102c81ebb..aca5578844a 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigManager.java @@ -85,7 +85,7 @@ private void loadSettingsFromDisk(Class configClass, T T loadedConfig = (T) serializer.deserialize(TypeInfo.of(configClass), inputStream).get(); mergeConfig(configClass, loadedConfig, config); } catch (Exception e) { - logger.atError().addArgument(() -> config.getId()).addArgument(e).log("Error while loading config {} from disk"); + logger.error("Error while loading config {} from disk", config.getId(), e); //NOPMD } } @@ -116,7 +116,7 @@ private void saveConfigToDisk(AutoConfig config) { StandardOpenOption.CREATE)) { serializer.serialize(config, TypeInfo.of((Class) config.getClass()), output); } catch (IOException e) { - logger.atError().addArgument(() -> config.getId()).addArgument(e).log("Error while saving config {} to disk"); + logger.error("Error while saving config {} to disk", config.getId(), e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java index 7efc4891ef9..fabf90889b2 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/LocaleConstraint.java @@ -31,12 +31,13 @@ public boolean isSatisfiedBy(Locale value) { } @Override + @SuppressWarnings("PMD.GuardLogStatement") public void warnUnsatisfiedBy(Locale value) { - logger.atWarn(). - addArgument(value). - addArgument(() -> locales.stream() + logger.warn("Locale {} should be one of {}", + value, + locales.stream() .map(Locale::getLanguage) - .collect(Collectors.joining(",", "[", "]"))). - log("Locale {} should be one of {}"); + .collect(Collectors.joining(",", "[", "]")) + ); } } diff --git a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java index 7cb6964c88f..d3852f083ce 100644 --- a/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java +++ b/engine/src/main/java/org/terasology/engine/core/TerasologyEngine.java @@ -253,7 +253,7 @@ public void initialize() { } double seconds = 0.001 * totalInitTime.elapsed(TimeUnit.MILLISECONDS); - logger.atInfo().addArgument(() -> String.format("%.2f", seconds)).log("Initialization completed in {}sec."); + logger.info("Initialization completed in {}sec.", String.format("%.2f", seconds)); //NOPMD } private void verifyInitialisation() { diff --git a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java index cffc6a9f17f..5f332ab5e54 100644 --- a/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java +++ b/engine/src/main/java/org/terasology/engine/core/module/ModuleInstaller.java @@ -38,7 +38,7 @@ public class ModuleInstaller implements Callable> { @Override public List call() throws Exception { Map filesToDownload = getDownloadUrls(moduleList); - logger.atInfo().addArgument(() -> filesToDownload.size()).log("Started downloading {} modules"); + logger.info("Started downloading {} modules", filesToDownload.size()); //NOPMD MultiFileDownloader downloader = new MultiFileDownloader(filesToDownload, downloadProgressListener); List downloadedModulesPaths = downloader.call(); logger.info("Module download completed, loading the new modules..."); diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java b/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java index d211194c8d0..08fd8fc866e 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/common/ConfigurationSubsystem.java @@ -66,7 +66,7 @@ public void preInitialise(Context rootContext) { checkServerIdentity(); // TODO: Move to display subsystem - logger.atInfo().addArgument(() -> config.renderConfigAsJson(config.getRendering())).log("Video Settings: {}"); + logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); //NOPMD rootContext.put(Config.class, config); //add facades diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java index b4b7647485b..d64cb9be2f3 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/event/internal/EventSystemImpl.java @@ -83,7 +83,7 @@ public void process() { @Override public void registerEvent(ResourceUrn uri, Class eventType) { eventIdMap.put(uri, eventType); - logger.atDebug().addArgument(() -> eventType.getSimpleName()).log("Registering event {}"); + logger.debug("Registering event {}", eventType.getSimpleName()); //NOPMD for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) { if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) { childEvents.put(parent, eventType); @@ -95,11 +95,11 @@ public void registerEvent(ResourceUrn uri, Class eventType) { public void registerEventHandler(ComponentSystem handler) { Class handlerClass = handler.getClass(); if (!Modifier.isPublic(handlerClass.getModifiers())) { - logger.atError().addArgument(() -> handlerClass.getName()).log("Cannot register handler {}, must be public"); + logger.error("Cannot register handler {}, must be public", handlerClass.getName()); //NOPMD return; } - logger.atDebug().addArgument(() -> handlerClass.getName()).log("Registering event handler {}"); + logger.debug("Registering event handler {}", handlerClass.getName()); //NOPMD for (Method method : handlerClass.getMethods()) { ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class); if (receiveEventAnnotation != null) { @@ -129,7 +129,7 @@ public void registerEventHandler(ComponentSystem handler) { logger.debug("Found method: {}", method); if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) { - logger.atError().addArgument(() -> method.getName()).log("Invalid event handler method: {}"); + logger.error("Invalid event handler method: {}", method.getName()); //NOPMD return; } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java index 4a6397c1896..91a0f8e83a8 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventLibrary.java @@ -30,8 +30,7 @@ public EventLibrary(ModuleEnvironment environment, ReflectFactory reflectFactory try { return new EventMetadata<>(type, copyStrategies, factory, uri); } catch (NoSuchMethodException e) { - logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). - log("Unable to register class {}: Default Constructor Required"); + logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); //NOPMD return null; } } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java index 14f32cf21eb..0eb71a8ae1c 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/EventMetadata.java @@ -38,8 +38,7 @@ public EventMetadata(Class simpleClass, CopyStrategyLibrary copyStrategies, R skipInstigator = simpleClass.getAnnotation(BroadcastEvent.class).skipInstigator(); } if (networkEventType != NetworkEventType.NONE && !isConstructable() && !Modifier.isAbstract(simpleClass.getModifiers())) { - logger.atError().addArgument(() -> this). - log("Event '{}' is a network event but lacks a default constructor - will not be replicated"); + logger.error("Event '{}' is a network event but lacks a default constructor - will not be replicated", this); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java index 9f9e13d44b8..62aa7df2904 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/actions/conditions/ConditionAction.java @@ -98,7 +98,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi secondValue = ""; break; default: - logger.atError().addArgument(() -> tokens[0]).log("Unsupported guard value type: {}"); + logger.error("Unsupported guard value type: {}", tokens[0]); //NOPMD secondValue = ""; } @@ -115,7 +115,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = (Boolean) fieldValue != Boolean.parseBoolean(secondValue); break; default: - logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for boolean values: {}"); + logger.error("Unsupported operation for boolean values: {}", tokens[2]); //NOPMD } @@ -142,7 +142,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = ((Number) fieldValue).doubleValue() < Double.parseDouble(secondValue); break; default: - logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for numeric values: {}"); + logger.error("Unsupported operation for numeric values: {}", tokens[2]); //NOPMD } @@ -157,7 +157,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi passing = !fieldValue.equals(secondValue); break; default: - logger.atError().addArgument(() -> tokens[2]).log("Unsupported operation for strings: {}"); + logger.error("Unsupported operation for strings: {}", tokens[2]); //NOPMD } } else { @@ -190,8 +190,7 @@ protected boolean condition(Actor actor) throws ClassNotFoundException, NoSuchFi break; default: - logger.atError().addArgument(() -> fieldValue.getClass()).addArgument(() -> tokens[2]). - log("Unknown field type or operation: {} {}"); + logger.error("Unknown field type or operation: {} {}", fieldValue.getClass(), tokens[2]); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java index 65df48d3c42..a9a0301760b 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/ActionNode.java @@ -56,8 +56,7 @@ public void construct(Actor actor) { try { action.construct(actor); } catch (Exception e) { - logger.atDebug().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e). - log("Exception while running construct() of action {} from entity {}: "); + logger.debug("Exception while running construct() of action {} from entity {}: ", action, actor.getEntity(), e); //NOPMD } } } @@ -68,8 +67,7 @@ public BehaviorState execute(Actor actor) { try { return action.modify(actor, BehaviorState.UNDEFINED); } catch (Exception e) { - logger.atDebug().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e). - log("Exception while running action {} from entity {}: "); + logger.debug("Exception while running action {} from entity {}: ", action, actor.getEntity(), e); //NOPMD // TODO maybe returning UNDEFINED would be more fitting? return BehaviorState.FAILURE; } diff --git a/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java b/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java index 29cc0c133e5..39c51b200c3 100644 --- a/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java +++ b/engine/src/main/java/org/terasology/engine/logic/behavior/core/DecoratorNode.java @@ -48,8 +48,7 @@ public void construct(Actor actor) { try { action.construct(actor); } catch (Exception e) { - logger.atInfo().addArgument(() -> action).addArgument(() -> actor.getEntity()). - log("Exception while running construct() of action {} from entity {}:"); + logger.info("Exception while running construct() of action {} from entity {}:", action, actor.getEntity()); //NOPMD } } } @@ -81,8 +80,7 @@ public BehaviorState execute(Actor actor) { try { modifiedState = action.modify(actor, lastState); } catch (Exception e) { - logger.atInfo().addArgument(() -> action).addArgument(() -> actor.getEntity()).addArgument(() -> e.getStackTrace()). - log("Exception while running action {} from entity {}: {}"); + logger.info("Exception while running action {} from entity {}: {}", action, actor.getEntity(), e.getStackTrace()); //NOPMD // TODO maybe returning UNDEFINED would be more canonical? return BehaviorState.FAILURE; } diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java index 7429cd75040..0cee78267c6 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSoundSystem.java @@ -60,7 +60,7 @@ public void onFootstep(FootstepEvent event, EntityRef entity, LocationComponent Block block = worldProvider.getBlock(blockPos); if (block != null) { if (block.getSounds() == null) { - logger.atError().addArgument(() -> block.getURI()).log("Block '{}' has no sounds"); + logger.error("Block '{}' has no sounds", block.getURI()); //NOPMD } else if (!block.getSounds().getStepSounds().isEmpty()) { footstepSounds = block.getSounds().getStepSounds(); } diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java index 678f050baf8..640390f9849 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/ClientCharacterPredictionSystem.java @@ -84,8 +84,7 @@ public void onDestroy(final BeforeDeactivateComponent event, final EntityRef ent @ReceiveEvent(components = {CharacterMovementComponent.class, LocationComponent.class, AliveCharacterComponent.class}) public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity) { if (entity.equals(localPlayer.getCharacterEntity())) { - logger.atTrace().addArgument(() -> state.getSequenceNumber()).addArgument(() -> inputs.size()). - log("Received new state, sequence number: {}, buffered input size {}"); + logger.trace("Received new state, sequence number: {}, buffered input size {}", state.getSequenceNumber(), inputs.size()); //NOPMD playerStates.remove(entity); authoritiveState = state; @@ -99,7 +98,7 @@ public void onCharacterStateReceived(CharacterStateEvent state, EntityRef entity newState = stepState(input, newState, entity); } } - logger.atTrace().addArgument(() -> inputs.size()).log("Resultant input size {}"); + logger.trace("Resultant input size {}", inputs.size()); //NOPMD characterMovementSystemUtility.setToState(entity, newState); // TODO: soft correct predicted state predictedState = newState; diff --git a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java index d613363f3fa..04b66b74479 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java @@ -139,7 +139,7 @@ public void addMessage(String message, MessageType type, boolean newLine) { @Override public void addMessage(Message message) { String uncoloredText = FontUnderline.strip(FontColor.stripColor(message.getMessage())); - logger.atInfo().addArgument(() -> message.getType()).addArgument(() -> uncoloredText).log("[{}] {}"); + logger.info("[{}] {}", message.getType(), uncoloredText); //NOPMD messageHistory.add(message); for (ConsoleSubscriber subscriber : messageSubscribers) { subscriber.onNewConsoleMessage(message); diff --git a/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java b/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java index 78617b27008..41945385d18 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/commands/ServerCommands.java @@ -68,7 +68,7 @@ public String shutdownServer(@Sender EntityRef sender) { EntityRef clientInfo = sender.getComponent(ClientComponent.class).clientInfo; DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class); - logger.atInfo().addArgument(() -> name.name).log("Shutdown triggered by {}"); + logger.info("Shutdown triggered by {}", name.name); //NOPMD gameEngine.shutdown(); @@ -165,7 +165,7 @@ private String kick(EntityRef clientEntity) { EntityRef clientInfo = clientEntity.getComponent(ClientComponent.class).clientInfo; DisplayNameComponent name = clientInfo.getComponent(DisplayNameComponent.class); - logger.atInfo().addArgument(() -> name.name).log("Kicking user {}"); + logger.info("Kicking user {}", name.name); //NOPMD networkSystem.forceDisconnect(client); return "User kick triggered for '" + name.name + "'"; diff --git a/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java b/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java index a611ec1d200..50e1e633693 100644 --- a/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java +++ b/engine/src/main/java/org/terasology/engine/logic/debug/ChunkEventErrorLogger.java @@ -25,14 +25,14 @@ public class ChunkEventErrorLogger extends BaseComponentSystem { @ReceiveEvent(components = WorldComponent.class) public void onNewChunk(OnChunkLoaded chunkAvailable, EntityRef worldEntity) { if (!loadedChunks.add(chunkAvailable.getChunkPos())) { - logger.atError().addArgument(() -> chunkAvailable.getChunkPos()).log("Multiple loads of chunk {}"); + logger.error("Multiple loads of chunk {}", chunkAvailable.getChunkPos()); //NOPMD } } @ReceiveEvent(components = WorldComponent.class) public void onRemoveChunk(BeforeChunkUnload chunkUnload, EntityRef worldEntity) { if (!loadedChunks.remove(chunkUnload.getChunkPos())) { - logger.atError().addArgument(() -> chunkUnload.getChunkPos()).log("Unload event for not loaded chunk {}"); + logger.error("Unload event for not loaded chunk {}", chunkUnload.getChunkPos()); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java b/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java index b61a26f07b3..27c02d19ead 100644 --- a/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/inventory/ItemPickupAuthoritySystem.java @@ -82,7 +82,7 @@ public void updateExtentsOnBlockItemBoxShape(OnAddedComponent event, EntityRef i BlockFamily blockFamily = blockItemComponent.blockFamily; if (blockFamily == null) { - LOGGER.atWarn().addArgument(() -> itemEntity.getParentPrefab().getName()).log("Prefab {} does not have a block family"); + LOGGER.warn("Prefab {} does not have a block family", itemEntity.getParentPrefab().getName()); //NOPMD return; } diff --git a/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java b/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java index 627ce16a9bd..9515194137d 100644 --- a/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/players/PlayerSystem.java @@ -155,7 +155,7 @@ public void onConnect(ConnectedEvent connected, EntityRef entity) { private void restoreCharacter(EntityRef entity, EntityRef character) { Client clientListener = networkSystem.getOwner(entity); - LOGGER.atInfo().addArgument(() -> clientListener.toString()).log("{}"); + LOGGER.info("{}", clientListener); updateRelevanceEntity(entity, clientListener.getViewDistance().getChunkDistance()); ClientComponent client = entity.getComponent(ClientComponent.class); diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java index 84fadef009b..4eee38115d5 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java @@ -827,7 +827,7 @@ private void processRemovedClient(Client client) { } clientList.remove(client); clientPlayerLookup.remove(client.getEntity()); - logger.atInfo().addArgument(() -> client.getName()).log("Client disconnected: {}"); + logger.info("Client disconnected: {}", client.getName()); //NOPMD storageManager.deactivatePlayer(client); client.getEntity().send(new DisconnectedEvent()); client.disconnect(); @@ -856,7 +856,7 @@ private void processNewClient(NetClient client) { connectClient(client); // log after connect so that the name has been set: - logger.atInfo().addArgument(() -> client.getEntity()).log("New client entity: {}"); + logger.info("New client entity: {}", client.getEntity()); //NOPMD for (EntityRef netEntity : entityManager.getEntitiesWith(NetworkComponent.class)) { NetworkComponent netComp = netEntity.getComponent(NetworkComponent.class); if (netComp.getNetworkId() != NULL_NET_ID) { @@ -973,8 +973,7 @@ private Map, Integer> generateIds(ClassLibrary classLi int fieldId = 0; for (FieldMetadata field : metadata.getFields()) { if (fieldId >= 256) { - logger.atError().addArgument(() -> metadata.getId()). - log("Class {} has too many fields (>255), serialization will be incomplete"); + logger.error("Class {} has too many fields (>255), serialization will be incomplete", metadata.getId()); //NOPMD break; } field.setId((byte) fieldId); diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java index a56a21ccb05..6ae75e4a1b9 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java @@ -349,7 +349,7 @@ private void processBlockRegistrations(NetData.NetMessage message) { } blockManager.receiveFamilyRegistration(family, registrationMap); } catch (BlockUriParseException e) { - logger.atError().addArgument(() -> blockFamily.getBlockUri(0)).log("Received invalid block uri {}"); + logger.error("Received invalid block uri {}", blockFamily.getBlockUri(0)); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java index dd5f1a3cadf..b5a1fd25845 100644 --- a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java +++ b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java @@ -125,8 +125,7 @@ public void initialize() { for (Class type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) { if (!ParticleSystemFunction.class.isAssignableFrom(type)) { - logger.atError().addArgument(() -> type.getSimpleName()). - log("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction"); + logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", type.getSimpleName()); //NOPMD } else { try { ParticleSystemFunction function = (ParticleSystemFunction) type.newInstance(); diff --git a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java index b7c58fba2a6..911bd471427 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java +++ b/engine/src/main/java/org/terasology/engine/persistence/internal/GlobalStoreLoader.java @@ -93,7 +93,7 @@ private Prefab loadPrefab(EntityData.Prefab prefabData, Map prefabData.getParentName()).addArgument(e).log("Failed to load prefab {}"); + logger.error("Failed to load prefab {}", prefabData.getParentName(), e); //NOPMD return null; } } diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java index 98d7f15d526..a2913b8b503 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/EventSerializer.java @@ -154,7 +154,7 @@ public Class getEventClass(EntityData.Event eventData) { } } if (metadata == null) { - logger.atWarn().addArgument(() -> eventData.getType()).log("Unable to deserialize unknown event with id: {}"); + logger.warn("Unable to deserialize unknown event with id: {}", eventData.getType()); //NOPMD return null; } return metadata.getType(); diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java index 1bb95f1b201..7c6028ac403 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/PrefabSerializer.java @@ -155,8 +155,7 @@ private void applyComponentChanges(Module context, EntityData.Prefab prefabData, } } } else if (componentData.hasType()) { - logger.atWarn().addArgument(() -> prefabData.getName()).addArgument(() -> componentData.getType()). - log("Prefab '{}' contains unknown component '{}'"); + logger.warn("Prefab '{}' contains unknown component '{}'", prefabData.getName(), componentData.getType()); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java index 514efd4cd19..d39a46fbc53 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/WorldSerializerImpl.java @@ -157,7 +157,7 @@ private void createPrefab(EntityData.Prefab prefabData) { PrefabData protoPrefab = prefabSerializer.deserialize(prefabData); Assets.generateAsset(new ResourceUrn(prefabData.getName()), protoPrefab, Prefab.class); } catch (Exception e) { - logger.atError().addArgument(() -> prefabData.getName()).log("Failed to create prefab {}"); + logger.error("Failed to create prefab {}", prefabData.getName()); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java index cc2ba46f464..2b117ba1bae 100644 --- a/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java +++ b/engine/src/main/java/org/terasology/engine/physics/bullet/BulletPhysics.java @@ -241,8 +241,7 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Col hitNormalWorld, voxelPosition); } else { //we hit something we don't understand, assume its nothing and log a warning - logger.atWarn().addArgument(() -> collisionObject.userData). - log("Unidentified object was hit in the physics engine: {}"); + logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); //NOPMD } } @@ -306,8 +305,7 @@ public HitResult rayTrace(Vector3f from, Vector3f direction, float distance, Set hitNormalWorld, voxelPosition); } else { //we hit something we don't understand, assume its nothing and log a warning - logger.atWarn().addArgument(() -> collisionObject.userData). - log("Unidentified object was hit in the physics engine: {}"); + logger.warn("Unidentified object was hit in the physics engine: {}", collisionObject.userData); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java index b502e278468..7cb4f798495 100644 --- a/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java +++ b/engine/src/main/java/org/terasology/engine/recording/EventSystemReplayImpl.java @@ -276,7 +276,7 @@ private EntityRef getEntityRef(RecordedEvent recordedEvent) { @Override public void registerEvent(ResourceUrn uri, Class eventType) { eventIdMap.put(uri, eventType); - logger.atDebug().addArgument(() -> eventType.getSimpleName()).log("Registering event {}"); + logger.debug("Registering event {}", eventType.getSimpleName()); //NOPMD for (Class parent : ReflectionUtils.getAllSuperTypes(eventType, Predicates.subtypeOf(Event.class))) { if (!AbstractConsumableEvent.class.equals(parent) && !Event.class.equals(parent)) { childEvents.put(parent, eventType); @@ -303,11 +303,11 @@ private boolean shouldAddToLibrary(Class eventType) { public void registerEventHandler(ComponentSystem handler) { Class handlerClass = handler.getClass(); if (!Modifier.isPublic(handlerClass.getModifiers())) { - logger.atError().addArgument(() -> handlerClass.getName()).log("Cannot register handler {}, must be public"); + logger.error("Cannot register handler {}, must be public", handlerClass.getName()); //NOPMD return; } - logger.atDebug().addArgument(() -> handlerClass.getName()).log("Registering event handler {}"); + logger.debug("Registering event handler {}", handlerClass.getName()); //NOPMD for (Method method : handlerClass.getMethods()) { ReceiveEvent receiveEventAnnotation = method.getAnnotation(ReceiveEvent.class); if (receiveEventAnnotation != null) { @@ -336,7 +336,7 @@ public void registerEventHandler(ComponentSystem handler) { logger.debug("Found method: {}", method); if (!Event.class.isAssignableFrom(types[0]) || !EntityRef.class.isAssignableFrom(types[1])) { - logger.atError().addArgument(() -> method.getName()).log("Invalid event handler method: {}"); + logger.error("Invalid event handler method: {}", method.getName()); //NOPMD return; } @@ -344,8 +344,7 @@ public void registerEventHandler(ComponentSystem handler) { List> componentParams = Lists.newArrayList(); for (int i = 2; i < types.length; ++i) { if (!Component.class.isAssignableFrom(types[i])) { - logger.atError().addArgument(() -> method.getName()).addArgument(types[i]). - log("Invalid event handler method: {} - {} is not a component class"); + logger.error("Invalid event handler method: {} - {} is not a component class", method.getName(), types[i]); //NOPMD return; } requiredComponents.add((Class) types[i]); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java index 3a3265dfce3..64b8adcdab0 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java @@ -474,7 +474,7 @@ public List getOutputConnectionsList() { } public void disconnectInputFbo(int inputId) { - logger.atInfo().addArgument(() -> this.getUri()).addArgument(inputId).log("Disconnecting {} input Fbo number {}"); + logger.info("Disconnecting {} input Fbo number {}", this.getUri(), inputId); //NOPMD DependencyConnection connectionToDisconnect = this.inputConnections.get(FboConnection.getConnectionName(inputId, this.nodeUri)); if (connectionToDisconnect != null) { // TODO make it reconnectInputFboToOutput @@ -549,8 +549,8 @@ public void dispose() { */ protected void addDesiredStateChange(StateChange stateChange) { if (stateChange.isTheDefaultInstance()) { - logger.atError().addArgument(() -> stateChange.getClass().getSimpleName()).addArgument(this). - log("Attempted to add default state change {} to the set of desired state changes. (Node: {})"); + logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})", + stateChange.getClass().getSimpleName(), this); //NOPMD } desiredStateChanges.add(stateChange); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java index 9e1e37951e4..b80d2a58eaa 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java @@ -52,8 +52,8 @@ public void addNode(Node node) { } if (akaNodeMap.containsKey(nodeAka)) { Node aNode = akaNodeMap.get(nodeAka); - logger.atInfo().addArgument(nodeUri).addArgument(nodeAka).addArgument(() -> aNode.getUri()). - log("Node {} also known as {} already matches existing node with uri {} - attempting replacing..."); + logger.info("Node {} also known as {} already matches existing node with uri {} - attempting replacing...", + nodeUri, nodeAka, aNode.getUri()); //NOPMD replaceNode(aNode, node); } else { nodeMap.put(nodeUri, node); @@ -149,8 +149,7 @@ private void connect(Node... nodeList) { if (!graph.hasEdgeConnecting(fromNode, toNode)) { graph.putEdge(fromNode, toNode); } else { - logger.atWarn().addArgument(fromNode.getUri()).addArgument(toNode.getUri()). - log("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri()); + logger.warn("Trying to connect two already connected nodes, {} and {}", fromNode.getUri(), toNode.getUri()); //NOPMD } } @@ -170,8 +169,7 @@ public void disconnect(Node fromNode, Node toNode) { Preconditions.checkNotNull(toNode, "toNode cannot be null!"); if (!graph.hasEdgeConnecting(fromNode, toNode)) { - logger.atWarn().addArgument(() -> fromNode.getUri()).addArgument(() -> toNode.getUri()). - log("Trying to disconnect two nodes that aren't connected, {} and {}"); + logger.warn("Trying to disconnect two nodes that aren't connected, {} and {}", fromNode.getUri(), toNode.getUri()); //NOPMD } graph.removeEdge(fromNode, toNode); @@ -277,8 +275,8 @@ private void connectFbo(Node toNode, int inputFboId, DependencyConnection fromCo } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.atInfo().addArgument(() -> toNode.getUri()).addArgument(inputFboId).addArgument(() -> fromConnection.getName()). - log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections.."); + logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", + toNode.getUri(), inputFboId, fromConnection.getName()); //NOPMD DependencyConnection localConnection = toNode.getInputFboConnection(inputFboId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -342,8 +340,8 @@ private void connectBufferPair(Node toNode, int inputConnectionId, DependencyCon } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.atInfo().addArgument(() -> toNode.getUri()).addArgument(inputConnectionId).addArgument(() -> fromConnection.getName()). - log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections.."); + logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", + toNode.getUri(), inputConnectionId, fromConnection.getName()); //NOPMD DependencyConnection localConnection = toNode.getInputBufferPairConnection(inputConnectionId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -533,14 +531,13 @@ public void reconnectInputToOutput(String fromNodeUri, int outputId, Node toNode */ private void reconnectInputToOutput(Node toNode, int inputId, DependencyConnection fromConnection, ConnectionType connectionType, boolean disconnectPrevious) { - logger.atDebug().addArgument(() -> toNode.getUri()).addArgument(() -> fromConnection.getParentNode()). - log("Attempting reconnection of {} to {}'s output."); + logger.debug("Attempting reconnection of {} to {}'s output.", toNode.getUri(), fromConnection.getParentNode()); //NOPMD Node fromNode; fromNode = findNode(fromConnection.getParentNode()); if (!fromConnection.getConnectedConnections().isEmpty()) { - logger.atWarn().addArgument(fromConnection).addArgument(() -> fromConnection.getConnectedConnections()). - log("WARNING: destination connection ({}) is already connected to ({})"); + logger.warn("WARNING: destination connection ({}) is already connected to ({})", + fromConnection, fromConnection.getConnectedConnections()); //NOPMD // TODO update the hashmap to string to be pretty // throw new RuntimeException("Could not reconnect, destination connection (" + fromConnection + ") is already connected to (" // + fromConnection.getConnectedConnections() + "). Remove connection first."); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java index d00ad950fde..a3f99a95a74 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java @@ -42,21 +42,22 @@ public RenderTaskListGenerator() { taskList = Lists.newArrayList(); } + @SuppressWarnings("PMD.GuardLogStatement") private void logIntermediateRendererListForDebugging(List orderedNodes) { for (Node node : orderedNodes) { if (node.isEnabled()) { // printing out node name - logger.atInfo().addArgument(() -> node.getClass().getSimpleName()).log("----- {}"); + logger.info("----- {}", node.getClass().getSimpleName()); // printing out individual desired state changes for (StateChange desiredStateChange : node.getDesiredStateChanges()) { - logger.atInfo().addArgument(desiredStateChange).log("{}"); + logger.info("{}", desiredStateChange); } // printing out process() statement - logger.atInfo().addArgument(node).log("{}: process()"); + logger.info("{}: process()", node); } } } @@ -166,22 +167,17 @@ public List generateFrom(List orderedNodes) { long endTimeInNanoSeconds = System.nanoTime(); - // if (logger.isDebugEnabled()) { - logger.atDebug().log("===== INTERMEDIATE RENDERER LIST ========================="); + if (logger.isDebugEnabled()) { + logger.debug("===== INTERMEDIATE RENDERER LIST ========================="); logIntermediateRendererListForDebugging(orderedNodes); - logger.atDebug().log("===== RENDERER TASK LIST ================================="); + logger.debug("===== RENDERER TASK LIST ================================="); logList(taskList); - logger.atDebug().log("----------------------------------------------------------"); - logger.atDebug().addArgument(() -> String.format("%.3f", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f)). - log("Task list generated in {} ms"); - logger.atDebug(). - addArgument(() -> nodeList.size()). - addArgument(enabledNodes). - addArgument(taskList.size() - enabledNodes). - addArgument(potentialTasks). - log("{} nodes, {} enabled - {} tasks (excluding marker tasks) out of {} potential tasks."); - logger.atDebug().log("----------------------------------------------------------"); - // } + logger.debug("----------------------------------------------------------"); + logger.debug(String.format("Task list generated in %.3f ms", (endTimeInNanoSeconds - startTimeInNanoSeconds) / 1000000f)); + logger.debug(String.format("%s nodes, %s enabled - %s tasks (excluding marker tasks) out of %s potential tasks.", + nodeList.size(), enabledNodes, taskList.size() - enabledNodes, potentialTasks)); + logger.debug("----------------------------------------------------------"); + } return taskList; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java b/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java index c8abc1a308f..22f04f084f8 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/logic/FloatingTextRenderer.java @@ -77,7 +77,7 @@ private void render(Iterable floatingTextEntities) { LocationComponent location = entity.getComponent(LocationComponent.class); if (location == null) { - logger.atWarn().addArgument(() -> floatingText.text).log("location component is not defined can't render text: {}"); + logger.warn("location component is not defined can't render text: {}", floatingText.text); //NOPMD continue; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java b/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java index 845edd2c6ff..0c2eac17b21 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java +++ b/engine/src/main/java/org/terasology/engine/rendering/logic/SkeletonRenderer.java @@ -307,7 +307,7 @@ public void renderOpaque() { boneTransform.mul(bone.getInverseBindMatrix()); boneTransforms[bone.getIndex()] = boneTransform.transpose(); } else { - logger.atWarn().addArgument(() -> bone.getName()).log("Unable to resolve bone \"{}\""); + logger.warn("Unable to resolve bone \"{}\"", bone.getName()); //NOPMD boneTransforms[bone.getIndex()] = new Matrix4f(); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java index 37b30f544ce..fc74d07caf3 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIFormat.java @@ -175,7 +175,7 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC if (id != null) { FieldMetadata fieldMetadata = elementMetadata.getField(ID_FIELD); if (fieldMetadata == null) { - logger.atWarn().addArgument(() -> elementMetadata.getId()).log("UIWidget type {} lacks id field"); + logger.warn("UIWidget type {} lacks id field", elementMetadata.getId()); //NOPMD } else { fieldMetadata.setValue(element, id); } @@ -218,8 +218,7 @@ public UIWidget deserialize(JsonElement json, Type typeOfT, JsonDeserializationC field.setValue(element, context.deserialize(jsonObject.get(field.getSerializationName()), field.getType())); } } catch (RuntimeException e) { - logger.atError().addArgument(() -> field.getName()).addArgument(type).addArgument(e). - log("Failed to deserialize field {} of {}"); + logger.error("Failed to deserialize field {} of {}", field.getName(), type, e); //NOPMD } } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java index 016b40dec37..e13f2a6d7b1 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/editor/utils/NUIEditorMenuTreeBuilder.java @@ -259,7 +259,7 @@ private void populateContextMenu(JsonTree node, MenuTree addTree, boolean isSkin } } } else { - logger.atWarn().addArgument(() -> node.getValue()).log("Could not get class for node {}"); + logger.warn("Could not get class for node {}", node.getValue()); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java index af2ee4ce3e9..579e1f90b35 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/internal/NUIManagerInternal.java @@ -365,8 +365,7 @@ public T createScreen(ResourceUrn screenUri, Class root.getClass()).addArgument(expectedType). - log("Screen '{}' is a '{}' and not a '{}'"); + logger.error("Screen '{}' is a '{}' and not a '{}'", screenUri, root.getClass(), expectedType); //NOPMD } } return null; @@ -491,8 +490,7 @@ public T addOverlay(ResourceUrn overlayUri, Class e addOverlay(overlay, overlayUri); return overlay; } else { - logger.atError().addArgument(overlayUri).addArgument(() -> root.getClass()).addArgument(expectedType). - log("Screen '{}' is a '{}' and not a '{}'"); + logger.error("Screen '{}' is a '{}' and not a '{}'", overlayUri, root.getClass(), expectedType); //NOPMD } } return null; diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java index 47f6a08632a..ff7ed98ca8a 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/videoSettings/VideoSettingsScreen.java @@ -355,7 +355,7 @@ public boolean onKeyEvent(NUIKeyEvent event) { } public void saveSettings() { - logger.atInfo().addArgument(() -> config.renderConfigAsJson(config.getRendering())).log("Video Settings: {}"); + logger.info("Video Settings: {}", config.renderConfigAsJson(config.getRendering())); //NOPMD // TODO: add a dirty flag that checks if recompiling is needed CoreRegistry.get(ShaderManager.class).recompileAllShaders(); triggerBackAnimation(); diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java index 8a32043ca2b..340dc90b7c6 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/UIButtonWebBrowser.java @@ -68,7 +68,7 @@ public class UIButtonWebBrowser extends UIButton { try { desktop.browse(new URI(this.url)); } catch (IOException | URISyntaxException e) { - logger.atWarn().addArgument(() -> this.url).log("Can't open {} in default browser of your system."); + logger.warn("Can't open {} in default browser of your system.", this.url); //NOPMD showErrorPopup("Can't open " + this.url + " in default browser of your system."); } } else { @@ -83,7 +83,7 @@ public class UIButtonWebBrowser extends UIButton { runtime.exec(createCommand("xdg-open", this.url)); } } catch (IOException e) { - logger.atWarn().addArgument(() -> this.url).log("Can't recognize your OS and open the url {}."); + logger.warn("Can't recognize your OS and open the url {}.", this.url); //NOPMD showErrorPopup("Can't recognize your OS and open the url " + this.url); } } @@ -125,7 +125,7 @@ private void showConfirmationPopup() { confirmUrlPopup.setCheckbox(webBrowserConfig, this.url); } } catch (MalformedURLException e) { - logger.atError().addArgument(() -> this.url).addArgument(e).log("{} is malformed"); + logger.error("{} is malformed", this.url, e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java index 090cf99d3ed..ab45466732d 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLMaterial.java @@ -156,7 +156,7 @@ public final void doReload(MaterialData data) { rebindVariables(data); }); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } @@ -228,8 +228,7 @@ public void activateFeature(ShaderProgramFeature feature) { activeFeaturesMask = ShaderProgramFeature.getBitset(activeFeatures); activeFeaturesChanged = true; } else { - logger.atError().addArgument(feature).addArgument(() -> getUrn()).addArgument(() -> shader.getUrn()). - log("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn()); + logger.error("Attempt to activate unsupported feature {} for material {} using shader {}", feature, getUrn(), shader.getUrn()); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java index 749fb9e072e..6f0ffe48ab6 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/GLSLShader.java @@ -278,8 +278,7 @@ private void registerAllShaderPermutations() { disposalAction.vertexPrograms.put(featureHash, vertShaderId); } - logger.atDebug().addArgument(() -> allPermutations.size()).addArgument(() -> getUrn()). - log("Compiled {} permutations for {}."); + logger.debug("Compiled {} permutations for {}.", allPermutations.size(), getUrn()); //NOPMD } private String assembleShader(int type, Set features) { @@ -365,7 +364,7 @@ private int compileShader(int type, Set features) { protected void doReload(ShaderData data) { try { GameThread.synch(() -> { - logger.atDebug().addArgument(() -> getUrn()).log("Recompiling shader {}."); + logger.debug("Recompiling shader {}.", getUrn()); //NOPMD disposalAction.disposeData(); shaderProgramBase = data; @@ -377,11 +376,11 @@ protected void doReload(ShaderData data) { try { registerAllShaderPermutations(); } catch (RuntimeException e) { - logger.atWarn().addArgument(() -> e.getMessage()).log("{}"); + logger.warn("{}", e.getMessage()); //NOPMD } }); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java index 833a1bc589f..303d6712d1d 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLMesh.java @@ -54,7 +54,7 @@ protected void doReload(MeshData newData) { try { GameThread.synch(() -> buildMesh(newData)); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } @@ -86,7 +86,7 @@ public void render() { } GL30.glBindVertexArray(0); } else { - logger.atError().addArgument(() -> getUrn()).log("Attempted to render disposed mesh: {}"); + logger.error("Attempted to render disposed mesh: {}", getUrn()); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java index 2e53f93539c..a50cd945214 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLSkeletalMesh.java @@ -112,7 +112,7 @@ protected void doReload(SkeletalMeshData newData) { GL30.glBindVertexArray(0); }); } catch (InterruptedException e) { - logger.atError().addArgument(() -> getUrn()).addArgument(e).log("Failed to reload {}"); + logger.error("Failed to reload {}", getUrn(), e); //NOPMD } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java index 049304ee9be..e74ccafd27c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java @@ -82,8 +82,7 @@ protected void doReload(TextureData data) { resources.graphicsManager.disposeTexture(newId); } else { resources.id = newId; - logger.atDebug().addArgument(() -> getUrn()).addArgument(resources.id). - log("Bound texture '{}' - {}"); + logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); //NOPMD } } }); diff --git a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java index 5b41d908a35..5e16b2f0c7b 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java +++ b/engine/src/main/java/org/terasology/engine/utilities/concurrency/TaskProcessor.java @@ -42,7 +42,7 @@ public void run() { logger.error("Thread interrupted", e); } catch (RuntimeException e) { ThreadMonitor.addError(e); - logger.atError().addArgument(Thread.currentThread().getName()).addArgument(e).log("Error in thread {}"); + logger.error("Error in thread {}", Thread.currentThread().getName(), e); //NOPMD } catch (Error e) { GameThread.asynch(() -> { throw e; // re-throw on game thread to terminate the entire application diff --git a/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java b/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java index 8f55f529166..c088902376d 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java +++ b/engine/src/main/java/org/terasology/engine/world/block/family/BlockFamilyLibrary.java @@ -37,7 +37,7 @@ public BlockFamilyLibrary(ModuleEnvironment moduleEnvironment, Context context) for (Class entry : moduleEnvironment.getTypesAnnotatedWith(RegisterBlockFamily.class)) { if (!BlockFamily.class.isAssignableFrom(entry)) { - logger.atError().addArgument(() -> entry.getSimpleName()).log("Cannot load {}, must be a subclass of BlockFamily"); + logger.error("Cannot load {}, must be a subclass of BlockFamily", entry.getSimpleName()); //NOPMD continue; } RegisterBlockFamily registerInfo = entry.getAnnotation(RegisterBlockFamily.class); @@ -96,7 +96,7 @@ public Optional get(Class type) { return result; } catch (Exception e) { - logger.atError().addArgument(blockFamily).addArgument(e).log("Failed to load blockFamily {}"); + logger.error("Failed to load blockFamily {}", blockFamily, e); //NOPMD } return null; } diff --git a/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java b/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java index 46832c13fc2..b5a768dfb96 100644 --- a/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java +++ b/engine/src/main/java/org/terasology/engine/world/block/internal/BlockManagerImpl.java @@ -95,8 +95,7 @@ public void initialise(List registeredBlockFamilies, if (id != null) { block.setId(id); } else { - logger.atError().addArgument(() -> block.getURI()).addArgument(() -> family.get().getURI()). - log("Missing id for block {} in provided family {}"); + logger.error("Missing id for block {} in provided family {}", block.getURI(), family.get().getURI()); //NOPMD if (generateNewIds) { block.setId(getNextId()); } else { @@ -157,8 +156,7 @@ public void receiveFamilyRegistration(BlockUri familyUri, Map r if (id != null) { block.setId((short) id.intValue()); } else { - logger.atError().addArgument(() -> block.getURI()).addArgument(() -> familyUri). - log("Missing id for block {} in registered family {}"); + logger.error("Missing id for block {} in registered family {}", block.getURI(), familyUri); //NOPMD block.setId(UNKNOWN_ID); } } @@ -191,7 +189,7 @@ protected void registerFamily(BlockFamily family) { private void registerBlock(Block block, RegisteredState newState) { if (block.getId() != UNKNOWN_ID) { - logger.atInfo().addArgument(() -> block).addArgument(() -> block.getId()).log("Registered Block {} with id {}"); + logger.info("Registered Block {} with id {}", block, block.getId()); //NOPMD newState.blocksById.put(block.getId(), block); newState.idByUri.put(block.getURI(), block.getId()); } else { diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java index 2e0f4becd0f..9c5f08e07fc 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java @@ -301,7 +301,7 @@ private boolean unloadChunkInternal(Vector3ic pos) { try { unloadRequestTaskMaster.put(new ChunkUnloadRequest(chunk, this)); } catch (InterruptedException e) { - logger.atError().addArgument(() -> chunk.getPosition()).addArgument(e).log("Failed to enqueue unload request for {}"); + logger.error("Failed to enqueue unload request for {}", chunk.getPosition(), e); //NOPMD } return true; @@ -311,7 +311,7 @@ void gatherBlockPositionsForDeactivate(Chunk chunk) { try { deactivateBlocksQueue.put(createBatchBlockEventMappings(chunk)); } catch (InterruptedException e) { - logger.atError().addArgument(() -> chunk.getPosition()).log("Failed to queue deactivation of blocks for {}"); + logger.error("Failed to queue deactivation of blocks for {}", chunk.getPosition()); //NOPMD } } From cf50c8e73dca09d97f37577aacde1f79b0c31ad4 Mon Sep 17 00:00:00 2001 From: soloturn Date: Sun, 7 Apr 2024 07:48:34 +0200 Subject: [PATCH 20/28] Update engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java Co-authored-by: jdrueckert --- .../org/terasology/engine/rendering/opengl/OpenGLTexture.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java index e74ccafd27c..05473461ca8 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java +++ b/engine/src/main/java/org/terasology/engine/rendering/opengl/OpenGLTexture.java @@ -104,7 +104,7 @@ protected void doReload(TextureData data) { resources.graphicsManager.disposeTexture(newId); } else { resources.id = newId; - logger.atDebug().addArgument(() -> getUrn()).addArgument(resources.id).log("Bound texture '{}' - {}"); + logger.debug("Bound texture '{}' - {}", getUrn(), resources.id); //NOPMD } } }); From f8b792ca02239ae4c433cd0486e5a56185738b43 Mon Sep 17 00:00:00 2001 From: soloturn Date: Mon, 13 May 2024 05:37:29 +0200 Subject: [PATCH 21/28] line length warning removed --- .../engine/particles/updating/ParticleUpdaterImpl.java | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java index b5a1fd25845..e66912d3ff8 100644 --- a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java +++ b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java @@ -125,7 +125,8 @@ public void initialize() { for (Class type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) { if (!ParticleSystemFunction.class.isAssignableFrom(type)) { - logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", type.getSimpleName()); //NOPMD + logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", + type.getSimpleName()); //NOPMD } else { try { ParticleSystemFunction function = (ParticleSystemFunction) type.newInstance(); From 12ae29acb78720ec04b60892238e58d9a6c2dff2 Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:19:55 +0200 Subject: [PATCH 22/28] refactor: use less verbose varient of fluent API --- .../engine/config/RenderingDebugConfig.java | 3 +-- .../constraints/NumberRangeConstraint.java | 13 ++++++------- .../engine/core/ComponentSystemManager.java | 2 +- .../org/terasology/engine/core/PathManager.java | 2 +- .../core/modes/loadProcesses/JoinServer.java | 3 +-- .../core/modes/loadProcesses/LoadEntities.java | 2 +- .../core/modes/loadProcesses/RegisterMods.java | 3 +-- .../core/subsystem/config/BindsSubsystem.java | 6 ++---- .../entitySystem/metadata/ComponentLibrary.java | 3 +-- .../StorageServiceWorker.java | 4 ++-- .../input/lwjgl/LwjglControllerDevice.java | 10 +++++----- .../console/commandSystem/MethodCommand.java | 4 ++-- .../engine/network/internal/NetClient.java | 3 +-- .../engine/network/internal/ServerImpl.java | 7 ++----- .../serializers/ComponentSerializer.java | 16 ++++++++-------- .../serializers/NetworkEntitySerializer.java | 11 ++++------- .../engine/registry/InjectionHelper.java | 6 ++---- .../engine/rendering/dag/RenderGraph.java | 6 ++---- .../rendering/nui/asset/UIDeltaFormat.java | 5 +---- .../engine/rendering/nui/skin/UISkinFormat.java | 3 +-- .../types/object/ObjectLayoutBuilder.java | 4 ++-- .../types/object/SubtypeLayoutBuilder.java | 3 +-- .../rendering/world/WorldRendererImpl.java | 7 +++---- .../org/terasology/engine/utilities/Jvm.java | 4 ++-- .../generation/FacetedWorldConfigurator.java | 2 +- 25 files changed, 54 insertions(+), 78 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java b/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java index b7050f3248c..8d1f90a0625 100644 --- a/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java +++ b/engine/src/main/java/org/terasology/engine/config/RenderingDebugConfig.java @@ -108,7 +108,6 @@ public void setRenderSkeletons(boolean renderSkeletons) { @Override public void propertyChange(PropertyChangeEvent evt) { - logger.atDebug().addArgument(() -> evt.getPropertyName().toUpperCase()).addArgument(evt.getNewValue()). - log("Set {} property to {}."); + logger.atDebug().log("Set {} property to {}.", evt.getPropertyName().toUpperCase(), evt.getNewValue()); } } diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java index 318e8916bbc..e8c0b2e73a9 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/constraints/NumberRangeConstraint.java @@ -96,13 +96,12 @@ public boolean isSatisfiedBy(T value) { * {@inheritDoc} */ @Override + @SuppressWarnings("PMD.GuardLogStatement") public void warnUnsatisfiedBy(T value) { - LOGGER.atWarn(). - addArgument(value). - addArgument(minInclusive ? "[" : "("). - addArgument(min != null ? min : "UNBOUNDED"). - addArgument(max != null ? max : "UNBOUNDED"). - addArgument(maxInclusive ? "]" : ")"). - log("Value {} is not in the range {}{}, {}{}"); + LOGGER.warn("Value {} is not in the range {}{}, {}{}", value, + minInclusive ? "[" : "(", + min != null ? min : "UNBOUNDED", + max != null ? max : "UNBOUNDED", + maxInclusive ? "]" : ")"); } } diff --git a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java index 4e4fbfbd6f7..c7faff9ee5c 100644 --- a/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java +++ b/engine/src/main/java/org/terasology/engine/core/ComponentSystemManager.java @@ -177,7 +177,7 @@ public void register(ComponentSystem object) { context.get(EntityManager.class).getEventSystem().registerEventHandler(object); if (initialised) { - logger.atWarn().addArgument(object.getClass().getName()).log("System {} registered post-init."); + logger.atWarn().log("System {} registered post-init.", object.getClass().getName()); initialiseSystem(object); } } diff --git a/engine/src/main/java/org/terasology/engine/core/PathManager.java b/engine/src/main/java/org/terasology/engine/core/PathManager.java index b66107c882e..69650bc6082 100644 --- a/engine/src/main/java/org/terasology/engine/core/PathManager.java +++ b/engine/src/main/java/org/terasology/engine/core/PathManager.java @@ -78,7 +78,7 @@ private static Path findInstallPath() { URI urlToSource = PathManager.class.getProtectionDomain().getCodeSource().getLocation().toURI(); Path codeLocation = Paths.get(urlToSource); installationSearchPaths.add(codeLocation); - LOGGER.atInfo().addArgument(codeLocation.toAbsolutePath()).log("PathManager: Initial code location is {}"); + LOGGER.atInfo().log("PathManager: Initial code location is " + codeLocation.toAbsolutePath()); } catch (URISyntaxException e) { LOGGER.error("PathManager: Failed to convert code location to path.", e); } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java index 44032823f3d..199617ff9dd 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/JoinServer.java @@ -104,8 +104,7 @@ public boolean step() { context.get(GameEngine.class).changeState(mainMenu); return false; } else { - logger.atInfo().addArgument(() -> moduleInfo.getName()).addArgument(() -> moduleInfo.getVersion()). - log("Activating module: {}:{}"); + logger.atInfo().log("Activating module: {}:{}", moduleInfo.getName(), moduleInfo.getVersion()); gameManifest.addModule(module.getId(), module.getVersion()); moduleSet.add(module); } diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java index 6b51c95236d..fe154254387 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/LoadEntities.java @@ -34,7 +34,7 @@ public boolean step() { boolean entityCreated = false; for (EntityRef entity : em.getAllEntities()) { entityCreated = true; - logger.atError().addArgument(() -> entity.toFullDescription()).log("Entity created before load: {}"); + logger.atError().log("Entity created before load: {}", entity.toFullDescription()); } if (entityCreated) { throw new IllegalStateException("Entity creation detected during component system initialisation, game load aborting"); diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java index e8bac12b0a0..e99eac75299 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/RegisterMods.java @@ -68,8 +68,7 @@ public boolean step() { ModuleEnvironment env = moduleManager.loadEnvironment(result.getModules(), true); for (Module moduleInfo : env.getModulesOrderedByDependencies()) { - logger.atInfo().addArgument(() -> moduleInfo.getId()).addArgument(() -> moduleInfo.getVersion()). - log("Activating module: {}:{}"); + logger.atInfo().log("Activating module: {}:{}", moduleInfo.getId(), moduleInfo.getVersion()); } EnvironmentSwitchHandler environmentSwitchHandler = context.get(EnvironmentSwitchHandler.class); diff --git a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java index 97c059f60e8..aa508a38531 100644 --- a/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java +++ b/engine/src/main/java/org/terasology/engine/core/subsystem/config/BindsSubsystem.java @@ -251,13 +251,11 @@ private void registerAxisBinds(ModuleEnvironment environment) { BindableButton positiveButton = getBindButton(new SimpleUri(info.positiveButton())); BindableButton negativeButton = getBindButton(new SimpleUri(info.negativeButton())); if (positiveButton == null) { - logger.atWarn().addArgument(() -> id).addArgument(() -> info.positiveButton()). - log("Failed to register axis \"{}\", missing positive button \"{}\""); + logger.atWarn().log("Failed to register axis \"{}\", missing positive button \"{}\"", id, info.positiveButton()); continue; } if (negativeButton == null) { - logger.atWarn().addArgument(() -> id).addArgument(() -> info.negativeButton()). - log("Failed to register axis \"{}\", missing negative button \"{}\""); + logger.atWarn().log("Failed to register axis \"{}\", missing negative button \"{}\"", id, info.negativeButton()); continue; } try { diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java index 37c06572ea3..1294e20a59d 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java @@ -50,8 +50,7 @@ public ComponentLibrary createCopyUsingCopyStrategy(Class type, CopyStrat return null; } catch (NoClassDefFoundError e) { // log what class was not found so that diagnosis is easier - logger.atError().addArgument(() -> type.getSimpleName()).addArgument(() -> e). - log("Class not found, {}"); + logger.atError().log("Class not found, {}", type.getSimpleName(), e); throw e; } return info; diff --git a/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java b/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java index e4199df0938..11c37e50dd0 100644 --- a/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java +++ b/engine/src/main/java/org/terasology/engine/identity/storageServiceClient/StorageServiceWorker.java @@ -71,10 +71,10 @@ private synchronized void performAction(Action action, StorageServiceWorkerStatu throw new RuntimeException("StorageServiceWorker is not in the required status"); } status = StorageServiceWorkerStatus.WORKING; - logger.atInfo().addArgument(() -> action.getClass().getSimpleName()).log("Performing action {}"); + logger.atInfo().log("Performing action {}", action.getClass().getSimpleName()); new Thread(() -> { action.perform(this); - logger.atInfo().addArgument(() -> action.getClass().getSimpleName()).log("Completed action {}"); + logger.atInfo().log("Completed action {}", action.getClass().getSimpleName()); }).start(); } diff --git a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java index 1a62d114d25..c86b5bb4925 100644 --- a/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java +++ b/engine/src/main/java/org/terasology/engine/input/lwjgl/LwjglControllerDevice.java @@ -107,20 +107,20 @@ private void onJoystickConnectDisconnect(int jid, int event) { private void handleJoystickConnect(int jid) { if (GLFW.glfwJoystickIsGamepad(jid)) { gamepadIds.add(jid); - logger.atInfo().addArgument(() -> GLFW.glfwGetJoystickName(jid)).log("JoyStick connected: {}"); + logger.atInfo().log("JoyStick connected: {}", GLFW.glfwGetJoystickName(jid)); } else { joystickIds.add(jid); - logger.atInfo().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Gamepad connected: {}"); + logger.atInfo().log("Gamepad connected: {}", GLFW.glfwGetGamepadName(jid)); } } private void handleJoystickDisconnect(int jid) { if (GLFW.glfwJoystickIsGamepad(jid)) { gamepadIds.remove(jid); - logger.atInfo().addArgument(() -> GLFW.glfwGetJoystickName(jid)).log("JoyStick disconnected: {}"); + logger.atInfo().log("JoyStick disconnected: {}", GLFW.glfwGetJoystickName(jid)); } else { joystickIds.remove(jid); - logger.atInfo().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Gamepad disconnected: {}"); + logger.atInfo().log("Gamepad disconnected: {}", GLFW.glfwGetGamepadName(jid)); } } @@ -186,7 +186,7 @@ public Queue getInputQueue() { buttonIndex++; } } else { - logger.atError().addArgument(() -> GLFW.glfwGetGamepadName(jid)).log("Cannot get states for {}"); + logger.atError().log("Cannot get states for {}", GLFW.glfwGetGamepadName(jid)); } } diff --git a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java index 606b8a0b563..a510d771bcc 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java @@ -74,8 +74,8 @@ public static void registerAvailable(Object provider, Console console, Context c Set commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); for (Method method : commandMethods) { if (!hasSenderAnnotation(method)) { - logger.atError().addArgument(() -> method.getName()).addArgument(() -> provider.getClass().getSimpleName()). - log("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a NullPointerException"); + logger.atError().log("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a " + + "NullPointerException", methodName, providerClass.getSimpleName()); } logger.atDebug().addArgument(() -> method.getName()).addArgument(() -> method.getDeclaringClass().getCanonicalName()). log("Registering command method {} in class {}"); diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java index 94726b79382..9288b489638 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java @@ -507,8 +507,7 @@ private void processEvents(NetData.NetMessage message) { Event event = eventSerializer.deserialize(eventMessage.getEvent()); EventMetadata metadata = eventLibrary.getMetadata(event.getClass()); if (metadata.getNetworkEventType() != NetworkEventType.SERVER) { - logger.atWarn().addArgument(() -> metadata).addArgument(() -> getName()). - log("Received non-server event '{}' from client '{}'"); + logger.atWarn().log("Received non-server event '{}' from client '{}'", metadata, getName()); continue; } if (!lagCompensated && metadata.isLagCompensated()) { diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java index 6ae75e4a1b9..64cf4e57358 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java @@ -193,7 +193,7 @@ private void processReceivedChunks() { } private void send(NetData.NetMessage data) { - logger.atTrace().addArgument(() -> data.getSerializedSize()).log("Sending with size {}"); + logger.atTrace().log("Sending with size {}", data.getSerializedSize()); channel.writeAndFlush(data); } @@ -232,10 +232,7 @@ private void processEvent(NetData.EventMessage message) { if (target.exists()) { target.send(event); } else { - logger.atInfo(). - addArgument(() -> event.getClass().getSimpleName()). - addArgument(target). - log("Dropping event {} for unavailable entity {}"); + logger.atInfo().log("Dropping event {} for unavailable entity {}", event.getClass().getSimpleName(), target); } } catch (DeserializationException e) { logger.error("Failed to deserialize event", e); diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java index d6695ced682..88b49f66ed8 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/ComponentSerializer.java @@ -100,7 +100,7 @@ public Component deserialize(EntityData.Component componentData, Module context) Component component = componentMetadata.newInstance(); return deserializeOnto(component, componentData, componentMetadata, FieldSerializeCheck.NullCheck.newInstance()); } else { - logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); + logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType()); } return null; } @@ -159,7 +159,7 @@ public Component deserializeOnto(Component target, EntityData.Component componen if (componentMetadata != null) { return deserializeOnto(target, componentData, componentMetadata, fieldCheck); } else { - logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); + logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType()); } return target; } @@ -179,8 +179,7 @@ private Component deserializeOnto(Component targetComponen if (fieldInfo != null) { dataMap.put(fieldInfo, new ProtobufPersistedData(field.getValue())); } else if (field.hasName()) { - logger.atWarn().addArgument(() -> field.getName()).addArgument(() -> componentMetadata.getId()). - log("Cannot deserialize unknown field '{}' onto '{}'"); + logger.atWarn().log("Cannot deserialize unknown field '{}' onto '{}'", field.getName(), componentMetadata.getId()); } } serializer.deserializeOnto(targetComponent, dataMap, fieldCheck); @@ -206,9 +205,10 @@ public EntityData.Component serialize(Component component) { * @return The serialized component, or null if it could not be serialized. */ public EntityData.Component serialize(Component component, FieldSerializeCheck check) { + ComponentMetadata componentMetadata = componentLibrary.getMetadata(component.getClass()); if (componentMetadata == null) { - logger.atError().addArgument(() -> component.getClass()).log("Unregistered component type: {}"); + logger.atError().log("Unregistered component type: {}", component.getClass()); return null; } EntityData.Component.Builder componentMessage = EntityData.Component.newBuilder(); @@ -263,7 +263,7 @@ public EntityData.Component serialize(Component base, Component delta) { public EntityData.Component serialize(Component base, Component delta, FieldSerializeCheck check) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(base.getClass()); if (componentMetadata == null) { - logger.atError().addArgument(() -> base.getClass()).log("Unregistered component type: {}"); + logger.atError().log("Unregistered component type: {}", base.getClass()); return null; } @@ -326,7 +326,7 @@ public ComponentMetadata getComponentMetadata(EntityData.Co } } if (metadata == null) { - logger.atWarn().addArgument(() -> componentData.getTypeIndex()).log("Unable to deserialize unknown component with id: {}"); + logger.atWarn().log("Unable to deserialize unknown component with id: {}", componentData.getTypeIndex()); return null; } return metadata; @@ -338,7 +338,7 @@ public ComponentMetadata getComponentMetadata(EntityData.Co metadata = componentLibrary.resolve(componentData.getType()); } if (metadata == null) { - logger.atWarn().addArgument(() -> componentData.getType()).log("Unable to deserialize unknown component type: {}"); + logger.atWarn().log("Unable to deserialize unknown component type: {}", componentData.getType()); return null; } return metadata; diff --git a/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java b/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java index e104ab2b299..cec62dba634 100644 --- a/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java +++ b/engine/src/main/java/org/terasology/engine/persistence/serializers/NetworkEntitySerializer.java @@ -130,7 +130,7 @@ private void serializeComponentDelta(Component oldComponent, Component newCompon boolean componentInitial) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(oldComponent.getClass()); if (componentMetadata == null) { - logger.atError().addArgument(() -> oldComponent.getClass()).log("Unregistered component type: {}"); + logger.atError().log("Unregistered component type: {}", oldComponent.getClass()); return; } @@ -165,7 +165,7 @@ private void serializeComponentFull(Component component, boolean ignoreIfNoField boolean componentInitial) { ComponentMetadata componentMetadata = componentLibrary.getMetadata(component.getClass()); if (componentMetadata == null) { - logger.atError().addArgument(() -> component.getClass()).log("Unregistered component type: {}"); + logger.atError().log("Unregistered component type: {}", component.getClass()); return; } @@ -218,11 +218,8 @@ public void deserializeOnto(MutableComponentContainer entity, EntityData.PackedE byte fieldId = entityData.getFieldIds().byteAt(fieldPos); ReplicatedFieldMetadata fieldMetadata = metadata.getField(fieldId); if (fieldMetadata != null && fieldCheck.shouldDeserialize(metadata, fieldMetadata)) { - logger.atTrace(). - addArgument(() -> fieldMetadata). - addArgument(() -> metadata). - addArgument(entityData.getFieldValue(fieldPos)). - log("Deserializing field {} of component {} as value {}"); + logger.atTrace().log("Deserializing field {} of component {} as value {}", + fieldMetadata, metadata, entityData.getFieldValue(fieldPos)); serializer.deserializeOnto(component, fieldMetadata, new ProtobufPersistedData(entityData.getFieldValue(fieldPos))); } fieldPos++; diff --git a/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java b/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java index e0295a5c831..c79d185380c 100644 --- a/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java +++ b/engine/src/main/java/org/terasology/engine/registry/InjectionHelper.java @@ -73,10 +73,8 @@ public static void inject(final Object object) { logger.error("Failed to inject value {} into field {} of {}", value, field, object, e); } } else { - logger.atWarn(). - addArgument(() -> object.getClass().getSimpleName()). - addArgument(() -> field.getType().getSimpleName()). - log("{} wanted {} injected but CoreRegistry has none."); + logger.atWarn().log("{} wanted {} injected but CoreRegistry has none.", + object.getClass().getSimpleName(), field.getType().getSimpleName()); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java index b80d2a58eaa..1a9a9df474c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java @@ -302,8 +302,7 @@ public void connectFbo(Node fromNode, int outputId, Node toNode, int inputId) { // if (!areConnected(fromNode, toNode)) { // connect(fromNode, toNode); // } - logger.atDebug().addArgument(() -> fromNode.getOutputFboConnection(outputId)).addArgument(toNode). - log("Connected {} to {}."); + logger.atDebug().log("Connected {} to {}.", fromNode.getOutputFboConnection(outputId), toNode); } public void reconnectFbo(Node fromNode, int outputId, Node toNode, int inputId) { @@ -402,8 +401,7 @@ public void connectBufferPair(Node fromNode, int outputId, Node toNode, int inpu // if (!areConnected(fromNode, toNode)) { // connect(fromNode, toNode); // } - logger.atDebug().addArgument(() -> fromNode.getOutputBufferPairConnection(outputId)).addArgument(toNode). - log("Connected {} to {}."); + logger.atDebug().log("Connected {} to {}.", fromNode.getOutputBufferPairConnection(outputId), toNode); } /** diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java index f0bce128267..777dd5c96b1 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/asset/UIDeltaFormat.java @@ -47,10 +47,7 @@ public void apply(AssetDataFile input, UIData assetData) throws IOException { if (skin.isPresent()) { assetData.getRootWidget().setSkin(skin.get()); } else { - logger.atWarn(). - addArgument(skinUri). - addArgument(() -> input.getFilename()). - log("Failed to load skin {} for the delta file {}"); + logger.atWarn().log("Failed to load skin {} for the delta file {}", skinUri, input.getFilename()); } } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java b/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java index 39ac38f581d..4abc912d8c7 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/skin/UISkinFormat.java @@ -145,8 +145,7 @@ public void apply(UISkinBuilder builder) { builder.setElementClass(metadata.getType()); entry.getValue().apply(builder); } else { - logger.atWarn().addArgument(() -> entry.getKey()). - log("Failed to resolve UIWidget class {}, skipping style information"); + logger.atWarn().log("Failed to resolve UIWidget class {}, skipping style information", entry.getKey()); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java index 22c763f0da7..4a76b192472 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/ObjectLayoutBuilder.java @@ -192,8 +192,8 @@ private void populateConstructorParameters(Binding binding, library.getBaseTypeWidget((Binding) argumentBinding, parameterType); if (!optionalWidget.isPresent()) { - LOGGER.atWarn().addArgument(parameter).addArgument(() -> selectedConstructor.get()). - log("Could not create widget for parameter of type {} of constructor {}"); + LOGGER.atWarn().log("Could not create widget for parameter of type {} of constructor {}", + parameter, selectedConstructor.get()); continue; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java index 76d1ee0803c..531c6278db0 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/widgets/types/object/SubtypeLayoutBuilder.java @@ -147,8 +147,7 @@ protected void onSet() { .orElse(baseTypeWidgetBuilder); if (builder == null) { - LOGGER.atError().addArgument(() -> get()).addArgument(baseType). - log("Could not find widget for type {}, editing as base type {}"); + LOGGER.atError().log("Could not find widget for type {}, editing as base type {}", get(), baseType); return; } diff --git a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java index 46f8727370f..29e6a56c677 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java +++ b/engine/src/main/java/org/terasology/engine/rendering/world/WorldRendererImpl.java @@ -205,10 +205,9 @@ private void initRenderingModules() { for (ModuleRendering moduleRenderingInstance : renderingModuleRegistry.getOrderedRenderingModules()) { if (moduleRenderingInstance.isEnabled()) { - logger.atInfo(). - addArgument(moduleRenderingInstance.getClass().getSimpleName()). - addArgument(moduleRenderingInstance.getProvidingModule()). - log("\nInitialising rendering class {} from {} module.\n"); + logger.atInfo().log("\nInitialising rendering class {} from {} module.\n", + moduleRenderingInstance.getClass().getSimpleName(), + moduleRenderingInstance.getProvidingModule()); moduleRenderingInstance.initialise(); } } diff --git a/engine/src/main/java/org/terasology/engine/utilities/Jvm.java b/engine/src/main/java/org/terasology/engine/utilities/Jvm.java index bdca4a848b8..be0dcbd7a17 100644 --- a/engine/src/main/java/org/terasology/engine/utilities/Jvm.java +++ b/engine/src/main/java/org/terasology/engine/utilities/Jvm.java @@ -28,12 +28,12 @@ public static void logClasspath(Logger aLogger) { Matcher asMavenCache = MAVEN_CACHE.matcher(pathEntry); if (asGradleCache.matches()) { if (asGradleCache.group(1).contains(interestingGroup)) { - aLogger.atDebug().addArgument(indent).addArgument(() -> asGradleCache.group(2)).log("{}gradle:{}"); + aLogger.atDebug().log("{}gradle:{}", indent, asGradleCache.group(2)); } else { elidedCount++; } } else if (asMavenCache.matches()) { - aLogger.atDebug().addArgument(indent).addArgument(() -> asMavenCache.group(1)).log("{}maven:{}"); + aLogger.atDebug().log("{}maven:{}", indent, asMavenCache.group(1)); } else { String place = pathEntry; if (pathEntry.startsWith(projectRoot)) { diff --git a/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java b/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java index 7151438d351..97a87e6fbe8 100644 --- a/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java +++ b/engine/src/main/java/org/terasology/engine/world/generation/FacetedWorldConfigurator.java @@ -30,7 +30,7 @@ public FacetedWorldConfigurator(List providersList) { for (ConfigurableFacetProvider provider : providersList) { Component old = properties.put(provider.getConfigurationName(), provider.getConfiguration()); if (old != null) { - logger.atWarn().addArgument(() -> provider.getConfigurationName()).log("Duplicate property key: {}"); + logger.atWarn().log("Duplicate property key: {}", provider.getConfigurationName()); } } this.providers = providersList; From 3705efff1d5108fc2cdcb4af76337db18fb6ab7a Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:23:52 +0200 Subject: [PATCH 23/28] fix: //NOPMD doesn't work if log spans multiple lines - removed line break or switched back to fluent API (using less verbose variant though) --- .../config/flexible/AutoConfigTypeHandler.java | 3 +-- .../modes/loadProcesses/InitialiseWorld.java | 4 ++-- .../entitySystem/metadata/ComponentLibrary.java | 2 +- .../particles/updating/ParticleUpdaterImpl.java | 4 ++-- .../engine/rendering/dag/AbstractNode.java | 4 ++-- .../engine/rendering/dag/RenderGraph.java | 16 ++++++++-------- 6 files changed, 16 insertions(+), 17 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java index 060e5b8a2f7..cf74ea8c52a 100644 --- a/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java +++ b/engine/src/main/java/org/terasology/engine/config/flexible/AutoConfigTypeHandler.java @@ -77,8 +77,7 @@ public Optional deserialize(PersistedData data) { if (value.isPresent()) { setting.set(value.get()); } else { - logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(), - setting.getValueType()); //NOPMD + logger.error("Cannot deserialize value [{}] to type [{}]", entry.getValue(), setting.getValueType()); //NOPMD } } else { logger.error("Cannot deserialize type [{}]", setting.getValueType()); //NOPMD diff --git a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java index db4757090bf..80201a202d0 100644 --- a/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java +++ b/engine/src/main/java/org/terasology/engine/core/modes/loadProcesses/InitialiseWorld.java @@ -105,8 +105,8 @@ public boolean step() { worldGenerator.setWorldSeed(worldInfo.getSeed()); context.put(WorldGenerator.class, worldGenerator); } catch (UnresolvedWorldGeneratorException e) { - logger.error("Unable to load world generator {}. Available world generators: {}", - worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators()); //NOPMD + logger.atError().log("Unable to load world generator {}. Available world generators: {}", + worldInfo.getWorldGenerator(), worldGeneratorManager.getWorldGenerators()); context.get(GameEngine.class).changeState(new StateMainMenu("Failed to resolve world generator.")); return true; // We need to return true, otherwise the loading state will just call us again immediately } diff --git a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java index 1294e20a59d..4dad928a94a 100644 --- a/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java +++ b/engine/src/main/java/org/terasology/engine/entitySystem/metadata/ComponentLibrary.java @@ -46,7 +46,7 @@ public ComponentLibrary createCopyUsingCopyStrategy(Class type, CopyStrat try { info = new ComponentMetadata<>(uri, type, factory, copyStrategies); } catch (NoSuchMethodException e) { - logger.error("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); //NOPMD + logger.atError().log("Unable to register class {}: Default Constructor Required", type.getSimpleName(), e); return null; } catch (NoClassDefFoundError e) { // log what class was not found so that diagnosis is easier diff --git a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java index e66912d3ff8..418aa2f2236 100644 --- a/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java +++ b/engine/src/main/java/org/terasology/engine/particles/updating/ParticleUpdaterImpl.java @@ -125,8 +125,8 @@ public void initialize() { for (Class type : environment.getTypesAnnotatedWith(RegisterParticleSystemFunction.class)) { if (!ParticleSystemFunction.class.isAssignableFrom(type)) { - logger.error("Cannot register particle system function {}, must be a subclass of ParticleSystemFunction", - type.getSimpleName()); //NOPMD + logger.atError().log("Cannot register particle system function {}, " + + "must be a subclass of ParticleSystemFunction", type.getSimpleName()); } else { try { ParticleSystemFunction function = (ParticleSystemFunction) type.newInstance(); diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java index 64b8adcdab0..4ef3f3fcfeb 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java @@ -549,8 +549,8 @@ public void dispose() { */ protected void addDesiredStateChange(StateChange stateChange) { if (stateChange.isTheDefaultInstance()) { - logger.error("Attempted to add default state change {} to the set of desired state changes. (Node: {})", - stateChange.getClass().getSimpleName(), this); //NOPMD + logger.atError().log("Attempted to add default state change {} to the set of desired state changes. (Node: {})", + stateChange.getClass().getSimpleName(), this); } desiredStateChanges.add(stateChange); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java index 1a9a9df474c..e040f732a7f 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderGraph.java @@ -52,8 +52,8 @@ public void addNode(Node node) { } if (akaNodeMap.containsKey(nodeAka)) { Node aNode = akaNodeMap.get(nodeAka); - logger.info("Node {} also known as {} already matches existing node with uri {} - attempting replacing...", - nodeUri, nodeAka, aNode.getUri()); //NOPMD + logger.atInfo().log("Node {} also known as {} already matches existing node with uri {} - attempting replacing...", + nodeUri, nodeAka, aNode.getUri()); replaceNode(aNode, node); } else { nodeMap.put(nodeUri, node); @@ -275,8 +275,8 @@ private void connectFbo(Node toNode, int inputFboId, DependencyConnection fromCo } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", - toNode.getUri(), inputFboId, fromConnection.getName()); //NOPMD + logger.atInfo().log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", + toNode.getUri(), inputFboId, fromConnection.getName()); DependencyConnection localConnection = toNode.getInputFboConnection(inputFboId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -339,8 +339,8 @@ private void connectBufferPair(Node toNode, int inputConnectionId, DependencyCon } else { // if adding new input failed, it already existed - check for connections //TODO update - logger.info("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", - toNode.getUri(), inputConnectionId, fromConnection.getName()); //NOPMD + logger.atInfo().log("{}.connectFbo({}, {}): Connection already existed. Testing for its connections..", + toNode.getUri(), inputConnectionId, fromConnection.getName()); DependencyConnection localConnection = toNode.getInputBufferPairConnection(inputConnectionId); // DependencyConnection localConnectionConnectedTo = localConnection.getConnectedConnections(); // if our input is connected @@ -534,8 +534,8 @@ private void reconnectInputToOutput(Node toNode, int inputId, DependencyConnecti fromNode = findNode(fromConnection.getParentNode()); if (!fromConnection.getConnectedConnections().isEmpty()) { - logger.warn("WARNING: destination connection ({}) is already connected to ({})", - fromConnection, fromConnection.getConnectedConnections()); //NOPMD + logger.atWarn().log("WARNING: destination connection ({}) is already connected to ({})", + fromConnection, fromConnection.getConnectedConnections()); // TODO update the hashmap to string to be pretty // throw new RuntimeException("Could not reconnect, destination connection (" + fromConnection + ") is already connected to (" // + fromConnection.getConnectedConnections() + "). Remove connection first."); From c48561f43e0f2a20ea4d73fb6f09eeba638e38e6 Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:26:53 +0200 Subject: [PATCH 24/28] refactor: introduce and reference local variables --- .../logic/characters/CharacterSystem.java | 64 ++++++++----------- .../console/commandSystem/MethodCommand.java | 18 +++--- .../internal/ClientConnectionHandler.java | 16 ++--- .../engine/network/internal/NetClient.java | 3 +- .../network/internal/NetworkSystemImpl.java | 25 ++++---- .../engine/network/internal/ServerImpl.java | 19 +++--- .../gameDetailsScreen/GameDetailsScreen.java | 23 +++---- .../engine/world/generation/WorldBuilder.java | 13 ++-- 8 files changed, 84 insertions(+), 97 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java index 5f233831092..49caafa0646 100644 --- a/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java +++ b/engine/src/main/java/org/terasology/engine/logic/characters/CharacterSystem.java @@ -306,48 +306,41 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques CharacterComponent characterComponent = character.getComponent(CharacterComponent.class); EntityRef camera = GazeAuthoritySystem.getGazeEntityForCharacter(character); LocationComponent location = camera.getComponent(LocationComponent.class); - Vector3f direction = location.getWorldDirection(new Vector3f()); - if (!(event.getDirection().equals(direction, 0.0001f))) { - logger.atError().addArgument(() -> event.getDirection()).addArgument(direction). - log("Direction at client {} was different than direction at server {}"); + Vector3f worldDirection = location.getWorldDirection(new Vector3f()); + Vector3f eventDirection = event.getDirection(); + if (!(eventDirection.equals(worldDirection, 0.0001f))) { + logger.error("Direction at client {} was different than direction at server {}", eventDirection, worldDirection); } - // Assume the exact same value in case there are rounding mistakes: - direction = event.getDirection(); + String playerName = getPlayerNameFromCharacter(character); Vector3f originPos = location.getWorldPosition(new Vector3f()); - if (!(event.getOrigin().equals(originPos, 0.0001f))) { - logger.atInfo(). - addArgument(() -> getPlayerNameFromCharacter(character)). - addArgument(() -> event.getOrigin()). - addArgument(() -> originPos). - log("Player {} seems to have cheated: It stated that it performed an action from {} but the predicted position is {}"); + Vector3f eventOrigin = event.getOrigin(); + if (!(eventOrigin.equals(originPos, 0.0001f))) { + logger.info("Player {} seems to have cheated: It stated that it performed an action from {} " + + "but the predicted position is {}", playerName, eventOrigin, originPos); return false; } if (event.isOwnedEntityUsage()) { if (!event.getUsedOwnedEntity().exists()) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since the used entity does not exist on the authority"); + logger.info("Denied activation attempt by {} since the used entity does not exist on the authority", playerName); return false; } if (!networkSystem.getOwnerEntity(event.getUsedOwnedEntity()).equals(networkSystem.getOwnerEntity(character))) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since it does not own the entity at the authority"); + logger.info("Denied activation attempt by {} since it does not own the entity at the authority", playerName); return false; } } else { // check for cheats so that data can later be trusted: if (event.getUsedOwnedEntity().exists()) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since it is not properly marked as owned entity usage"); + logger.info("Denied activation attempt by {} since it is not properly marked as owned entity usage", playerName); return false; } } if (event.isEventWithTarget()) { if (!event.getTarget().exists()) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since the target does not exist on the authority"); + logger.info("Denied activation attempt by {} since the target does not exist on the authority", playerName); return false; // can happen if target existed on client } @@ -361,45 +354,42 @@ private boolean isPredictionOfEventCorrect(EntityRef character, ActivationReques interactionRange = characterComponent.interactionRange; } - HitResult result = physics.rayTrace(originPos, direction, interactionRange, Sets.newHashSet(character), + HitResult result = physics.rayTrace(originPos, eventDirection, interactionRange, Sets.newHashSet(character), DEFAULTPHYSICSFILTER); if (!result.isHit()) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since at the authority there was nothing to activate at that place"); + logger.info("Denied activation attempt by {} since at the authority there was nothing " + + "to activate at that place", playerName); return false; } EntityRef hitEntity = result.getEntity(); if (!hitEntity.equals(event.getTarget())) { - /** - * Tip for debugging this issue: Obtain the network id of hit entity and search it in both client and - * server entity dump. When certain fields don't get replicated, then wrong entity might get hin in the - * hit test. + /* + Tip for debugging this issue: Obtain the network id of hit entity and search it in both client and + server entity dump. When certain fields don't get replicated, then wrong entity might get hin in the + hit test. */ - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since at the authority another entity would have been activated"); + logger.info("Denied activation attempt by {} since at the authority another entity would have been activated", playerName); return false; } if (!(event.getHitPosition().equals(result.getHitPoint(), 0.0001f))) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since at the authority the object got hit at a differnt position"); + logger.info("Denied activation attempt by {} since at the authority the object " + + "got hit at a different position", playerName); return false; } } else { // In order to trust the data later we need to verify it even if it should be correct if no one cheats: if (event.getTarget().exists()) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since the event was not properly labeled as having a target"); + logger.info("Denied activation attempt by {} since the event was not properly labeled as having a target", playerName); return false; } if (event.getHitPosition() != null) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since the event was not properly labeled as having a hit position"); + logger.info("Denied activation attempt by {} since the event was not properly labeled " + + "as having a hit position", playerName); return false; } if (event.getHitNormal() != null) { - logger.atInfo().addArgument(() -> getPlayerNameFromCharacter(character)). - log("Denied activation attempt by {} since the event was not properly labeled as having a hit delta"); + logger.info("Denied activation attempt by {} since the event was not properly labeled as having a hit delta", playerName); return false; } } diff --git a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java index a510d771bcc..f636f12225d 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/commandSystem/MethodCommand.java @@ -71,26 +71,24 @@ public static MethodCommand referringTo(SpecificAccessibleObject specifi public static void registerAvailable(Object provider, Console console, Context context) { Predicate predicate = Predicates.and(ReflectionUtils.withModifier(Modifier.PUBLIC), ReflectionUtils.withAnnotation(Command.class)); - Set commandMethods = ReflectionUtils.getAllMethods(provider.getClass(), predicate); + + Class providerClass = provider.getClass(); + Set commandMethods = ReflectionUtils.getAllMethods(providerClass, predicate); for (Method method : commandMethods) { + String methodName = method.getName(); + String canonicalMethodName = method.getDeclaringClass().getCanonicalName(); if (!hasSenderAnnotation(method)) { logger.atError().log("Command {} provided by {} contains a EntityRef without @Sender annotation, may cause a " + "NullPointerException", methodName, providerClass.getSimpleName()); } - logger.atDebug().addArgument(() -> method.getName()).addArgument(() -> method.getDeclaringClass().getCanonicalName()). - log("Registering command method {} in class {}"); + logger.debug("Registering command method {} in class {}", methodName, canonicalMethodName); try { SpecificAccessibleObject specificMethod = new SpecificAccessibleObject<>(method, provider); MethodCommand command = referringTo(specificMethod, context); console.registerCommand(command); - logger.atDebug().addArgument(() -> method.getName()).addArgument(() -> method.getDeclaringClass().getCanonicalName()). - log("Registered command method {} in class {}"); + logger.debug("Registered command method {} in class {}", methodName, canonicalMethodName); } catch (RuntimeException t) { - logger.atError(). - addArgument(() -> method.getName()). - addArgument(() -> method.getDeclaringClass().getCanonicalName()). - addArgument(() -> t). - log("Failed to load command method {} in class {}"); + logger.error("Failed to load command method {} in class {}", methodName, canonicalMethodName, t); } } } diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java index 8ea7d34a4a7..d4b86ea0c51 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ClientConnectionHandler.java @@ -151,21 +151,18 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext, return; } String moduleId = moduleDataHeader.getId(); + String moduleVersion = moduleDataHeader.getVersion(); if (missingModules.remove(moduleId.toLowerCase(Locale.ENGLISH))) { if (moduleDataHeader.hasError()) { joinStatus.setErrorMessage("Module download error: " + moduleDataHeader.getError()); channelHandlerContext.channel().close(); } else { String sizeString = getSizeString(moduleDataHeader.getSize()); + int numOfMissingModules = missingModules.size(); joinStatus.setCurrentActivity( - "Downloading " + moduleDataHeader.getId() + ":" + moduleDataHeader.getVersion() + " (" - + sizeString + "," + missingModules.size() + " modules remain)"); - logger.atInfo(). - addArgument(() -> moduleDataHeader.getId()). - addArgument(() -> moduleDataHeader.getVersion()). - addArgument(() -> sizeString). - addArgument(() -> missingModules.size()). - log("Downloading {}: {} ({}, {} modules remain)"); + "Downloading " + moduleDataHeader.getId() + ":" + moduleVersion + + " (" + sizeString + "," + numOfMissingModules + " modules remain)"); + logger.info("Downloading {}: {} ({}, {} modules remain)", moduleId, moduleVersion, sizeString, numOfMissingModules); receivingModule = moduleDataHeader; lengthReceived = 0; try { @@ -180,8 +177,7 @@ private void receiveModuleStart(ChannelHandlerContext channelHandlerContext, } } } else { - logger.atError().addArgument(() -> moduleDataHeader.getId()).addArgument(() -> moduleDataHeader.getVersion()). - log("Received unwanted module {}:{} from server"); + logger.error("Received unwanted module {}:{} from server", moduleId, moduleVersion); joinStatus.setErrorMessage("Module download error"); channelHandlerContext.channel().close(); } diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java index 9288b489638..4d032876acd 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java @@ -363,7 +363,8 @@ public boolean isLocal() { } void send(NetData.NetMessage data) { - logger.atTrace().addArgument(() -> data.getSerializedSize()).log("Sending packet with size {}"); + int dataSize = data.getSerializedSize(); + logger.trace("Sending packet with size {}", dataSize); sentMessages.incrementAndGet(); sentBytes.addAndGet(data.getSerializedSize()); channel.writeAndFlush(data); diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java index 4eee38115d5..ca552b46975 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java @@ -239,11 +239,13 @@ public JoinStatus join(String address, int port) throws InterruptedException { return connectionHandler.getJoinStatus(); } } else { - logger.atWarn().addArgument(connectCheck.cause()).log("Failed to connect to server"); + + Throwable connectionFailureCause = connectCheck.cause(); + logger.warn("Failed to connect to server", connectionFailureCause); connectCheck.channel().closeFuture().awaitUninterruptibly(); clientGroup.shutdownGracefully(shutdownQuietMs, shutdownTimeoutMs, TimeUnit.MILLISECONDS) .syncUninterruptibly(); - return new JoinStatusImpl("Failed to connect to server - " + connectCheck.cause().getMessage()); + return new JoinStatusImpl("Failed to connect to server - " + connectionFailureCause.getMessage()); } } connectCheck.channel().closeFuture().sync(); @@ -538,12 +540,12 @@ public void unregisterNetworkEntity(EntityRef entity) { if (mode != NetworkMode.CLIENT) { NetworkComponent netComponent = entity.getComponent(NetworkComponent.class); if (netComponent != null) { - logger.atDebug().addArgument(entity).addArgument(netComponent.getNetworkId()). - log("Unregistering network entity: {} with netId {}"); - netIdToEntityId.remove(netComponent.getNetworkId()); + int networkId = netComponent.getNetworkId(); + logger.debug("Unregistering network entity: {} with netId {}", entity, networkId); + netIdToEntityId.remove(networkId); if (mode.isServer()) { for (NetClient client : netClientList) { - client.setNetRemoved(netComponent.getNetworkId()); + client.setNetRemoved(networkId); } } netComponent.setNetworkId(NULL_NET_ID); @@ -993,20 +995,21 @@ private Map, Integer> applySerializationInfo(List classLibrary) { Map, Integer> idTable = Maps.newHashMap(); for (NetData.SerializationInfo info : infoList) { - ClassMetadata metadata = classLibrary.getMetadata(info.getName()); + String infoName = info.getName(); + ClassMetadata metadata = classLibrary.getMetadata(infoName); if (metadata != null) { idTable.put(metadata.getType(), info.getId()); for (int i = 0; i < info.getFieldIds().size(); ++i) { - FieldMetadata field = metadata.getField(info.getFieldName(i)); + String fieldName = info.getFieldName(i); + FieldMetadata field = metadata.getField(fieldName); if (field != null) { field.setId(info.getFieldIds().byteAt(i)); } else { - logger.atError().addArgument(info.getFieldName(i)).addArgument(() -> info.getName()). - log("Server has unknown field '{}' on '{}'"); + logger.error("Server has unknown field '{}' on '{}'", fieldName, infoName); } } } else { - logger.atError().addArgument(() -> info.getName()).log("Server has unknown class '{}'"); + logger.error("Server has unknown class '{}'", infoName); } } return idTable; diff --git a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java index 64cf4e57358..ce58a19391b 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/ServerImpl.java @@ -353,15 +353,16 @@ private void processBlockRegistrations(NetData.NetMessage message) { } private void updateEntity(NetData.UpdateEntityMessage updateEntity) { - EntityRef currentEntity = networkSystem.getEntity(updateEntity.getNetId()); + int entityNetId = updateEntity.getNetId(); + EntityRef currentEntity = networkSystem.getEntity(entityNetId); if (currentEntity.exists()) { NetworkComponent netComp = currentEntity.getComponent(NetworkComponent.class); if (netComp == null) { - logger.atError().addArgument(() -> currentEntity).addArgument(() -> updateEntity.getNetId()). - log("Updating entity with no network component: {}, expected netId {}"); + logger.error("Updating entity with no network component: {}, expected netId {}", currentEntity, entityNetId); return; } - if (netComp.getNetworkId() != updateEntity.getNetId()) { + int networkId = netComp.getNetworkId(); + if (networkId != entityNetId) { logger.error("Network ID wrong before update"); } boolean blockEntityBefore = currentEntity.hasComponent(BlockComponent.class); @@ -371,15 +372,11 @@ private void updateEntity(NetData.UpdateEntityMessage updateEntity) { && !blockEntityRegistry.getExistingBlockEntityAt(blockComponent.getPosition()).equals(currentEntity)) { logger.error("Failed to associated new block entity"); } - if (netComp.getNetworkId() != updateEntity.getNetId()) { - logger.atError(). - addArgument(() -> currentEntity). - addArgument(() -> updateEntity.getNetId()). - addArgument(() -> netComp.getNetworkId()). - log("Network ID lost in update: {}, {} -> {}"); + if (networkId != entityNetId) { + logger.error("Network ID lost in update: {}, {} -> {}", currentEntity, entityNetId, networkId); } } else { - logger.atWarn().addArgument(() -> updateEntity.getNetId()).log("Received update for non-existent entity {}"); + logger.warn("Received update for non-existent entity {}", entityNetId); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java index 31d98494b45..a1a2caaa23c 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java +++ b/engine/src/main/java/org/terasology/engine/rendering/nui/layers/mainMenu/gameDetailsScreen/GameDetailsScreen.java @@ -26,7 +26,9 @@ import org.terasology.gestalt.module.Module; import org.terasology.gestalt.module.ModuleMetadata; import org.terasology.gestalt.module.dependencyresolution.DependencyInfo; +import org.terasology.gestalt.naming.Name; import org.terasology.gestalt.naming.NameVersion; +import org.terasology.gestalt.naming.Version; import org.terasology.nui.Canvas; import org.terasology.nui.databinding.Binding; import org.terasology.nui.databinding.ReadOnlyBinding; @@ -350,25 +352,24 @@ private void loadGameModules() { final List sortedGameModules = gameInfo.getManifest().getModules().stream() .sorted(Comparator.comparing(NameVersion::getName)) .map(nameVersion -> { - Module module = moduleManager.getRegistry().getModule(nameVersion.getName(), nameVersion.getVersion()); + Name name = nameVersion.getName(); + Version version = nameVersion.getVersion(); + Module module = moduleManager.getRegistry().getModule(name, version); if (module != null) { return ModuleSelectionInfo.strictVersion(module); } else { - logger.atWarn().addArgument(() -> nameVersion.getName()).addArgument(() -> nameVersion.getVersion()). - log("Can't find module in your classpath - {}:{}"); - module = moduleManager.getRegistry().getLatestModuleVersion(nameVersion.getName()); + logger.warn("Can't find module in your classpath - {}:{}", name, version); + module = moduleManager.getRegistry().getLatestModuleVersion(name); if (module != null) { - logger.atDebug().addArgument(() -> nameVersion.getName()). - log("Get the latest available version of module {} in your classpath"); + logger.debug("Get the latest available version of module {} in your classpath", name); errors.add(String.format("Can't find module %s:%s in your classpath; " + "loaded description for the latest available version.", - nameVersion.getName(), nameVersion.getVersion())); + name, version)); return ModuleSelectionInfo.latestVersion(module); } - logger.atError().addArgument(() -> nameVersion.getName()). - log("Can't find any versions of module {} in your classpath!"); - errors.add(String.format("Can't find any versions of module %s in your classpath!", nameVersion.getName())); - return ModuleSelectionInfo.unavailableVersion(nameVersion.getName().toString(), nameVersion.getVersion().toString()); + logger.error("Can't find any versions of module {} in your classpath!", name); + errors.add(String.format("Can't find any versions of module %s in your classpath!", name)); + return ModuleSelectionInfo.unavailableVersion(name.toString(), version.toString()); } }) .filter(Objects::nonNull) diff --git a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java index bf5c888367e..9cecdce85c1 100644 --- a/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java +++ b/engine/src/main/java/org/terasology/engine/world/generation/WorldBuilder.java @@ -175,23 +175,24 @@ private ListMultimap, FacetProvider> determineProvid ListMultimap, FacetProvider> result = ArrayListMultimap.create(); Set> facets = new LinkedHashSet<>(); for (FacetProvider provider : providersList) { - Produces produces = provider.getClass().getAnnotation(Produces.class); + Class providerClass = provider.getClass(); + Produces produces = providerClass.getAnnotation(Produces.class); if (produces != null) { facets.addAll(Arrays.asList(produces.value())); } - Requires requires = provider.getClass().getAnnotation(Requires.class); + Requires requires = providerClass.getAnnotation(Requires.class); if (requires != null) { for (Facet facet : requires.value()) { - if (!facets.contains(facet.value())) { - logger.atError().addArgument(() -> facet.value()).addArgument(() -> provider.getClass()). - log("Facet provider for {} is missing. It is required by {}"); + Class facetValue = facet.value(); + if (!facets.contains(facetValue)) { + logger.error("Facet provider for {} is missing. It is required by {}", facetValue, providerClass); throw new IllegalStateException("Missing facet provider"); } } } - Updates updates = provider.getClass().getAnnotation(Updates.class); + Updates updates = providerClass.getAnnotation(Updates.class); if (updates != null) { for (Facet facet : updates.value()) { facets.add(facet.value()); From 56f9ed87735c31fa3c16092239f7cbbeff5c3835 Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:27:24 +0200 Subject: [PATCH 25/28] refactor: suppress guardlogstatement warnings for methods intended for logging --- .../engine/logic/console/ConsoleImpl.java | 15 ++++++--------- .../engine/rendering/ShaderManagerLwjgl.java | 11 ++++++----- 2 files changed, 12 insertions(+), 14 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java index 04b66b74479..316dc954c6b 100644 --- a/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java +++ b/engine/src/main/java/org/terasology/engine/logic/console/ConsoleImpl.java @@ -59,21 +59,18 @@ public ConsoleImpl(Context context) { * @param command The command to be registered */ @Override + @SuppressWarnings("PMD.GuardLogStatement") public void registerCommand(ConsoleCommand command) { Name commandName = command.getName(); if (commandRegistry.containsKey(commandName)) { - logger.atWarn(). - addArgument(() -> commandName). - addArgument(() -> commandRegistry.get(commandName).getSource().getClass().getCanonicalName()). - addArgument(() -> command.getSource().getClass().getCanonicalName()). - log("Command with name '{}' already registered by class '{}', skipping '{}'"); + logger.warn("Command with name '{}' already registered by class '{}', skipping '{}'", commandName, + commandRegistry.get(commandName).getSource().getClass().getCanonicalName(), + command.getSource().getClass().getCanonicalName()); } else { commandRegistry.put(commandName, command); - logger.atDebug(). - addArgument(() -> commandName). - addArgument(() -> command.getSource().getClass().getCanonicalName()). - log("Command '{}' successfully registered for class '{}'."); + logger.debug("Command '{}' successfully registered for class '{}'.", commandName, + command.getSource().getClass().getCanonicalName()); } } diff --git a/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java b/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java index c5ae2930f4f..99b32654932 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java +++ b/engine/src/main/java/org/terasology/engine/rendering/ShaderManagerLwjgl.java @@ -47,13 +47,14 @@ public void initShaders() { addShaderProgram("particle"); } + @SuppressWarnings("PMD.GuardLogStatement") private void logCapabilities() { logger.info("Loading Terasology shader manager..."); - logger.atInfo().addArgument(() -> Version.getVersion()).addArgument(() -> Platform.get().getName()).log("LWJGL: {} / {}"); - logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_VENDOR)).log("GL_VENDOR: {}"); - logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_RENDERER)).log("GL_RENDERER: {}"); - logger.atInfo().addArgument(() -> GL11.glGetString(GL11.GL_VERSION)).log("GL_VERSION: {}"); - logger.atInfo().addArgument(() -> GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION)).log("SHADING_LANGUAGE VERSION: {}"); + logger.info("LWJGL: {} / {}", Version.getVersion(), Platform.get().getName()); + logger.info("GL_VENDOR: {}", GL11.glGetString(GL11.GL_VENDOR)); + logger.info("GL_RENDERER: {}", GL11.glGetString(GL11.GL_RENDERER)); + logger.info("GL_VERSION: {}", GL11.glGetString(GL11.GL_VERSION)); + logger.info("SHADING_LANGUAGE VERSION: {}", GL11.glGetString(GL20.GL_SHADING_LANGUAGE_VERSION)); int[] extension = new int[1]; GL30.glGetIntegerv(GL30.GL_NUM_EXTENSIONS, extension); From e4cb5fc3b826e8fcf8d9fbb0e5242050bc2fbfda Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:28:27 +0200 Subject: [PATCH 26/28] revert: unnecessary usage of fluent API --- .../engine/network/internal/NetClient.java | 3 +-- .../network/internal/NetworkSystemImpl.java | 2 +- .../engine/rendering/dag/AbstractNode.java | 18 ++++++++---------- .../rendering/dag/RenderTaskListGenerator.java | 2 +- 4 files changed, 11 insertions(+), 14 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java index 4d032876acd..9752c7136f7 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetClient.java @@ -525,8 +525,7 @@ private void processEvents(NetData.NetMessage message) { if (Objects.equal(networkSystem.getOwner(target), this)) { target.send(event); } else { - logger.atWarn().addArgument(() -> event).addArgument(target).addArgument(() -> this). - log("Received event {} for non-owned entity {} from {}"); + logger.warn("Received event {} for non-owned entity {} from {}", event, target, this); } } } catch (DeserializationException e) { diff --git a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java index ca552b46975..bd28ae55293 100644 --- a/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java +++ b/engine/src/main/java/org/terasology/engine/network/internal/NetworkSystemImpl.java @@ -183,7 +183,7 @@ public void host(int port, boolean dedicatedServer) throws HostingFailedExceptio logger.info("Started server on port {}", port); if (config.getServerMOTD() != null) { - logger.atInfo().addArgument(() -> config.getServerMOTD()).log("Server MOTD is \"{}\""); + logger.info("Server MOTD is \"{}\"", config.getServerMOTD()); //NOPMD } else { logger.info("No server MOTD is defined"); } diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java index 4ef3f3fcfeb..6a5225245cb 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/AbstractNode.java @@ -204,8 +204,8 @@ public boolean addOutputBufferPairConnection(int id, BufferPair bufferPair) { } if (localBufferPairConnection.getData() != null) { - logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(localBufferPairConnection). - log("Adding output buffer pair to slot id {} of {} node overwrites data of existing connection: {}"); + logger.warn("Adding output buffer pair to slot id {} of {} node overwrites data of existing connection: {}", + id, this.nodeUri, localBufferPairConnection); } localBufferPairConnection.setData(bufferPair); success = true; @@ -241,8 +241,8 @@ public boolean addOutputBufferPairConnection(int id, BufferPairConnection from) } if (localBufferPairConnection.getData() != null) { - logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(localBufferPairConnection). - log("Adding output buffer pair connection to slot id {} of {} node overwrites data of existing connection: {}"); + logger.warn("Adding output buffer pair connection to slot id {} of {} node overwrites data of existing connection: {}", + id, this.nodeUri, localBufferPairConnection); } localBufferPairConnection.setData(from.getData()); @@ -303,8 +303,8 @@ protected boolean addOutputFboConnection(int id, FBO fboData) { FboConnection fboConnection = (FboConnection) outputConnections.get(connectionUri); if (fboConnection.getData() != null) { - logger.atWarn().addArgument(id).addArgument(() -> this.nodeUri).addArgument(fboConnection). - log("Adding output fbo data to slot id {} of {} node overwrites data of existing connection: {}"); + logger.warn("Adding output fbo data to slot id {} of {} node overwrites data of existing connection: {}", + id, this.nodeUri, fboConnection); } fboConnection.setData(fboData); @@ -443,8 +443,7 @@ public int getNumberOfOutputConnections() { public DependencyConnection getInputConnection(String name) { DependencyConnection connection = inputConnections.get(name); if (connection == null) { - logger.atError().addArgument(name).addArgument(this). - log("Getting input connection named {} returned null. No such input connection in {}"); + logger.error("Getting input connection named {} returned null. No such input connection in {}", name, this); // throw new NullPointerException(errorMessage); } return connection; @@ -454,8 +453,7 @@ public DependencyConnection getInputConnection(String name) { public DependencyConnection getOutputConnection(String name) { DependencyConnection connection = outputConnections.get(name); if (connection == null) { - logger.atError().addArgument(name).addArgument(this). - log("Getting output connection named {} returned null. No such output connection in {}."); + logger.error("Getting output connection named {} returned null. No such output connection in {}.", name, this); // throw new NullPointerException(errorMessage); } return connection; diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java index a3f99a95a74..02ca5fb3006 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/RenderTaskListGenerator.java @@ -184,7 +184,7 @@ public List generateFrom(List orderedNodes) { private void logList(List list) { for (Object object : list) { - logger.atDebug().addArgument(object).log("{}"); + logger.debug("{}", object); } } From 2f15a827476943667929d637e65466ff62ce5a36 Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:29:05 +0200 Subject: [PATCH 27/28] qa: address remaining PMD guardlogstatement warnings --- .../terasology/engine/rendering/dag/ModuleRendering.java | 6 ++---- .../world/chunks/blockdata/ExtraBlockDataManager.java | 4 ++-- .../world/chunks/localChunkProvider/LocalChunkProvider.java | 2 +- 3 files changed, 5 insertions(+), 7 deletions(-) diff --git a/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java b/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java index bc25fb341c3..fa0cf557a67 100644 --- a/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java +++ b/engine/src/main/java/org/terasology/engine/rendering/dag/ModuleRendering.java @@ -118,11 +118,9 @@ protected FBO generateWithDimensions(FboConfig fboConfig, FBO.Dimensions dimensi // At this stage it's unclear what should be done in this circumstances as I (manu3d) do not know what // the effects of using an incomplete FrameBuffer are. Throw an exception? Live with visual artifacts? if (fbo.getStatus() == FBO.Status.INCOMPLETE) { - logger.atError().addArgument(() -> fboConfig.getName()). - log("FBO {} is incomplete. Look earlier in the log for details."); + logger.error("FBO {} is incomplete. Look earlier in the log for details.", fboConfig.getName()); //NOPMD } else if (fbo.getStatus() == FBO.Status.UNEXPECTED) { - logger.atError().addArgument(() -> fboConfig.getName()). - log("FBO {} has generated an unexpected status code. Look earlier in the log for details."); + logger.error("FBO {} has generated an unexpected status code. Look earlier in the log for details.", fboConfig.getName()); //NOPMD } return fbo; } diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java index be5bef50e7b..e8dd4a46564 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java @@ -90,7 +90,7 @@ public ExtraBlockDataManager(Context context) { loggingOutput.append(first ? " " : ", ").append(entry.getKey()).append(" -> ").append(entry.getValue()); first = false; } - logger.info(loggingOutput.toString()); + logger.info(loggingOutput); } // Find requests for extensions and which blocks they apply to. @@ -107,7 +107,7 @@ private Map>> getFieldsFromAnnotations(Context c if (registerAnnotation != null) { String errorType = validRegistrationMethod(method, registerAnnotation); if (errorType != null) { - logger.error("Unable to register extra block data: {} for {}.{}: should be \"public static" + logger.atError().log("Unable to register extra block data: {} for {}.{}: should be \"public static" + " boolean {}(Block block)\", and bitSize should be 4, 8 or 16.", errorType, type.getName(), method.getName(), method.getName()); continue; diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java index 9c5f08e07fc..6316960d7bb 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/localChunkProvider/LocalChunkProvider.java @@ -239,7 +239,7 @@ public void update() { processReadyChunk(chunk); long totalProcessingTime = System.currentTimeMillis() - processingStartTime; if (!readyChunks.isEmpty() && totalProcessingTime > UPDATE_PROCESSING_DEADLINE_MS) { - logger.warn("Chunk processing took too long this tick ({}/{}ms). {} chunks remain.", totalProcessingTime, + logger.atWarn().log("Chunk processing took too long this tick ({}/{}ms). {} chunks remain.", totalProcessingTime, UPDATE_PROCESSING_DEADLINE_MS, readyChunks.size()); break; } From 4ad29ed3c3f8c570129b26d02241b416c27a55ff Mon Sep 17 00:00:00 2001 From: Josephine Rueckert Date: Fri, 17 May 2024 20:41:42 +0200 Subject: [PATCH 28/28] fix: log format --- .../engine/world/chunks/blockdata/ExtraBlockDataManager.java | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java index e8dd4a46564..c6b843984e1 100644 --- a/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java +++ b/engine/src/main/java/org/terasology/engine/world/chunks/blockdata/ExtraBlockDataManager.java @@ -90,7 +90,7 @@ public ExtraBlockDataManager(Context context) { loggingOutput.append(first ? " " : ", ").append(entry.getKey()).append(" -> ").append(entry.getValue()); first = false; } - logger.info(loggingOutput); + logger.info("{}", loggingOutput); } // Find requests for extensions and which blocks they apply to.