Logging quickstart
Demonstration of how to write a log entry.
Explore further
For detailed documentation that includes this code sample, see the following:
Code sample
C#
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.
usingSystem;
// Imports the Google Cloud Logging client library
usingGoogle.Cloud.Logging.V2 ;
usingGoogle.Cloud.Logging.Type ;
usingSystem.Collections.Generic;
usingGoogle.Api ;
namespaceGoogleCloudSamples
{
publicclassQuickStart
{
publicstaticvoidMain(string[]args)
{
// Your Google Cloud Platform project ID.
stringprojectId="YOUR-PROJECT-ID";
// Instantiates a client.
varclient=LoggingServiceV2Client .Create ();
// Prepare new log entry.
LogEntry logEntry=newLogEntry ();
stringlogId="my-log";
LogName logName=newLogName (projectId,logId);
logEntry.LogNameAsLogName =logName;
logEntry.Severity =LogSeverity .Info ;
// Create log entry message.
stringmessage="Hello World!";
stringmessageId=DateTime.Now.Millisecond.ToString();
TypemyType=typeof(QuickStart);
stringentrySeverity=logEntry.Severity .ToString().ToUpper();
logEntry.TextPayload =
$"{messageId} {entrySeverity} {myType.Namespace}.LoggingSample - {message}";
// Set the resource type to control which GCP resource the log entry belongs to.
// See the list of resource types at:
// https://cloud.google.com/logging/docs/api/v2/resource-list
// This sample uses resource type 'global' causing log entries to appear in the
// "Global" resource list of the Developers Console Logs Viewer:
// https://console.cloud.google.com/logs/viewer
MonitoredResource resource=newMonitoredResource
{
Type="global"
};
// Create dictionary object to add custom labels to the log entry.
IDictionary<string,string>entryLabels=newDictionary<string,string>();
entryLabels.Add ("size","large");
entryLabels.Add ("color","red");
// Add log entry to collection for writing. Multiple log entries can be added.
IEnumerable<LogEntry>logEntries=newLogEntry []{logEntry};
// Write new log entry.
client.WriteLogEntries(logName,resource,entryLabels,logEntries);
Console.WriteLine("Log Entry created.");
}
}
}
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 logging-quickstart writes a log entry to Cloud Logging.
packagemain
import(
"context"
"fmt"
"log"
"cloud.google.com/go/logging"
)
funcmain(){
ctx:=context.Background()
// Sets your Google Cloud Platform project ID.
projectID:="YOUR_PROJECT_ID"
// Creates a client.
client,err:=logging.NewClient(ctx,projectID)
iferr!=nil{
log.Fatalf("Failed to create client: %v",err)
}
// Sets the name of the log to write to.
logName:="my-log"
// Selects the log to write to.
logger:=client.Logger(logName)
// Sets the data to log.
text:="Hello, world!"
// Adds an entry to the log buffer.
logger.Log (logging.Entry {Payload:text})
// Closes the client and flushes the buffer to the Cloud Logging
// service.
iferr:=client.Close();err!=nil{
log.Fatalf("Failed to close client: %v",err)
}
fmt.Printf("Logged: %v\n",text)
}
Java
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.
importcom.google.cloud.MonitoredResource ;
importcom.google.cloud.logging.LogEntry ;
importcom.google.cloud.logging.Logging ;
importcom.google.cloud.logging.LoggingOptions ;
importcom.google.cloud.logging.Payload.StringPayload;
importcom.google.cloud.logging.Severity ;
importjava.util.Collections;
/**
* This sample demonstrates writing logs using the Cloud Logging API. The library also offers a
* java.util.logging Handler `com.google.cloud.logging.LoggingHandler` Logback integration is also
* available :
* https://github.com/googleapis/google-cloud-java/tree/master/google-cloud-clients/google-cloud-contrib/google-cloud-logging-logback
* Using the java.util.logging handler / Logback appender should be preferred to using the API
* directly.
*/
publicclass QuickstartSample{
/** Expects a new or existing Cloud log name as the first argument. */
publicstaticvoidmain(String ...args)throwsException{
// The name of the log to write to
String logName=args[0];// "my-log";
String textPayload="Hello, world!";
// Instantiates a client
try(Logging logging=LoggingOptions .getDefaultInstance().getService()){
LogEntry entry=
LogEntry .newBuilder(StringPayload.of(textPayload))
.setSeverity(Severity .ERROR)
.setLogName(logName)
.setResource(MonitoredResource .newBuilder("global").build())
.build();
// Writes the log entry asynchronously
logging.write(Collections.singleton(entry));
// Optional - flush any pending log entries just before Logging is closed
logging.flush();
}
System.out.printf("Logged: %s%n",textPayload);
}
}Node.js
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 Google Cloud client library
const{Logging}=require('@google-cloud/logging');
asyncfunctionquickstart(
projectId='YOUR_PROJECT_ID',// Your Google Cloud Platform project ID
logName='my-log'// The name of the log to write to
){
// Creates a client
constlogging=newLogging ({projectId});
// Selects the log to write to
constlog=logging.log(logName);
// The data to write to the log
consttext='Hello, world!';
// The metadata associated with the entry
constmetadata={
resource:{type:'global'},
// See: https://cloud.google.com/logging/docs/reference/v2/rest/v2/LogEntry#logseverity
severity:'INFO',
};
// Prepares a log entry
constentry=log.entry(metadata,text);
asyncfunctionwriteLog(){
// Writes the log entry
awaitlog.write(entry);
console.log(`Logged: ${text}`);
}
writeLog();
}PHP
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.
# Includes the autoloader for libraries installed with composer
require __DIR__ . '/vendor/autoload.php';
# Imports the Google Cloud client library
use Google\Cloud\Logging\LoggingClient;
# Your Google Cloud Platform project ID
$projectId = 'YOUR_PROJECT_ID';
# Instantiates a client
$logging = new LoggingClient([
'projectId' => $projectId
]);
# Selects the log to write to
$logger = $logging->logger('my-log');
# The data to log
$text = 'Hello, world!';
# Creates and writes the log entry
$entry = $logger->entry($text);
$logger->write($entry);
echo 'Logged ' . $text;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 Google Cloud client library
fromgoogle.cloudimport logging
# Instantiates a client
logging_client = logging.Client ()
# The name of the log to write to
log_name = "my-log"
# Selects the log to write to
logger = logging_client.logger (log_name)
# The data to log
text = "Hello, world!"
# Writes the log entry
logger.log_text(text)
print("Logged: {}".format(text))Ruby
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 Google Cloud client library
require"google/cloud/logging"
# Instantiates a client
logging=Google::Cloud::Logging .new
# Prepares a log entry
entry=logging.entry
# payload = "The data you want to log"
entry.payload =payload
# log_name = "The name of the log to write to"
entry.log_name=log_name
# The resource associated with the data
entry.resource.type="global"
# Writes the log entry
logging.write_entriesentry
puts"Logged #{entry.payload }"What's next
To search and filter code samples for other Google Cloud products, see the Google Cloud sample browser.