Uploaded image for project: 'SLF4J'
  1. SLF4J
  2. SLF4J-371

Support the lambda expression in the Logger

    XMLWordPrintable

    Details

    • Type: Improvement
    • Status: Resolved
    • Priority: Major
    • Resolution: Fixed
    • Affects Version/s: 1.7.22
    • Fix Version/s: 2.0.0-alpha1
    • Component/s: Core API
    • Labels:
      None

      Description

      In some cases, we don't want to calculate the expression for logging eagerly cause the performance reason. Then, we would write the code like the following:

      if (LOGGER.isWarnEnabled())
      {
       LOGGER.warn("some message: {}", Json.serialize(obj));
      }

      Before JDK8, there is no way to encapsulate the above code, because the expression is always calculated before passed as an argument. So, many "if"s appear in the code and smell badly.

      Now, the lambda expression is supported by JDK8, the above could be simplified like following:

      LOGGER.warn(formatter -> formatter.format("some message: {}", Json.serialize(obj)));

      With the default method definition in the org.slf4j.Logger:

      public interface Logger
      {
       default void warn(Function<MessageFormatter, String> messageSupplier)
       {
        if (this.isWarnEnabled())
        {
         /* Calculate the expression only if the WARN level logging is enabled. */
         this.warn(messageSupplier.apply(this.getFormatter()));
        }
       }
      }

        Attachments

          Issue Links

            Activity

              People

              Assignee:
              ceki Ceki Gülcü
              Reporter:
              JasonMing MiNG
              Votes:
              65 Vote for this issue
              Watchers:
              57 Start watching this issue

                Dates

                Created:
                Updated:
                Resolved: