Setting Up Cloud Logging for Java

You can write logs to Cloud Logging from Java applications byusing theLogback appender or ajava.util.logging handler,or by using the Cloud Logging library for Java directly.

The Cloud Logging agent does not have to be installed to use theCloud Logging library for Java.

Before you begin

  1. Sign in to your Google Cloud account. If you're new to Google Cloud, create an account to evaluate how our products perform in real-world scenarios. New customers also get $300 in free credits to run, test, and deploy workloads.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Logging API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains theresourcemanager.projects.create permission.Learn how to grant roles.
    Note: If you don't plan to keep the resources that you create in this procedure, create a project instead of selecting an existing project. After you finish these steps, you can delete the project, removing all resources associated with the project.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Logging API.

    Roles required to enable APIs

    To enable APIs, you need the Service Usage Admin IAM role (roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enable permission.Learn how to grant roles.

    Enable the API

Logback appender for Cloud Logging

Using theLogback appender, you can useCloud Logging with theSLF4J logging facade.

Installing the dependency

If you are usingMaven, addthe following to yourpom.xml file. For more information aboutBOMs, seeThe Google Cloud Platform Libraries BOM.

<dependency>  <groupId>com.google.cloud</groupId>  <artifactId>google-cloud-logging-logback</artifactId>  <version>0.131.11-alpha</version></dependency>

If you are usingGradle,add the following to your dependencies:

implementation 'com.google.cloud:google-cloud-logging-logback:0.131.11-alpha'

If you are usingsbt, addthe following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-logging-logback" % "0.131.11-alpha"

Logback configuration

Logback can beconfiguredprogrammatically or using a script expressed in XML or Groovy.

You can customize the minimum severity threshold, log name, or provideadditional enhancers.This is a sample Logback configuration in XML format:

<configuration><appendername="CLOUD"class="com.google.cloud.logging.logback.LoggingAppender">    <!-- Optional : filter logs at or above a level -->    <filterdevsite-syntax-n">ch.qos.logback.classic.filter.ThresholdFilter">      <level>INFO</level>    </filter>    <log>application.log</log> <!-- Optional : default java.log -->    <resourceType>gae_app</resourceType> <!-- Optional : default: auto-detected, fallback: global -->    <enhancer>com.example.logging.logback.enhancers.ExampleEnhancer</enhancer> <!-- Optional -->    <flushLevel>WARN</flushLevel> <!-- Optional : default ERROR -->  </appender>  <root level="info">    <appender-ref ref="CLOUD" />  </root></configuration>

Example

Once you have configured Logback to use the Cloud Logging Logback appender,you can now redirect logs using the SLF4J logging API.Provide Google Cloudconfiguration if you plan to run the example locally or outside of Google Cloud.This snippet shows how to log using SLF4J facade within your application:

importorg.slf4j.Logger;importorg.slf4j.LoggerFactory;publicclassQuickstart{privatestaticfinalLoggerlogger=LoggerFactory.getLogger(Quickstart.class);publicstaticvoidmain(String[]args){logger.info("Logging INFO with Logback");logger.error("Logging ERROR with Logback");}}

The java.util.logging handler

You can also use the Cloud Logging API using a default Java Logging APIhandler.

Installing the dependency

If you are usingMaven witha BOM, add the following to yourpom.xml file:

<dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>libraries-bom</artifactId><version>26.55.0</version><type>pom</type><scope>import</scope></dependency></dependencies></dependencyManagement><dependencies><dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-logging</artifactId></dependency><!--...</dependencies>

If you are usingMavenwithout a BOM, add this to your dependencies:

<dependency><groupId>com.google.cloud</groupId><artifactId>google-cloud-logging</artifactId><version>3.21.3</version></dependency>

If you are usingGradle,add the following to your dependencies:

implementation platform('com.google.cloud:libraries-bom:26.72.0')implementation 'com.google.cloud:google-cloud-logging'

If you are usingsbt, addthe following to your dependencies:

libraryDependencies += "com.google.cloud" % "google-cloud-logging" % "3.23.9"

If you're using Visual Studio Code or IntelliJ, you can add client libraries to your project using the following IDE plugins:

The plugins provide additional functionality, such as key management for service accounts. Refer to each plugin's documentation for details.

Note: Cloud Java client libraries do not currently support Android.

java.util.logging configuration

Logging handlers can be added programmatically or by using a configuration file.The path to the configuration file must be provided to your application as a system property:

  -Djava.util.logging.config.file=/path/to/logging.properties

Here is an example of a configuration file:

#Tousethisconfiguration,addtosystemproperties:-Djava.util.logging.config.file="/path/to/file"#.level=INFO#itisrecommendedthatio.grpcandsun.netloggingleveliskeptatINFOlevel,#asboththesepackagesareusedbyCloudinternalsandcanresultinverbose/initializationproblems.io.grpc.netty.level=INFOsun.net.level=INFOcom.example.logging.jul.Quickstart.handlers=com.google.cloud.logging.LoggingHandler#default:java.logcom.google.cloud.logging.LoggingHandler.log=custom_log#default:INFOcom.google.cloud.logging.LoggingHandler.level=FINE#default:ERRORcom.google.cloud.logging.LoggingHandler.flushLevel=ERROR#default:auto-detected,fallback"global"com.google.cloud.logging.LoggingHandler.resourceType=container#customformattercom.google.cloud.logging.LoggingHandler.formatter=java.util.logging.SimpleFormatterjava.util.logging.SimpleFormatter.format=%3$s:%5$s%6$s#optionalenhancers(toaddadditionalfields,labels)com.google.cloud.logging.LoggingHandler.enhancers=com.example.logging.jul.enhancers.ExampleEnhancer

Example

Provide Google Cloudconfiguration if you plan to run the example locally or outside of Google Cloud.This snippet shows you how to log usingjava.util.logging:

importjava.util.logging.Logger;publicclassQuickstart{privatestaticfinalLoggerlogger=Logger.getLogger(Quickstart.class.getName());publicstaticvoidmain(String[]args){logger.info("Logging INFO with java.util.logging");logger.severe("Logging ERROR with java.util.logging");}}

Common Configuration

The following sections cover configuration that is common to thejava.util.logging handler and the Logback appender for Cloud Logging.

Defaults

The Logback appender andjava.util.logging handler use the following defaultsto instantiate a Cloud Logging client:

  • Log name :java.log

  • Minimum threshold to log :INFO

  • Flush severity :ERROR

The Cloud Logging library for Java batches messages by size and time since last write.Batches with logging requests at or above the flush severity are immediatelywritten out.

Note: If using the Cloud Logging library for Java API directly, there is no default logname or minimum threshold.

Monitored resource detection

All logs sent via the Cloud Logging libraries requireamonitored resource typeto identify your application.

The Logback appender and thejava.util.logging handler provide automaticresource type detection of your App Engine, Compute Engine, and Google Kubernetes Engineapplications.

Aglobal monitored resource is used as the default in other environments.

You can override the monitored resource type to avalid typein theLogback appender Configurationor thejava.util.logging Handler Configuration.

Note: If using the Cloud Logging API directly, you must provide a validmonitored resource type when logging using the API.

Additional fields and labels

Using the Logback appender and thejava.util.logging handler, you can add orupdate fields on aLogEntry object usingan instance ofLoggingEnhancer.

The enhancers must be configured as shown in theLogback appender configuration or thejava.util.logging handler configuration:

importcom.google.cloud.logging.LogEntry;importcom.google.cloud.logging.LoggingEnhancer;// Add / update additional fields to the log entrypublicclassExampleEnhancerimplementsLoggingEnhancer{@OverridepublicvoidenhanceLogEntry(LogEntry.BuilderlogEntry){// add additional labelslogEntry.addLabel("test-label-1","test-value-1");}}

Use of custom labels might not be supported for your configuration. For example,Dataflow logs don't include these labels.

For more information on installation, see thedocumentation for theCloud Logging library for Java. You can also report issues using theissue tracker.

Write logs with the Cloud Logging client library

For information on using the Cloud Logging client library forJava directly, seeCloud Logging Client Libraries.

Run on Google Cloud

For an application to write logs by using the Cloud Logging library for Java, theservice account for the underlying resource must have theLogs Writer (roles/logging.logWriter)IAM role.Most Google Cloud environments automatically configure the defaultservice account to have this role.

App Engine

Cloud Logging is automatically enabled for App Engine, and your app'sdefault service account hasthe IAM permissions by default to write log entries.

App Engine standard environment, bydefault, uses thejava.util.logging.LoggerAPI; this writes to Cloud Logging directly and is easy to configure.

For further details, see App Engine documentation onReading and Writing Application Logs.

App Engine flexible environment

OnApp Engine flexible environment,java.util.logging uses theConsoleHandlerby default, and sends logs tostdout andstderr.

TheJetty Runtime is bundled withthe Cloud Logging library for Java.

Thejava.util.logging handler can be used to log directlyto Cloud Logging by providing thelogging.properties in yourapp.yamlas shown here:

    env_variables:      JETTY_ARGS: -Djava.util.logging.config.file=WEB-INF/logging.properties

Trace ID logging is available on Jetty runtimes if you are using thejava.util.logging handler or the Logback appender.

When running on App Engine flexible environment, aTraceLoggingEnhancer instance adds a thread-safe trace ID to every log entry using the labeltrace_id.

Google Kubernetes Engine (GKE)

GKE automatically grants the default service accounttheLogs Writer (roles/logging.logWriter) IAM role.If you useWorkload Identity Federation for GKEwith this default service account to let workloads access specificGoogle Cloud APIs, then no additional configuration is required.However, if you use Workload Identity Federation for GKE with acustom IAM service account, then ensure that the custom serviceaccount has the role of Logs Writer (roles/logging.logWriter).

If needed, you can also use the following command to add thelogging.writeaccess scope when creating the cluster:

gcloudcontainerclusterscreateexample-cluster-name\--scopeshttps://www.googleapis.com/auth/logging.write

Compute Engine

Note: To use the Cloud Logging library for Java on aCompute Engine VM instance,you do not need to install the Cloud Logging agent.

When usingCompute Engine VM instances, add thecloud-platformaccess scope to each instance. When creating a new instance through theGoogle Cloud console, you can do this in theIdentity and API access sectionof theCreate Instance panel. Use the Compute Engine default serviceaccount or another service account of your choice, and selectAllow full access to all Cloud APIs in theIdentity and API accesssection. Whichever serviceaccount you select, ensure that it has been granted theLogs Writer role in theIAM & Admin section of theGoogle Cloud console.

Run locally and elsewhere

To use the Cloud Logging library for Java outside of Google Cloud,including running the library on your own workstation, on your data center'scomputers, or on the VM instances of another cloud provider, you mustset up Application Default Credentials (ADC) in your local environment toauthenticate to the Cloud Logging library for Java.

For more information, seeSet up ADC for on-premises or another cloud provider.

View the logs

In the Google Cloud console, go to theLogs Explorer page:

Go toLogs Explorer

If you use the search bar to find this page, then select the result whose subheading isLogging.

In the Logs Explorer, you must specify one or more resources, but the resourceselection might not be obvious. Here are some tips to help you getstarted:

  • If you are deploying your application to App Engine or using theApp Engine-specific libraries, set your resource toGAE Application.

  • If you are deploying your application on Compute Engine, set the resourcetoGCE VM Instance.

  • If you are deploying your application on Google Kubernetes Engine, yourcluster's logging configuration determines the resource type of the logentries. For a detaileddiscussion on the Legacy Google Cloud Observability and the Google Cloud ObservabilityKubernetes Monitoring solutions, and how those options affect theresource type, seeMigrating to Google Cloud Observability Kubernetes Monitoring.

  • If your application is using the Cloud Logging API directly,the resource is dependent on the API and your configuration. For example,in your application, you can specify a resource or use a default resource.

  • If you don't see any logs in the Logs Explorer, to see all log entries,switch to the advanced query mode and use an empty query.

    1. To switch to the advanced query mode, clickmenu (▾)at the top of the Logs Explorer andthen selectConvert to advanced filter.
    2. Clear the content that appears in the filter box.
    3. ClickSubmit Filter.

    You can examine the individual entries to identify your resources.

For additional information, seeUsing the Logs Explorer.

Except as otherwise noted, the content of this page is licensed under theCreative Commons Attribution 4.0 License, and code samples are licensed under theApache 2.0 License. For details, see theGoogle Developers Site Policies. Java is a registered trademark of Oracle and/or its affiliates.

Last updated 2025-12-15 UTC.