- Notifications
You must be signed in to change notification settings - Fork28
Node.js library for Google Cloud Profiler. Continuous CPU and heap profiling to improve performance and reduce costs.
License
googleapis/cloud-profiler-nodejs
Folders and files
| Name | Name | Last commit message | Last commit date | |
|---|---|---|---|---|
Repository files navigation
Adds support for Cloud Profiler to Node.js applications
A comprehensive list of changes in each version may be found inthe CHANGELOG.
- Cloud Profiler Node.js Client API Reference
- Cloud Profiler Documentation
- github.com/googleapis/cloud-profiler-nodejs
Read more about the client libraries for Cloud APIs, including the olderGoogle APIs Client Libraries, inClient Libraries Explained.
Table of contents:
- Select or create a Cloud Platform project.
- Enable the Cloud Profiler API.
- Set up authentication so you can access theAPI from your local workstation.
npm install @google-cloud/profiler
Your application will need to be using Node.js version between 14 and 20.
@google-cloud/profilerdepends on thepprofmodule, a module with a nativecomponent that is used to collect profiles with v8's CPU and Heap profilers.You may need to install additional dependencies to build thepprofmodule.- For Linux:
pprofhas prebuilt binaries available for Linux and AlpineLinux for Node 14 and 16. No additional dependencies are required. - For other environments: when using
@google-cloud/profileron environmentsthatpprofdoes not have prebuilt binaries for, the modulenode-gypwill be used tobuild binaries. Seenode-gyp'sdocumentationfor information on dependencies required to build binaries withnode-gyp.
- For Linux:
You will need a project in the [Google Developers Console][cloud-console].Your application can run anywhere, but the profiler data is associated with aparticular project.
You will need to enable the Cloud Profiler API for your project.
Install
@google-cloud/profilerwithnpmor addto yourpackage.json.# Install through npm while saving to the local 'package.json'npm install --save @google-cloud/profilerInclude and start the profiler at the beginning of your application:
require('@google-cloud/profiler').start().catch((err)=>{console.log(`Failed to start profiler:${err}`);});
Some environments require a configuration to be passed to the
start()function. For more details on this, see instructions for runningoutside of Google Cloud Platform, onApp Engine flexible environment,onGoogle Compute Engine,and onGoogle Container Engine.If you are running your application locally, or on a machine where you areusing the [Google Cloud SDK][gcloud-sdk], make sure to log in with theapplication default credentials:
gcloud beta auth application-default login
Alternatively, you can set
GOOGLE_APPLICATION_CREDENTIALS. For moredetails on this, seeRunning elsewhere
Seethe default configuration for a list of possibleconfiguration options. These options can be passed to the agent through theobject argument to the start command shown below:
awaitrequire('@google-cloud/profiler').start({disableTime:true});
Alternatively, you can provide the configuration through a config file. Thiscan be useful if you want to load our module using--require on the commandline (which requires and starts the agent) instead of editing your main script.TheGCLOUD_PROFILER_CONFIG environment variable should point to yourconfiguration file.
export GCLOUD_PROFILER_CONFIG=./path/to/your/profiler/configuration.jsThe profiler writes log statements to the console log for diagnostic purposes.By default, the log level is set to warn. You can adjust this by settinglogLevel in the config. SettinglogLevel to 0 will disable logging,1 sets log level to error, 2 sets it to warn (default), 3 sets it to info,and 4 sets it to debug.
So, for example, to start the profiler with the log level at debug, you woulddo this:
awaitrequire('@google-cloud/profiler').start({logLevel:4});
By default, the profiler collects both heap profiles, which show memoryallocations, and time profiles, which capture how much wall-clock time is spentin different locations of the code. Using the configuration, it is possible todisable the collection of either type of profile.
To disable time profile collection, setdisableTime to true:
awaitrequire('@google-cloud/profiler').start({disableTime:true});
To disable heap profile collection, setdisableHeap to true:
awaitrequire('@google-cloud/profiler').start({disableHeap:true});
There are three different services that can host Node.js applications withinGoogle Cloud Platform: Google App Engine flexible environment, Google ComputeEngine, and Google Container Engine. After installing@google-cloud/profilerin your project and ensuring that the environment you are using uses asupported version of Node.js, follow the service-specific instructions toenable the profiler.
To enable the profiling agent for a Node.js program running in the App Engineflexible environment, import the agent at the top of your application’s mainscript or entry point by including the following code snippet:
require('@google-cloud/profiler').start();
You can specify which version of Node.js you're using by adding a snippet likethe following to yourpackage.json:
"engines": {"node":">=14.0.0"}
The above snippet will ensure that you're using 14.0.0 or greater.
Deploy your application to App Engine Flexible environment as usual.
To enable the profiling agent for a Node.js program running in the GoogleCompute Engine environment, import the agent at the top of your application’smain script or entry point by including the following code snippet:
require('@google-cloud/profiler').start({serviceContext:{service:'your-service',version:'1.0.0'}});
To enable the profiling agent for a Node.js program running in the GoogleContainer Engine environment, import the agent at the top of your application’smain script or entry point by including the following code snippet:
require('@google-cloud/profiler').start({serviceContext:{service:'your-service',version:'1.0.0'}});
On Istio, the GCP Metadata server may not be available for a few seconds afteryour application has started. When this occurs, the profiling agent may failto start because it cannot initialize required fields. One can retry whenstarting the profiler with the following snippet.
constprofiler=require('@google-cloud/profiler');asyncfunctionstartProfiler(){for(leti=0;i<3;i++){try{awaitprofiler.start({serviceContext:{service:'your-service',version:'1.0.0',},});}catch(e){console.log(`Failed to start profiler:${e}`);}// Wait for 1 second before trying again.awaitnewPromise(r=>setTimeout(r,1000));}}startProfiler();
You can still use@google-cloud/profiler if your application is runningoutside of Google Cloud Platform, for example, running locally, on-premise, oron another cloud provider.
- You will need to specify your project id and the service you want thecollected profiles to be associated with, and (optionally) the version ofthe service when starting the profiler:
awaitrequire('@google-cloud/profiler').start({projectId:'project-id',serviceContext:{service:'your-service',version:'1.0.0'}});
- You will need to provide credential for your application.
If you are running your application on a development machine or testenvironment where you are using the [
gcloudcommand line tools][gcloud-sdk],and are logged usinggcloud beta auth application-default login, youalready have sufficient credentials, and a service account key is notrequired.You can provide credentials via[Application Default Credentials][app-default-credentials]. This is therecommended method.1. [Create a new JSON service account key][service-account].2. Copy the key somewhere your application can access it. Be sure notto expose the key publicly.3. Set the environment variable
GOOGLE_APPLICATION_CREDENTIALStothe full path to the key. The profiler will automatically look forthis environment variable.You may set the
keyFilenameorcredentialsconfiguration field to thefull path or contents to the key file, respectively. Setting either of thesefields will override either settingGOOGLE_APPLICATION_CREDENTIALSorlogging in usinggcloud.This is how you would set
keyFilename:awaitrequire('@google-cloud/profiler').start({projectId:'project-id',serviceContext:{service:'your-service',version:'1.0.0'},keyFilename:'/path/to/keyfile'});
This is how you would set
credentials:awaitrequire('@google-cloud/profiler').start({projectId:'project-id',serviceContext:{service:'your-service',version:'1.0.0'},credentials:{client_email:'email',private_key:'private_key'}});
Samples are in thesamples/ directory. Each sample'sREADME.md has instructions for running its sample.
| Sample | Source Code | Try it |
|---|---|---|
| App | source code | ![]() |
| Snippets | source code | ![]() |
TheCloud Profiler Node.js Client API Reference documentationalso contains samples.
Our client libraries follow theNode.js release schedule.Libraries are compatible with all currentactive andmaintenance versions ofNode.js.If you are using an end-of-life version of Node.js, we recommend that you updateas soon as possible to an actively supported LTS version.
Google's client libraries support legacy versions of Node.js runtimes on abest-efforts basis with the following warnings:
- Legacy versions are not tested in continuous integration.
- Some security patches and features cannot be backported.
- Dependencies cannot be kept up-to-date.
Client libraries targeting some end-of-life versions of Node.js are available, andcan be installed through npmdist-tags.The dist-tags follow the naming conventionlegacy-(version).For example,npm install @google-cloud/profiler@legacy-8 installs client librariesfor versions compatible with Node.js 8.
This library followsSemantic Versioning.
This library is considered to bestable. The code surface will not change in backwards-incompatible waysunless absolutely necessary (e.g. because of critical security issues) or withan extensive deprecation period. Issues and requests againststable librariesare addressed with the highest priority.
More Information:Google Cloud Platform Launch Stages
Contributions welcome! See theContributing Guide.
Please note that thisREADME.md, thesamples/README.md,and a variety of configuration files in this repository (including.nycrc andtsconfig.json)are generated from a central template. To edit one of these files, make an editto its templates indirectory.
Apache Version 2.0
SeeLICENSE
About
Node.js library for Google Cloud Profiler. Continuous CPU and heap profiling to improve performance and reduce costs.
Resources
License
Code of conduct
Contributing
Security policy
Uh oh!
There was an error while loading.Please reload this page.
