In the Java 11 runtime, any output to
STDERR is propagated to
Cloud Logging. However, granular log
severity level is not propagated. In the Java 11 runtime, you can use the
Java Logging API (JUL)
to log messages and propagate the correct log severity levels to Cloud Logging.
- Format the log messages in the Structured Logging JSON format so that the severity level is propagated to Cloud Logging.
- Use a bridge/adapter to send log messages to the Java Logging API, which already propagates the log messages in the correct format. If you take this approach, make sure there is not an existing adapter that already routes from the Java Logging API to the logging framework.
If your function uses different libraries and the libraries use different logging frameworks, then you'll need to configure each of the logging frameworks used. The following sections cover some of the various options.
Spring Cloud Function
If you use Spring Cloud Function with the Spring Cloud Functions GCP
Adapter, you can easily output the log in the right format using the
Spring Cloud GCP's Logging Starter and the
to output the log in the JSON format. Spring uses SLF4J and Logback by
default—but you can also route SLF4J logs to the Java Logging API. See the
SLF4J section for details.
Java Logging API (JUL)
The Cloud Functions Java 11 environment already includes Java Logging with a JSON handler that outputs the log in the correct format. Some Java frameworks may add additional components to bridge JUL to a different logging framework (such as jul-to-slf4j bridge or Log4j JDK Logging Adapter), in which case those log messages will no longer be formatted correctly. If your log messages do not have correct severity levels, make sure those bridges are removed.
Logback does not have an appender that routes log messages to the Java Logging API. However, Logback is usually used with the SFL4J API, so you can switch the SLF4J logger implementation to the Java Logging API.
Log4j 2 does not have a direct adapter that routes log messages to the Java Logging API. If you are using Log4j 2, then you need to first route messages to SLF4J using the Log4J 2 to SLF4J Adapter, then configure SLF4J to use the Java Logging API implementation. Make sure you do not have the Log4j JDK Logging Adapter.