Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

kotlin logging with lambda parameters

In log4j2 we have a handy feature which is described as

// Java-8 style optimization: no need to explicitly check the log level:
// the lambda expression is not evaluated if the TRACE level is not enabled
logger.trace("Some long-running operation returned {}", () -> expensiveOperation());

my attempt to use this in kotlin

log.debug("random {}", { UUID.randomUUID() })

which will print

random Function0<java.util.UUID>

How do we use lambda argument logging with kotlin? Or how do we explicitly tell kotlin what method to call?

like image 407
vach Avatar asked Jun 11 '16 18:06

vach


People also ask

How do you pass the lambda function in Kotlin?

Lambda expression syntaxParameter declarations in the full syntactic form go inside curly braces and have optional type annotations. The body goes after the -> . If the inferred return type of the lambda is not Unit , the last (or possibly single) expression inside the lambda body is treated as the return value.

Does lambda use Log4j?

Advanced logging with Log4j 2 and SLF4J. AWS Lambda does not include Log4j2 in its managed runtimes or base container images. These are therefore not affected by the issues described in CVE-2021-44228, CVE-2021-45046, and CVE-2021-45105.

Does AWS lambda support Kotlin?

Lambda provides the Amazon Linux build of openjdk 1.8 which means that Lambda fully supports running all languages that can be compiled and run on the Java Virtual Machine. There are many popular languages that use JVM such as Scala, Groovy and Kotlin.


1 Answers

The problem is that debug() is overloaded, and has another method taking a vararg Object as argument. Kotlin chooses that overload rather than the one taking a Supplier<?> as argument, because it doesn't know that the lambda expression is supposed to be a Supplier.

Just specify it as a Supplier:

log.debug("random {}", Supplier { UUID.randomUUID() })
like image 118
JB Nizet Avatar answered Sep 20 '22 15:09

JB Nizet