Как иметь такой же журнал slf4j с JDK8 и JDK11 (с String.format внутри)?

Как иметь один и тот же журнал slf4j с JDK8 и JDK11?

Мой регистратор java Slf4j:

log.info("---> {} {}", "When", String.format(matcher.group(1).replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), invocation.getArguments()));

Моя трассировка в java 8 от JDK8:

---> When I update text {bakery.DemoPage-input_text_field} with {Jenkins T5}

Моя трассировка в java 8 от JDK11:

---> When "I update text {bakery.DemoPage-input_text_field} with {Jenkins T5}"

ИЗМЕНИТЬ:

Я пробую это, но тот же результат:

String message = MessageFormat.format("---> {0} {1}",
                                      stepAnnotation.annotationType().getSimpleName(),
                                      String.format(matcher.group(1).replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), invocation.getArguments())
                                     );
log.info(message);

ИЗМЕНИТЬ (если вам нужен более простой вариант):

log.info("---> {} {}", "When", String.format("I update text {%s} with {%s}", "bakery.DemoPage-input_text_field", "Jenkins T5"));

ИЗМЕНИТЬ с помощью @M. Предложение Deinum но не работает

log.info("---> {} " + matcher.group(1).replaceAll("\\{\\S+\\}", "{}").replace("(\\?)", ""), stepAnnotation.annotationType().getSimpleName(), invocation.getArguments());

---> When "I update text [bakery.DemoPage-input_text_field, Jenkins T5, []] with {}"

РЕДАКТИРОВАТЬ: я пробую другое предложение с внешней заменой:

String mes = String.format(matcher.group(1).replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), invocation.getArguments());
log.info("---> {} {}", stepAnnotation.annotationType().getSimpleName(), mes);

---> When "I update text {bakery.DemoPage-input_text_field} with {Jenkins T5}"

person Stéphane GRILLON    schedule 11.03.2020    source источник
comment
Измените свой вопрос, включив в него минимально воспроизводимый пример.   -  person Progman    schedule 11.03.2020
comment
Просто откажитесь от строкового формата. Используйте 1_. SLF4J выполнит замену независимо от используемого JDK.   -  person M. Deinum    schedule 12.03.2020
comment
@Progman, я добавил случай попроще, но все уже было в посте, чтобы воспроизвести проблему. Надеюсь, это поможет вам воспроизвести проблему дома.   -  person Stéphane GRILLON    schedule 12.03.2020
comment
@M.Deinum, ваше предложение, но оно не работает, я редактирую свой пост, добавляя больше элементов   -  person Stéphane GRILLON    schedule 12.03.2020
comment
Не используйте замены. Почему вы добавляете эту сложность к такой простой вещи, как ведение журнала. Log4j уже поддерживает замены. Как я уже сказал, поместите туда все сообщение и не выполняйте замену самостоятельно.   -  person M. Deinum    schedule 12.03.2020
comment
Мой случай не простой. Исходная строка содержит шаблон: "I update text {string} with {string}(\\?)"   -  person Stéphane GRILLON    schedule 12.03.2020
comment
Я нашел большую дорожку. проблема возникает не из slf4j, а из java.lang.annotation.Annotation.toString() разных в JDK8 и JDK11: @io.cucumber.java.en.When(timeout=0, value=I update text {string} with {string}(\?)) и @io.cucumber.java.en.When(timeout=0, value="@io.cucumber.java.en.When(timeout=0, value="I update text {string} with {string}(\?)")   -  person Stéphane GRILLON    schedule 12.03.2020
comment
вот продолжение проблемы, потому что это не исходит от Slf4j: stackoverflow.com/questions/60651653/   -  person Stéphane GRILLON    schedule 12.03.2020


Ответы (1)


проблема не в Slf4j, а в stepAnnotation.toString() разных JDK8 и JDK11)

openjdk11 и oraclejdk11 не уважают javadoc:

/**
 * Returns a string representation of this annotation.  The details
 * of the representation are implementation-dependent, but the following
 * may be regarded as typical:
 * <pre>
 *   &#064;com.acme.util.Name(first=Alfred, middle=E., last=Neuman)
 * </pre>
 *
 * @return a string representation of this annotation
 */
String toString();

Решение:

import java.lang.annotation.Annotation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import io.cucumber.java.en.When;

public class Sof {

    private static final Logger log = LoggerFactory.getLogger(Sof.class);

    @When(value = "I update text {string} with {string}(\\?)")
    public static void main(String[] args) {
        Object as[] = { "a", "b" };
        Class c = Sof.class;
        Method[] methods = c.getMethods();
        Method method = null;
        for (Method m : methods) {
            if (m.getName().equals("main")) {
                method = m;
            }
        }
        Annotation stepAnnotation = method.getAnnotation(When.class);
        Class<? extends Annotation> annotationClass = stepAnnotation.annotationType();
        try {
            Method valueMethods = annotationClass.getDeclaredMethod("value");
            if (Modifier.isPublic(valueMethods.getModifiers())) {
                log.info("---> {} " + String.format(valueMethods.invoke(stepAnnotation).toString().replaceAll("\\{\\S+\\}", "{%s}").replace("(\\?)", ""), as),
                        stepAnnotation.annotationType().getSimpleName());
            }
        } catch (NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException e1) {
            e1.printStackTrace();
        }
    }

}
person Stéphane GRILLON    schedule 12.03.2020