With sl4fj if I want to construct a string message there is a nice approach which makes use of substitutions. For instance, it might be something like:
logger.info("Action {} occured on object {}.", objectA.getAction(), objectB);
If there are more than a few substitutions required then it is something like:
logger.info("Action {} occured on object {} with outcome {}.", new Object[]{objectA.getAction(), objectB, outcome});
My question is: Is there a generic way for me to create a string (and not just a slf4j log message)? Something like:
String str = someMethod("Action {} occured on object {}.", objectA.getAction(), objectB);
or
String str = someMethod("Action {} occured on object {} with outcome {}.", new Object[]{objectA.getAction(), objectB, outcome});
If it is in the standard Java library, what would that "someMethod" be?
Using the + operator is the most common way to concatenate two strings in Java. You can provide either a variable, a number, or a String literal (which is always surrounded by double quotes). Be sure to add a space so that when the combined string is printed, its words are separated properly.
String.format
String str = String.format("Action %s occured on object %s.", objectA.getAction(), objectB);
Or
String str = String.format("Action %s occured on object %s with outcome %s.", new Object[]{objectA.getAction(), objectB, outcome});
You can also use numeric positions, for example to switch the parameters around:
String str = String.format("Action %2$s occured on object %1$s.", objectA.getAction(), objectB);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With