Logging and viewing logs in Cloud Run

This page describes the logs available when using Cloud Run, and how to viewand write logs.

Cloud Run has several types of logs, and these are automaticallysent toCloud Logging:

  • Request logs (services only): logs of requests sent to Cloud Run services. These logsare created automatically.
  • Container logs (services, jobs, and worker pools): logs emitted from the instances, typically from yourown code, written to supported locations as described inWriting container logs.
  • System logs (services, jobs, and worker pools): platform-generated logs containing information aboutyour workloads. These logs are written tovarlog/system.

View logs

You can view logs for your service, job, or worker pool in several ways:

Both of the console methods of viewing logs examine the same logs stored inCloud Logging, but the Cloud Logging Logs Explorer providesmore details and more filtering capabilities.

View logs in Cloud Run

You can view logs in the Cloud Run page for the following resources:

View logs for a service

To view service logs in the Cloud Run page:

  1. Go to Cloud Run

  2. Click the service in the displayed list.

  3. Click theLOGS tab to get the request and container logs for allrevisions of this service. You can filter by log severity level.

View logs for a job

To view job logs in the Cloud Run page:

  1. Go to Cloud Run

  2. Locate the job in the jobs list, and click on it.

  3. Click theLOGS tab to get the container logs for allexecutions of this job. You can filter by log severity level.

  4. Alternatively, if you want to see the logs pre-filtered for a specific jobexecution, click on the job execution and then click theLOGS tab.

View logs for a worker pool

To view worker pool logs in the Cloud Run page:

  1. Go to Cloud Run

  2. Click the worker pool in the displayed list.

  3. Click theLOGS tab to get the request and container logs for allrevisions of this worker pool. You can filter by log severity level.

View service logs using Google Cloud CLI

You can use Google Cloud CLI to view tailing logs or read existing logsfor a Cloud Run service in the command lineBy default, the logs are formatted in a single-line format optimized for the console.

To tail logs, you need to install thelog-streaming component inGoogle Cloud CLI. If the component isn't installed, you will be promptedto install it when required.

View tailing logs in the command line

Preview — Command-line log tail for Cloud Run services

This feature is subject to the "Pre-GA Offerings Terms" in the General Service Terms section of theService Specific Terms. Pre-GA features are available "as is" and might have limited support. For more information, see thelaunch stage descriptions.

For a Cloud Runservice, you can tail logs in real-time from yourCloud Run service directly in the command-line:

gcloudbetarunserviceslogstailSERVICE--projectPROJECT-ID

Replace:

  • SERVICE with the name of the Cloud Run service.
  • PROJECT-ID with the Google Cloud project ID. You can view yourproject ID by running the commandgcloud config get-value project.

Read logs in the command line

For a Cloud Runservice, you can read existing logs in either of two ways:

  • In a console-optimized format:
    gcloudrunserviceslogsreadSERVICE--limit=10--projectPROJECT-ID
  • Directly from Cloud Logging:
    gcloudloggingread"resource.type=cloud_run_revision AND resource.labels.service_name=SERVICE"--projectPROJECT-ID--limit10

Replace:

  • SERVICE with the name of the Cloud Run service.
  • PROJECT-ID with the Google Cloud project ID. You can view yourproject ID by running the commandgcloud config get-value project.

View logs in Cloud Logging

Note: Selecting a specific worker pool in the Log Fields pane is not implemented.To filter for a specific worker pool, add the following to the query:resource.labels.worker_pool_name="WORKER_POOL_NAME"

To view your Cloud Run logs in the Cloud Logging Logs Explorer:

  1. Go to the Logs Explorer page in theGoogle Cloud console:

    Go to the Logs Explorer page

  2. Select an existing Google Cloud project at the top of the page, orcreate a new project.

  3. Using the drop-down menus, select the resource:

    • Cloud Run Revision for a service
    • Cloud Run Job for a job
    • Cloud Run Worker Pool for a worker pool

For more information, seeUsing the Logs Explorer.

View service logs in Cloud Code

To view your logs inCloud Code,read theIntelliJ andVisual Studio Code guides.

Read logs programmatically

If you want to read the logs programmatically, you can use one of these methods:

