Mantenha tudo organizado com as coleções
Salve e categorize o conteúdo com base nas suas preferências.
Geração de registros Java
No ambiente de execução do Java, qualquer saída para STDOUT ou STDERR é propagada para o
Cloud Logging. No entanto, o nível de gravidade do registro granular não é propagado. Use a API Java Logging (JUL) padrão para registrar mensagens e propagar os
níveis de gravidade de registro corretos para o Cloud Logging.
Se você usar uma estrutura de geração de registros diferente, como SLF4J, Log4j 2 ou
Apache Commons Logging,
será possível propagar o nível de gravidade de registro correto em uma das seguintes maneiras:
Use uma ponte/adaptador para enviar mensagens de registro para a API Java Logging, que já propaga as mensagens de registro no formato correto. Se você adotar essa abordagem, verifique se não há um adaptador existente que já faz o roteamento da API Java Logging para o framework de geração de registros.
Se a função usar bibliotecas diferentes e as bibliotecas usarem estruturas de geração de registros diferentes, será necessário configurar cada uma delas. As seções a seguir abrangem algumas das várias opções.
Spring Cloud Run function
Se você usar o Spring Cloud Run function com o adaptador do Spring Cloud Run functions
para o Google Cloud, será possível gerar o registro no formato correto usando o método
Starter do Logging do Google Cloud para o Spring Cloud e o
anexador CONSOLE_JSON
para gerar o registro no formato JSON. O Spring usa o SLF4J e o Logback por padrão, mas também é possível rotear registros SLF4J para a API Java Logging. Consulte a seção SLF4J para mais detalhes.
API Java Logging (JUL)
Todos os ambientes Java compatíveis do Cloud Run functions incluem o Java Logging com um gerenciador JSON que gera o registro no formato correto. Alguns frameworks do Java podem adicionar outros componentes para conectar JUL a um framework de geração de registros diferente (como ponte jul-to-slf4j ou Adaptador Log4j JDK). Nesse caso, esses registros as mensagens não serão mais formatadas corretamente. Se as mensagens de registro não tiverem níveis de gravidade corretos, verifique se essas pontes foram removidas.
SLF4J
O SLF4J
pode gravar registros na API Java Logging usando a vinculação do framework de geração
de registros slf4j-jdk14. Consulte a documentação do SLF4J para mais detalhes. Verifique se você não tem a ponte jul-to-slf4j.
Logback
O Logback não tem um
aplicativo que roteie mensagens de registro para a API Java Logging. No entanto, o Logback geralmente é usado com a API SFL4J para que você possa alternar a implementação do registrador SLF4J para a API Java Logging.
Log4j2
O Log4j 2
não tem um adaptador direto que direciona mensagens de registro para a API Java Logging.
Se você estiver usando o Log4j 2, primeiro será necessário rotear as mensagens para o SLF4J usando o adaptador Log4J 2 para SLF4J e, em seguida, configurar o SLF4J para usar a implementação da API Java Logging. Verifique se você não tem o adaptador Log4j JDK do Logging.
[[["Fácil de entender","easyToUnderstand","thumb-up"],["Meu problema foi resolvido","solvedMyProblem","thumb-up"],["Outro","otherUp","thumb-up"]],[["Difícil de entender","hardToUnderstand","thumb-down"],["Informações incorretas ou exemplo de código","incorrectInformationOrSampleCode","thumb-down"],["Não contém as informações/amostras de que eu preciso","missingTheInformationSamplesINeed","thumb-down"],["Problema na tradução","translationIssue","thumb-down"],["Outro","otherDown","thumb-down"]],["Última atualização 2024-12-22 UTC."],[[["\u003cp\u003eJava's standard output and error streams are propagated to Cloud Logging, but without granular severity levels.\u003c/p\u003e\n"],["\u003cp\u003eThe Java Logging API (JUL) should be used to ensure correct log severity levels are propagated to Cloud Logging.\u003c/p\u003e\n"],["\u003cp\u003eOther logging frameworks like SLF4J, Log4j 2, and Apache Commons Logging require specific configurations, either via structured JSON formatting or bridges/adapters, to achieve proper severity level propagation.\u003c/p\u003e\n"],["\u003cp\u003eSpring Cloud Run functions using the Google Cloud Adapter can utilize the \u003ccode\u003eCONSOLE_JSON\u003c/code\u003e appender for correct log formatting and utilize SLF4J with Logback which can be routed to Java Logging API.\u003c/p\u003e\n"],["\u003cp\u003eWhen using alternative logging frameworks, it is crucial to remove any existing bridges that may interfere with the correct formatting of log messages and severity levels.\u003c/p\u003e\n"]]],[],null,["# Java Logging\n============\n\nIn the Java runtime, any output to `STDOUT` or `STDERR` is propagated to [Cloud\nLogging](/functions/1stgendocs/monitoring/logging). However, granular log severity\nlevel is not propagated. Use the standard [Java Logging API (JUL)](https://docs.oracle.com/javase/10/core/java-logging-overview.htm/) to log messages and propagate the\ncorrect log severity levels to Cloud Logging.\n\nIf you use a different logging framework, such as [SLF4J](http://www.slf4j.org/), [Log4j 2](https://logging.apache.org/log4j/2.x/), or [Apache Commons Logging](https://commons.apache.org/proper/commons-logging/), you can propagate the correct log\nseverity level in one of the following ways:\n\n- Format the log messages in the [Structured Logging JSON format](/logging/docs/structured-logging) so that the severity level is propagated to Cloud Logging.\n- 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.\n\nIf your function uses different libraries and the libraries use different\nlogging frameworks, then you'll need to configure each of the logging frameworks\nused. The following sections cover some of the various options.\n\nSpring Cloud Run function\n-------------------------\n\nIf you use Spring Cloud Run function with the Spring Cloud Run functions\nGoogle Cloud Adapter, you can output the log in the right format using the\n[Spring Cloud's Google Cloud Logging Starter](https://github.com/GoogleCloudPlatform/spring-cloud-gcp/tree/main/spring-cloud-gcp-samples/spring-cloud-gcp-logging-sample) and the\n[`CONSOLE_JSON` appender](https://github.com/GoogleCloudPlatform/spring-cloud-gcp/blob/main/spring-cloud-gcp-logging/src/main/resources/com/google/cloud/spring/logging/logback-json-appender.xml)\nto output the log in the JSON format. Spring uses SLF4J and Logback by\ndefault---but you can also route SLF4J logs to the Java Logging API. See the\n[SLF4J](#slf4j) section for details.\n\nJava Logging API (JUL)\n----------------------\n\nAll supported\nCloud Run functions [Java\nenvironments](/functions/1stgendocs/runtime-support#java)\ninclude Java Logging with a JSON handler that outputs the log in the correct\nformat. Some Java frameworks may add additional components to bridge JUL to a\ndifferent logging framework (such as [jul-to-slf4j bridge](http://www.slf4j.org/legacy.html#jul-to-slf4j) or [Log4j JDK Logging Adapter](https://logging.apache.org/log4j/2.0/log4j-jul.html)), in which case those log\nmessages will no longer be formatted correctly. If your log messages do not have\ncorrect severity levels, make sure those bridges are removed.\n\nSLF4J\n-----\n\n[SLF4J](http://www.slf4j.org/) can write logs to the\nJava Logging API by using the `slf4j-jdk14` logging framework binding. See the\n[SLF4J\ndocumentation](http://www.slf4j.org/docs.html) for details. Make sure you don't have the `jul-to-slf4j`\nbridge.\n\nLogback\n-------\n\n[Logback](http://logback.qos.ch/) does not have an\nappender that routes log messages to the Java Logging API. However, Logback is\nusually used with the SFL4J API, so you can switch the\nSLF4J logger implementation to the [Java Logging API](#java_logging_api_jul).\n\nLog4j 2\n-------\n\n[Log4j 2](https://logging.apache.org/log4j/2.x/)\ndoes not have a direct adapter that routes log messages to the Java Logging API.\nIf you are using Log4j 2, then you need to first route messages to SLF4J using\nthe [Log4J 2 to SLF4J Adapter](https://logging.apache.org/log4j/log4j-2.2/log4j-to-slf4j/index.html), then configure SLF4J to use the\n[Java Logging API](#java_logging_api_jul) implementation. Make sure you do not\nhave the Log4j JDK Logging Adapter.\n\nApache Commons Logging (JCL)\n----------------------------\n\n[Apache Commons Logging](https://commons.apache.org/proper/commons-logging/) has a Java Logging API adapter.\nConfigure Commons Logging to use the [Jdk14Logger](http://commons.apache.org/proper/commons-logging/apidocs/org/apache/commons/logging/impl/Jdk14Logger.html). See the [Apache Commons Logging configuration](http://commons.apache.org/proper/commons-logging/guide.html#Configuration) page for more\ninformation."]]