[slf4j-user] Combined logging and throwing question

Norbert Kiesel nkiesel at MetricStream.com
Wed May 6 19:59:16 CEST 2020


Hi,

we have quite a few places in our code where we do:

    logger.error("Param {} must be in [{}-{}]", name, low, high);
    throw new ValidationException("Param " + name + " must be in [" + low + "-" + high + "]");

This is obviously ugly.  Other options would be to use

    String msg = String.format("Param %s must be in [%s-%s]", name, low, high);
    logger.error(msg);
    throw new ValidationException(msg);

or

    String msg = MessageFormatter.format("Param {} must be in [{}-{}]", new Object[] {name, low, high}).getMessage();
    logger.error(msg);
    throw new ValidationException(msg);

Both are not ideal.  Can't we have a logger.format method which returns a FormattingTuple w/o the explicit array creation
and allow logger.error etc. to be called with a FormattingTuple?  Then I could write

    FormattingTuple entry = logger.format("Param {} must be in [{}-{}]", name, low, high);
    logger.error(entry);
    throw new ValidationException(entry.getMessage());

For my own exception classes I could then even offer a constructor that takes a FormattingTuple and internally use the
message and the throwable (if it is not null).

</nk>

---


Norbert Kiesel
Systems Architect, Engineering
E: nkiesel at metricstream.com<mailto:sonia.sharma at metricstream.com>
W: www.metricstream.com

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mailman.qos.ch/pipermail/slf4j-user/attachments/20200506/f5b69058/attachment.html>


More information about the slf4j-user mailing list