Instance scaling logs format and contents

When new instances start for your Cloud Run service, Cloud Loggingincludes log entries under thevarlog/system log name explaining why eachinstance was created. The log entry follows this format:

Starting new instance. Reason:REASON -DESCRIPTION

The following table provides a breakdown of instance descriptions:

ReasonDescription
MANUAL_OR_CUSTOMER_MIN_INSTANCEInstance started because of customer-configuredminimum instances ormanual scaling.
AUTOSCALINGInstance started due to configured scaling factors (such as CPU utilization, request throughput, and so forth) or not enough existing capacity for current traffic.
DEPLOYMENT_ROLLOUTInstance started due to traffic shifting between revisions due to deployment, traffic split adjustment, or deployment health check.

Write container logs

When you write logs from your service, job, or worker pool, they will be picked up automatically byCloud Logging so long as the logs are written to any of theselocations:

Most developers are expected to write logs using standard output and standarderror.

The container logs written to these supported locations are automaticallyassociated with the Cloud Run service, revision, and location, theCloud Run worker pool, revision, and location, or withthe Cloud Run job.Exceptions contained in these logs are captured by and reported inError Reporting.

The integrated logging balances reliability and resource usage, and should workfor most applications. Writing log entries using integrated logging does notconsume quota for the number ofentries.write requests per minute of theCloud Logging API.

If your application has requirements for higher volumeor reliability, we recommend using the Cloud Logging API directly, either asa library within your application or as a separate sidecar container.

Use simple text vs structured JSON in logs

When you write logs, you can send a simple text string or send a single lineof serialized JSON, also called "structured" data. This is picked up andparsed by Cloud Logging and is placed intojsonPayload. Incontrast, the simple text message is placed intextPayload.

Write structured logs

The following snippet shows how to write structured log entries. It alsoshows how to correlate log messages with the corresponding request log.

Node.js

// Uncomment and populate this variable in your code:// const project = 'The project ID of your function or Cloud Run service';// Build structured log messages as an object.constglobalLogFields={};// Add log correlation to nest all log messages beneath request log in Log Viewer.// (This only works for HTTP-based invocations where `req` is defined.)if(typeofreq!=='undefined'){consttraceHeader=req.header('X-Cloud-Trace-Context');if(traceHeader &&project){const[trace]=traceHeader.split('/');globalLogFields['logging.googleapis.com/trace']=`projects/${project}/traces/${trace}`;}}// Complete a structured log entry.constentry=Object.assign({severity:'NOTICE',message:'This is the default display field.',// Log viewer accesses 'component' as 'jsonPayload.component'.component:'arbitrary-property',},globalLogFields);// Serialize to a JSON string and output.console.log(JSON.stringify(entry));

Python

# Uncomment and populate this variable in your code:# PROJECT = 'The project ID of your Cloud Run service';# Build structured log messages as an object.global_log_fields={}# Add log correlation to nest all log messages.# This is only relevant in HTTP-based contexts, and is ignored elsewhere.# (In particular, non-HTTP-based Cloud Functions.)request_is_defined="request"inglobals()or"request"inlocals()ifrequest_is_definedandrequest:trace_header=request.headers.get("X-Cloud-Trace-Context")iftrace_headerandPROJECT:trace=trace_header.split("/")global_log_fields["logging.googleapis.com/trace"]=f"projects/{PROJECT}/traces/{trace[0]}"# Complete a structured log entry.entry=dict(severity="NOTICE",message="This is the default display field.",# Log viewer accesses 'component' as jsonPayload.component'.component="arbitrary-property",**global_log_fields,)print(json.dumps(entry))

Go

The structure for each log entry is provided by anEntry type:

// Entry defines a log entry.typeEntrystruct{Messagestring`json:"message"`Severitystring`json:"severity,omitempty"`Tracestring`json:"logging.googleapis.com/trace,omitempty"`// Logs Explorer allows filtering and display of this as `jsonPayload.component`.Componentstring`json:"component,omitempty"`}// String renders an entry structure to the JSON format expected by Cloud Logging.func(eEntry)String()string{ife.Severity==""{e.Severity="INFO"}out,err:=json.Marshal(e)iferr!=nil{log.Printf("json.Marshal: %v",err)}returnstring(out)}

When an Entry struct is logged, theString method is called to marshal it to the JSON format expected by Cloud Logging:

funcinit(){// Disable log prefixes such as the default timestamp.// Prefix text prevents the message from being parsed as JSON.// A timestamp is added when shipping logs to Cloud Logging.log.SetFlags(0)}funcindexHandler(whttp.ResponseWriter,r*http.Request){// Uncomment and populate this variable in your code:// projectID = "The project ID of your Cloud Run service"// Derive the traceID associated with the current request.vartracestringifprojectID!=""{traceHeader:=r.Header.Get("X-Cloud-Trace-Context")traceParts:=strings.Split(traceHeader,"/")iflen(traceParts) >0 &&len(traceParts[0]) >0{trace=fmt.Sprintf("projects/%s/traces/%s",projectID,traceParts[0])}}log.Println(Entry{Severity:"NOTICE",Message:"This is the default display field.",Component:"arbitrary-property",Trace:trace,})fmt.Fprintln(w,"Hello Logger!")}

Java

Enable JSON logging withLogback andSLF4J by enabling theLogstash JSON Encoder in yourlogback.xml configuration.

// Build structured log messages as an object.ObjectglobalLogFields=null;// Add log correlation to nest all log messages beneath request log in Log Viewer.// TODO(developer): delete this code if you're creating a Cloud//                  Function and it is *NOT* triggered by HTTP.StringtraceHeader=req.headers("x-cloud-trace-context");if(traceHeader!=null &&project!=null){Stringtrace=traceHeader.split("/")[0];globalLogFields=kv("logging.googleapis.com/trace",String.format("projects/%s/traces/%s",project,trace));}// -- End log correlation code --// Create a structured log entry using key value pairs.// For instantiating the "logger" variable, see// https://cloud.google.com/run/docs/logging#run_manual_logging-javalogger.error("This is the default display field.",kv("component","arbitrary-property"),kv("severity","NOTICE"),globalLogFields);

Customize standard field names to exclude unwanted content from ingestion in the logs payload.For a list of field names and expected data formats seeUse the logging agent.

<configuration><appendername="jsonConsoleAppender"class="ch.qos.logback.core.ConsoleAppender">    <encoderdevsite-syntax-n">net.logstash.logback.encoder.LogstashEncoder">      <!-- Ignore default logging fields -->      <fieldNames>        <timestamp>[ignore]</timestamp>        <version>[ignore]</version>        <logger>[ignore]</logger>        <thread>[ignore]</thread>        <level>[ignore]</level>        <levelValue>[ignore]</levelValue>      </fieldNames>    </encoder>  </appender>  <root level="INFO">    <appender-ref ref="jsonConsoleAppender"/>  </root></configuration>

Special JSON fields in messages

When you provide a structured log as a JSON dictionary, some special fields arestripped from thejsonPayload and are written to the corresponding field inthe generatedLogEntry as described inthe documentation forspecial fields.

For example, if your JSON includes aseverity property, it is removed fromthejsonPayload and appears instead as the log entry'sseverity.Themessage property is used as the main display text of the log entry if present.For more on special properties read theLogging Resource sectionbelow.

Correlate your container logs with a request log (services only)

In the Logs Explorer, logs correlated by the sametrace areviewable in "parent-child" format: when you click on the triangleicon at the left of the request log entry, the container logs related to thatrequest show up nested under the request log.

Container logs are not automatically correlated to request logs unless you use aCloud Logging client library.To correlate container logs with request logs without using a client library,you can use a structured JSON log line that contains alogging.googleapis.com/trace field with the trace identifier extracted fromtheX-Cloud-Trace-Context header as shown in the above sample forstructured logging.

Control request log resource usage (services only)

Request logs are created automatically. Although you cannot control the amount ofrequest logs directly from Cloud Run, you can make use of thelogs exclusion feature fromCloud Logging.

A note about logging agents

If you've used Cloud Logging with certain Google Cloud products, such asCompute Engine, you may have used Cloud Logging logging agents.Cloud Run does not use logging agents because it has built-in supportfor log collection.

Logging resource names

The logging resource names for Cloud Run are:

Logging resources

Clicking on a log entry in the Logs Explorer opens up a JSONformatted log entry so you can drill down to the details you want.

All of the fields in a log entry, such as timestamps, severity, andhttpRequestare standard, and are described in the documentation for alog entry.

Cloud Run adds additional metadata, so you can identify the source of a log.This includes the (labels that you set on your Cloud Run service)and resource labels that are specific to Cloud Run.

Log entry fields for a service

The following is a list of fields that can be found in the log entry for aCloud Run service:

FieldValues and notes
LogEntry.labels.instanceIdThe instance that handled the request.
LogEntry.labels.run.googleapis.com/base_image_versionsThe base image version that the service uses. Only appears for services deployed from source and ifautomatic security updates is enabled.
LogEntry.labels.run.googleapis.com/cloud_event_idThe CloudEvent ID. Only appears for services receiving events from Eventarc.
LogEntry.labels.run.googleapis.com/cloud_event_sourceThe CloudEvent source. Only appears for services receiving events from Eventarc.
LogEntry.labels.mylabel,
LogEntry.labels.mysecondlabel
Thelabels that are set by you on the service.
LogEntry.logNameIdentifies the log, for example, request log, standard error, standard output, etc.
LogEntry.resource.labels.locationIdentifies the Google Cloud location of the service.
LogEntry.resource.labels.project_idThe project the service is deployed to.
LogEntry.resource.labels.revision_nameThe revision that served the request.
LogEntry.resource.labels.service_nameThe service that served the request.
LogEntry.resource.typecloud_run_revision. The Cloud Run resource type.

Here's an example request log entry for a Cloud Run service:

{httpRequest:{}insertId:"5c82b3d1000ece0000000000"labels:{instanceId:"00bf4bf00000fb59c906a00000c9e29c2c4e06dce91500000000056008d2b6460f163c0057b97b2345f2725fb2423ee5f0bafd36df887fdb1122371563cf1ff453717282afe000001"mylabel:"mylabelvalue"mysecondlabel:"mysecondlabelvalue"}logName:"projects/my-project/logs/run.googleapis.com%2Frequests"receiveTimestamp:"2019-03-08T18:26:25.981686167Z"resource:{labels:{configuration_name:"myservice"location:"europe-west1"project_id:"my-project"revision_name:"myservice-00002"service_name:"myservice"}type:"cloud_run_revision"}severity:"INFO"timestamp:"2019-03-08T18:26:25.970397Z"}

Log entry fields for jobs

The following is a list of fields that can be found in the log entry for aCloud Run job:

FieldValues and notes
LogEntry.labels.instanceIdThe instance.
LogEntry.labels.mylabel,

LogEntry.labels.mysecondlabel

Thelabels that are set by you on the job.
LogEntry.logNameIdentifies the log, for example, standard error, standard output, etc.
LogEntry.resource.labels.locationIdentifies the Google Cloud location of the job.
LogEntry.resource.labels.project_idThe project the job is deployed to.
LogEntry.resource.labels.job_nameThe name of the job.
LogEntry.labels.execution_nameThe name of the job execution.
LogEntry.labels.task_indexThe task index.
LogEntry.labels.task_attemptHow many times this task has been attempted.
LogEntry.resource.typecloud_run_job. The Cloud Run resource type.

Log entry fields for worker pools

The following is a list of fields that can be found in the log entry for aCloud Run worker pool:

FieldValues and notes
LogEntry.labels.instanceIdThe instance.
LogEntry.labels.mylabel,

LogEntry.labels.mysecondlabel

Thelabels that are set by you on the worker pool.
LogEntry.logNameIdentifies the log, for example, standard error, standard output, etc.
LogEntry.resource.labels.locationThe Google Cloud location of the worker pool.
LogEntry.resource.labels.project_idThe project the worker pool is deployed to.
LogEntry.resource.labels.workerpool_nameThe name of the worker pool.
LogEntry.resource.typecloud_run_workerpool. The Cloud Run resource type.

What's Next

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 2026-02-19 UTC.