Write standard logs

Demonstrates how to use Cloud Logging in a standard library-compatible way.

Explore further

For detailed documentation that includes this code sample, see the following:

Code sample

Go

To learn how to install and use the client library for Logging, see Logging client libraries .

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  // Sample stdlogging writes log.Logger logs to the Cloud Logging. 
 package 
  
 main 
 import 
  
 ( 
  
 "context" 
  
 "log" 
  
 "cloud.google.com/go/logging" 
 ) 
 func 
  
 main 
 () 
  
 { 
  
 ctx 
  
 := 
  
 context 
 . 
 Background 
 () 
  
 // Sets your Google Cloud Platform project ID. 
  
 projectID 
  
 := 
  
 "YOUR_PROJECT_ID" 
  
 // Creates a client. 
  
 client 
 , 
  
 err 
  
 := 
  
 logging 
 . 
 NewClient 
 ( 
 ctx 
 , 
  
 projectID 
 ) 
  
 if 
  
 err 
  
 != 
  
 nil 
  
 { 
  
 log 
 . 
 Fatalf 
 ( 
 "Failed to create client: %v" 
 , 
  
 err 
 ) 
  
 } 
  
 defer 
  
 client 
 . 
 Close 
 () 
  
 // Sets the name of the log to write to. 
  
 logName 
  
 := 
  
 "my-log" 
  
 logger 
  
 := 
  
 client 
 . 
 Logger 
 ( 
 logName 
 ). 
  StandardLogger 
 
 ( 
 logging 
 . 
  Info 
 
 ) 
  
 // Logs "hello world", log entry is visible at 
  
 // Cloud Logs. 
  
 logger 
 . 
 Println 
 ( 
 "hello world" 
 ) 
 } 
 

Python

To learn how to install and use the client library for Logging, see Logging client libraries .

To authenticate to Logging, set up Application Default Credentials. For more information, see Set up authentication for a local development environment .

  # Imports the Cloud Logging client library 
 import 
  
 google.cloud.logging 
 # Instantiates a client 
 client 
 = 
 google 
 . 
 cloud 
 . 
 logging 
 . 
  Client 
 
 () 
 # Retrieves a Cloud Logging handler based on the environment 
 # you're running in and integrates the handler with the 
 # Python logging module. By default this captures all logs 
 # at INFO level and higher 
 client 
 . 
  setup_logging 
 
 () 
 # Imports Python standard library logging 
 import 
  
 logging 
 # The data to log 
 text 
 = 
 "Hello, world!" 
 # Emits the data using the standard logging module 
 logging 
 . 
 warning 
 ( 
 text 
 ) 
 print 
 ( 
 "Logged: 
 {} 
 " 
 . 
 format 
 ( 
 text 
 )) 
 

What's next

To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser .

Design a Mobile Site
View Site in Mobile | Classic
Share by: