Skip to content

SLF4J Fluent logging api migration recipe  #67

Description

@timtebeek

SLF4J 2.0.0 has been released: https://www.slf4j.org/faq.html#changesInVersion200
That means we can now adopt the fluent logging api: https://www.slf4j.org/manual.html#fluent

I expect this to be most useful around guard blocks such as the following:

void before() {
	if (log.isInfoEnabled()) {
		log.info("Log an expensive argument", expensiveArgument());
	}
}
void after() {
	log.atInfo()
		.addArgument(() -> expensiveArgument())
		.log("Log an expensive argument");
}
static List<String> expensiveArgument() {
	return new ArrayList<>(100_000_000);
}

But it can also be adopted independent of the guard blocks used previously.

The following log statements are equivalent in their output (for the default implementation):

int newT = 15;
int oldT = 16;

// using traditional API
logger.debug("Temperature set to {}. Old temperature was {}.", newT, oldT);

// using fluent API, add arguments one by one and then log message
logger.atDebug().addArgument(newT).addArgument(oldT).log("Temperature set to {}. Old temperature was {}.");

// using fluent API, log message with arguments
logger.atDebug().log("Temperature set to {}. Old temperature was {}.", newT, oldT);

// using fluent API, add one argument and then log message providing one more argument
logger.atDebug().addArgument(newT).log("Temperature set to {}. Old temperature was {}.", oldT);

// using fluent API, add one argument with a Supplier and then log message with one more argument.
// Assume the method t16() returns 16.
logger.atDebug().addArgument(() -> t16()).log(msg, "Temperature set to {}. Old temperature was {}.", oldT);

Migration would like to need to change the dependency version of both the api and the bindings.

Metadata

Metadata

Assignees

No one assigned

    Labels

    recipeRecipe Requested

    Type

    No type
    No fields configured for issues without a type.

    Projects

    Status
    Recipes Wanted

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions