Stackdriver Logging
The Stackdriver Logging service collects and stores logs from applications andservices on the Google Cloud Platform, giving you fine-grained, programmaticcontrol over your projects' logs. You can use the Stackdriver Logging API to:
- Read and filter log entries
- Export your log entries to Cloud Storage,BigQuery, or Cloud Pub/Sub
- Create logs-based metrics for use inCloud Monitoring
- Write log entries
For general information about Stackdriver Logging, readStackdriver LoggingDocumentation.
The goal of google-cloud is to provide an API that is comfortable to Rubyists.Your authentication credentials are detected automatically in Google CloudPlatform (GCP), including Google Compute Engine (GCE), Google Kubernetes Engine(GKE), Google App Engine (GAE), Google Cloud Functions (GCF) and Cloud Run. Inother environments you can configure authentication easily, either directly inyour code or via environment variables. Read more about the options forconnecting in theAuthentication Guide.
Listing log entries
Stackdriver Logging gathers log entries from many services, including Google AppEngine and Google Compute Engine. (See theList of LogTypes.) In addition, youcan write your own log entries to the service.
Project#entries returns theEntry records belonging to your project:
require"google/cloud/logging"logging=Google::Cloud::Logging.newentries=logging.entriesentries.eachdo|e|puts"[#{e.timestamp}]#{e.log_name}#{e.payload.inspect}"end
You can narrow the results to a single log using anadvanced logsfilter. A log is anamed collection of entries. Logs can be produced by Google Cloud Platformservices, by third-party services, or by your applications. For example, the logcompute.googleapis.com/activity_log is produced by Google Compute Engine. Logsare simply referenced by name in google-cloud. There is noLog type ingoogle-cloud orLog resource in the Stackdriver Logging API.
require"google/cloud/logging"logging=Google::Cloud::Logging.newentries=logging.entriesfilter:"logName:syslog"entries.eachdo|e|puts"[#{e.timestamp}]#{e.payload.inspect}"end
You can also order the log entries bytimestamp.
require"google/cloud/logging"logging=Google::Cloud::Logging.newentries=logging.entriesorder:"timestamp desc"entries.eachdo|e|puts"[#{e.timestamp}]#{e.log_name}"end
Exporting log entries
Stackdriver Logging lets you export log entries to destinations including GoogleCloud Storage buckets (for long term log storage), Google BigQuery datasets (forlog analysis), and Google Pub/Sub (for streaming to other applications).
Creating sinks
ASink is an object that lets you to specify aset of log entries to export.
In addition to the name of the sink and the export destination,Project#create_sink accepts anadvanced logsfilter to narrowthe collection.
Before creating the sink, ensure that you have grantedcloud-logs@google.compermission to write logs to the destination. SeeExporting Logs(V2).
require"google/cloud/storage"require"google/cloud/logging"storage=Google::Cloud::Storage.newbucket=storage.create_bucket"my-logs-bucket"# Grant owner permission to Stackdriver Logging serviceemail="cloud-logs@google.com"bucket.acl.add_owner"group-#{email}"logging=Google::Cloud::Logging.newsink=logging.create_sink"my-sink","storage.googleapis.com/#{bucket.id}"
When you create a sink, only new log entries are exported. Stackdriver Loggingdoes not send previously-ingested log entries to the sink's destination.
Listing sinks
You can also list the sinks belonging to your project withProject#sinks.
require"google/cloud/logging"logging=Google::Cloud::Logging.newsinks=logging.sinkssinks.eachdo|s|puts"#{s.name}:#{s.filter} ->#{s.destination}"end
Creating logs-based metrics
You can use log entries in your project as the basis forGoogle CloudMonitoring metrics. These metrics canthen be used to produce Cloud Monitoring reports and alerts.
Creating metrics
A metric is a measured value that can be used to assess a system. UseProject#create_metric toconfigure aMetric based on a collection oflog entries matching anadvanced logsfilter.
require"google/cloud/logging"logging=Google::Cloud::Logging.newmetric=logging.create_metric"errors","severity>=ERROR"
Listing metrics
You can also list the metrics belonging to your project withProject#metrics.
require"google/cloud/logging"logging=Google::Cloud::Logging.newmetrics=logging.metricsmetrics.eachdo|m|puts"#{m.name}:#{m.filter}"end
Writing log entries
AnGoogle::Cloud::Logging::Entry is composed of metadata and a payload. Thepayload is traditionally a message string, but in Stackdriver Logging it canalso be a JSON or protocol buffer object. A single log can have entries withdifferent payload types. In addition to the payload, your argument(s) toProject#write_entries must alsocontain a log name and a resource.
require"google/cloud/logging"logging=Google::Cloud::Logging.newentry=logging.entryentry.payload="Job started."entry.log_name="my_app_log"entry.resource.type="gae_app"entry.resource.labels[:module_id]="1"entry.resource.labels[:version_id]="20150925t173233"logging.write_entriesentry
To write a JSON payload to the log, simply pass a hash argument:
require"google/cloud/logging"logging=Google::Cloud::Logging.newentry=logging.entryentry.payload={"stats"=>{"a"=>8,"b"=>12.5}}entry.log_name="my_app_log"entry.resource.type="gae_app"entry.resource.labels[:module_id]="1"entry.resource.labels[:version_id]="20150925t173233"logging.write_entriesentry
If you write a collection of log entries, you can provide the log name,resource, and/or labels hash to be used for all of the entries, and omit thesevalues from the individual entries.
require"google/cloud/logging"logging=Google::Cloud::Logging.newentry1=logging.entryentry1.payload="Job started."entry2=logging.entryentry2.payload="Job completed."labels={job_size:"large",job_code:"red"}resource=logging.resource"gae_app","module_id"=>"1","version_id"=>"20150925t173233"logging.write_entries[entry1,entry2],log_name:"my_app_log",resource:resource,labels:labels
Normally, writing log entries is done synchronously; the call toProject#write_entries will blockuntil it has either completed transmitting the data or encountered an error. To"fire and forget" without blocking, useAsyncWriter; it spins up a background thread that writes log entries inbatches. Calls toAsyncWriter#write_entries simply add entries to its work queue and returnimmediately.
require"google/cloud/logging"logging=Google::Cloud::Logging.newasync=logging.async_writerentry1=logging.entryentry1.payload="Job started."entry2=logging.entryentry2.payload="Job completed."labels={job_size:"large",job_code:"red"}resource=logging.resource"gae_app","module_id"=>"1","version_id"=>"20150925t173233"async.write_entries[entry1,entry2],log_name:"my_app_log",resource:resource,labels:labels,partial_success:true
Creating a Ruby Logger implementation
If your environment requires a logger instance that is API-compatible withRuby's standard libraryLogger,you can useProject#logger to createone.
require"google/cloud/logging"logging=Google::Cloud::Logging.newresource=logging.resource"gae_app",module_id:"1",version_id:"20150925t173233"logger=logging.logger"my_app_log",resource,env::productionlogger.info"Job started."
By default, the logger instance writes log entries asynchronously in abackground thread using anAsyncWriter. Ifyou want to customize or disable asynchronous writing, you may call the Loggerconstructor directly.
require"google/cloud/logging"logging=Google::Cloud::Logging.newresource=logging.resource"gae_app",module_id:"1",version_id:"20150925t173233"logger=Google::Cloud::Logging::Logger.newlogging,"my_app_log",resource,{env::production}logger.info"Log entry written synchronously."
Configuring timeout
You can configure the requesttimeout value in seconds.
require"google/cloud/logging"logging=Google::Cloud::Logging.newtimeout:120
Additional information
Stackdriver Logging can be configured to be used in Rack applications or to usegRPC's logging. To learn more, see theInstrumentation Guide andLogging guide.
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-11-04 UTC.