Setting up on Compute Engine
Stay organized with collections
Save and categorize content based on your preferences.
You can send errors from your Compute Engine applications to Error Reporting in one of two ways:
By logging to Cloud Logging. If you're already using Cloud Logging, the only additional requirement is that your log entries be recognizable by Error Reporting. For more information on error formatting requirements, read Formatting errors in Cloud Logging.
Using the Error Reporting API. Your application can send HTTP requests using the REST API, or can make use of experimental libraries in several languages.
Using Logging to report errors
To connect your Compute Engine applications to Error Reporting, send your exceptions or other errors to Logging.
For example:
- Install the Logging
google-fluentdagent as is appropriate for your environment. For instructions, see Installing the Logging agent. Modify your application so that it logs exceptions and their stack traces to Logging.
You must include all the information for a single error or exception in the same log entry, including all the frames of any stack trace. If all the information isn't together, then Error Reporting might not detect the error. You can use the structured JSON format for your log entry payloads to include different kinds of information for each error.
Enable the Error Reporting API.
Roles required to enable APIs
To enable APIs, you need the Service Usage Admin IAM role (
roles/serviceusage.serviceUsageAdmin), which contains theserviceusage.services.enablepermission. Learn how to grant roles.Report errors to the API using either the REST API or a client library.
- Right-click your solution and select Manage NuGet packages for solution.
- Select the Include prerelease checkbox.
- Search for and install the package named
Google.Cloud.Diagnostics.AspNet.
Java
Add the following to your pom.xml file:
<dependency>
<groupId>org.fluentd</groupId>
<artifactId>fluent-logger</artifactId>
<version>0.3.4</version>
</dependency>Then use code like the following to send the exception data:
publicclass ExceptionUtil{
privatestaticFluentLoggerERRORS=FluentLogger.getLogger("myapp");
publicstaticvoidmain(String[]args){
try{
thrownewException("Generic exception for testing Stackdriver");
}catch(Exceptione){
report(e);
}
}
publicstaticvoidreport(Throwableex){
StringWriterexceptionWriter=newStringWriter();
ex.printStackTrace(newPrintWriter(exceptionWriter));
Map<String,Object>data=newHashMap<>();
data.put("message",exceptionWriter.toString());
Map<String,String>serviceContextData=newHashMap<>();
serviceContextData.put("service","myapp");
data.put("serviceContext",serviceContextData);
// ... add more metadata
ERRORS.log("errors",data);
}
}Python
First, install the
fluent-logger-python library:
sudo pip install fluent-logger
Then use code like the following to send the exception data:
importtraceback
importfluent.event
importfluent.sender
defsimulate_error():
fluent.sender.setup("myapp", host="localhost", port=24224)
defreport(ex):
data = {}
data["message"] = "{0}".format(ex)
data["serviceContext"] = {"service": "myapp"}
# ... add more metadata
fluent.event.Event("errors", data)
# report exception data using:
try:
# simulate calling a method that's not defined
raise NameError
except Exception:
report(traceback.format_exc())
Node.js
First, install the
fluent-logger-node library:
npminstallfluent-logger
Then use code like the following to send the exception data:
conststructuredLogger=require('fluent-logger').createFluentSender('myapp',{
host:'localhost',
port:24224,
timeout:3.0,
});
constreport=(err,req)=>{
constpayload={
serviceContext:{
service:'myapp',
},
message:err.stack,
context:{
httpRequest:{
url:req.originalUrl,
method:req.method,
referrer:req.header('Referer'),
userAgent:req.header('User-Agent'),
remoteIp:req.ip,
responseStatusCode:500,
},
},
};
structuredLogger.emit('errors',payload);
};
// Handle errors (the following uses the Express framework)
// eslint-disable-next-line no-unused-vars
app.use((err,req,res,next)=>{
report(err,req);
res.status(500).send(err.response||'Something broke!');
});Go
First, install the
fluent-logger-golang package:
gogetgithub.com/fluent/fluent-logger-golang/
Then use code like the following to send error data:
packagemain
import(
"log"
"net/http"
"os"
"runtime"
"github.com/fluent/fluent-logger-golang/fluent"
)
varlogger*fluent.Fluent
funcmain(){
varerrerror
logger,err=fluent.New(fluent.Config{
FluentHost:"localhost",
FluentPort:24224,
})
iferr!=nil{
log.Fatal(err)
}
http.HandleFunc("/demo",demoHandler)
port:=os.Getenv("PORT")
ifport==""{
port="8080"
}
log.Printf("Listening on port %s",port)
iferr:=http.ListenAndServe(":"+port,nil);err!=nil{
log.Fatal(err)
}
}
funcreport(stackTracestring,r*http.Request){
payload:=map[string]interface{}{
"serviceContext":map[string]interface{}{
"service":"myapp",
},
"message":stackTrace,
"context":map[string]interface{}{
"httpRequest":map[string]interface{}{
"method":r.Method,
"url":r.URL.String(),
"userAgent":r.UserAgent(),
"referrer":r.Referer(),
"remoteIp":r.RemoteAddr,
},
},
}
iferr:=logger.Post("myapp.errors",payload);err!=nil{
log.Print(err)
}
}
// Handler for the incoming requests.
funcdemoHandler(whttp.ResponseWriter,r*http.Request){
// How to handle a panic.
deferfunc(){
ife:=recover();e!=nil{
stack:=make([]byte,1<<16)
stackSize:=runtime.Stack(stack,true)
report(string(stack[:stackSize]),r)
}
}()
// Panic is triggered.
x:=0
log.Println(100500/x)
}
Using the Error Reporting API to write errors
The Error Reporting API provides a report endpoint for writing
error information to the service.
Samples
ASP.NET
The ASP.NET NuGet package reports uncaught exceptions from ASP.NET web applications to Error Reporting.
Install the NuGet package
To install the Stackdriver ASP.NET NuGet package in Visual Studio:
Usage
Once you've installed the Stackdriver ASP.NET NuGet package, add the following statement to your application code to start sending errors to Stackdriver:
using Google.Cloud.Diagnostics.AspNet;
Add the following HttpConfiguration code to the Register method of your
.NET web app (replacing your-project-id with your actual
project ID
to enable the reporting of exceptions:
publicstaticvoidRegister(HttpConfigurationconfig)
{
stringprojectId="YOUR-PROJECT-ID";
stringserviceName="NAME-OF-YOUR-SERVICE";
stringversion="VERSION-OF-YOUR-SERVCICE";
// ...
// Add a catch all for the uncaught exceptions.
config.Services.Add(typeof(IExceptionLogger),
ErrorReportingExceptionLogger.Create(projectId,serviceName,version));
// ...
}
Once you've added this method to your ASP.NET application, you can view any uncaught exceptions that occur as they get reported to Google Cloud in the Error Reporting section of the Google Cloud console.
C#
The following example can be found in the GoogleCloudPlatform/dotnet-docs-samples repo. To use it, after building the project, specify your project ID:
C:\...\bin\Debug>setGOOGLE_PROJECT_ID=[YOUR_PROJECT_ID]
Make sure to replace [YOUR_PROJECT_ID] with the correct value from the
Google Cloud console.
Then, send exception data with code similar to the following:
publicclassErrorReportingSample
{
publicstaticvoidMain(string[]args)
{
try
{
thrownewException("Generic exception for testing Stackdriver Error Reporting");
}
catch(Exceptione)
{
report(e);
Console.WriteLine("Stackdriver Error Report Sent");
}
}
/// <summary>
/// Create the Error Reporting service (<seealso cref="ClouderrorreportingService"/>)
/// with the Application Default Credentials and the proper scopes.
/// See: https://developers.google.com/identity/protocols/application-default-credentials.
/// </summary>
privatestaticClouderrorreportingServiceCreateErrorReportingClient()
{
// Get the Application Default Credentials.
GoogleCredentialcredential=GoogleCredential.GetApplicationDefaultAsync().Result;
// Add the needed scope to the credentials.
credential.CreateScoped(ClouderrorreportingService.Scope.CloudPlatform);
// Create the Error Reporting Service.
ClouderrorreportingServiceservice=newClouderrorreportingService(newBaseClientService.Initializer
{
HttpClientInitializer=credential,
});
returnservice;
}
/// <summary>
/// Creates a <seealso cref="ReportRequest"/> from a given exception.
/// </summary>
privatestaticReportRequestCreateReportRequest(Exceptione)
{
// Create the service.
ClouderrorreportingServiceservice=CreateErrorReportingClient();
// Get the project ID from the environement variables.
stringprojectId=Environment.GetEnvironmentVariable("GOOGLE_PROJECT_ID");
// Format the project id to the format Error Reporting expects. See:
// https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events/report
stringformattedProjectId=string.Format("projects/{0}",projectId);
// Add a service context to the report. For more details see:
// https://cloud.google.com/error-reporting/reference/rest/v1beta1/projects.events#ServiceContext
ServiceContextserviceContext=newServiceContext()
{
Service="myapp",
Version="8c1917a9eca3475b5a3686d1d44b52908463b989",
};
ReportedErrorEventerrorEvent=newReportedErrorEvent()
{
Message=e.ToString(),
ServiceContext=serviceContext,
};
returnnewReportRequest(service,errorEvent,formattedProjectId);
}
/// <summary>
/// Report an exception to the Error Reporting service.
/// </summary>
privatestaticvoidreport(Exceptione)
{
// Create the report and execute the request.
ReportRequestrequest=CreateReportRequest(e);
request.Execute();
}
}Go
Java
Node.js
Ruby
Python
PHP
View error groups
In the Google Cloud console, go to the Error Reporting page:
You can also find this page by using the search bar.