Programing

sl4fj와 유사한 일반적인 문자열 대체 기능이 있습니까?

lottogame 2020. 10. 21. 07:37
반응형

sl4fj와 유사한 일반적인 문자열 대체 기능이 있습니까?


sl4fj를 사용하면 문자열 메시지를 생성하려는 경우 대체를 사용하는 좋은 접근 방식이 있습니다. 예를 들어 다음과 같을 수 있습니다.

logger.info("Action {} occured on object {}.", objectA.getAction(), objectB);

몇 가지 이상의 대체가 필요한 경우 다음과 같습니다.

logger.info("Action {} occured on object {} with outcome {}.", 
    new Object[]{objectA.getAction(), objectB, outcome});

내 질문은 다음과 같습니다. slf4j 로그 메시지뿐만 아니라 문자열을 만드는 일반적인 방법이 있습니까? 다음과 같은 것 :

String str = someMethod("Action {} occured on object {}.", objectA.getAction(), objectB);

또는

String str = someMethod("Action {} occured on object {} with outcome {}.", 
    new Object[]{objectA.getAction(), objectB, outcome});

표준 Java 라이브러리에있는 경우 "someMethod"는 무엇입니까?


String.format

String str = String.format("Action %s occured on object %s.",
   objectA.getAction(), objectB);

또는

String str = String.format("Action %s occured on object %s with outcome %s.",
   new Object[]{objectA.getAction(), objectB, outcome});

예를 들어 매개 변수를 전환하기 위해 숫자 위치를 사용할 수도 있습니다.

String str = String.format("Action %2$s occured on object %1$s.",
   objectA.getAction(), objectB);

String.format 또는 MessageFormat.format을 사용할 수 있습니다.

예 :

MessageFormat.format("A sample value {1} with a sample string {0}", 
    new Object[] {"first", 1});

또는 단순히

MessageFormat.format("A sample value {1} with a sample string {0}", "first", 1);

문자열의 여러 변수를 값으로 대체 할 수있는 솔루션을 찾고 있다면 StrSubstitutor 를 사용할 수 있습니다 .

 Map<String, String> valuesMap = new HashMap<>();
 valuesMap.put("animal", "quick brown fox");
 valuesMap.put("target", "lazy dog");
 String templateString = "The ${animal} jumped over the ${target}.";
 StrSubstitutor sub = new StrSubstitutor(valuesMap);
 String resolvedString = sub.replace(templateString);

일반적으로 허용되는 패턴을 따르며 변수가있는 맵을 해결되지 않은 문자열과 함께 값에 전달할 수 있으며 해결 된 문자열을 반환합니다.


org.slf4j.helpers.MessageFormatter 를 사용하는 것이 좋습니다 . 그것의 도움으로 slf4j와 똑같은 서식 스타일을 사용하는 유틸리티 메서드를 만들 수 있습니다.

// utillity method to format like slf4j
public static String format(String msg, Object... objs) {
    return MessageFormatter.arrayFormat(msg, objs).getMessage();
}

// example usage
public static void main(String[] args) {
    String msg = format("This msg is {} like slf{}j would do. {}", "formatted", 4,
            new Exception("Not substituted into the message"));

    // prints "This msg is formatted like slf4j would do. {}"    
    System.out.println(msg); 
}

참고 : 배열의 마지막 개체가 Exception이면 slf4j 로거와 마찬가지로 메시지에서 대체되지 않습니다. 예외는를 통해 액세스 할 수 있습니다 MessageFormatter.arrayFormat(msg, objs).getThrowable().


저는 Joern Huxhorn이 Lilith를 위해 원래 작성한 Log4j2 ParameterizedMessage래핑합니다 .

public static String format(final String messagePattern, Object... arguments) {
    return ParameterizedMessage.format(messagePattern, arguments);
}

Throwable의 불필요한 처리를 포함하는 SLF4J MessageFormatter 와 달리 메시지 형식에 중점을 둡니다 .

Javadoc을 참조하십시오.

Handles messages that consist of a format string containing '{}' to represent each replaceable token, and the parameters.

참고URL : https://stackoverflow.com/questions/5057960/is-there-a-general-string-substitution-function-similar-to-sl4fj

반응형