Google Cloud Run
This guide walks you through instrumenting Google Cloud Run with Middleware APMs (Application Performance Monitoring). These instructions can also be found on the Installation page in your Middleware Account.
Introduction
Middleware Application Performance Monitoring (APMs) with Google Cloud Run enables tracing and monitoring for applications. This integration provides valuable insights into application performance and behavior, enhancing observability in a Cloud Run environment.
Prerequisites
- Node.js 18 +: Verify with
node --version
Features Supported
Traces | Metrics | App Logs | Custom Logs | Profiling |
---|---|---|---|---|
✅ | ✅ | ✅ | ✅ | ✅ |
Installation
1 Install Node.js
APM Package
Run the following command in your terminal:
shell
npm install @middleware.io/node-apm --save
Make sure to include this package in your package.json file for Google Cloud Run deployment.
2 Setup Options
Method 1: Direct Code Initialization
Add the following lines to the beginning of your application code base. The access token is your account key, which can be found on the Installation page.
index.js
const tracker = require('@middleware.io/node-apm'); tracker.track({ serviceName: "your-service-name", accessToken: "<MW_API_KEY>", target: "https://<MW_UID>.middleware.io:443", }); // must come before importing any other module. // At the very top of the entrypoint const express = require('express'); // other dependencies
Method 2: Add the tracker with command line arguments
Create a file named instrument.js or instrument.ts
in your project root:
instrument.js
// instrument.js const tracker = require('@middleware.io/node-apm'); tracker.track({ serviceName: "your-service-name", accessToken: "<MW_API_KEY>", target: "https://<MW_UID>.middleware.io:443", });
To ensure the tracker is initialized before any other code runs, use the --require
flag when starting your Node.js application:
Shell
node --require ./instrument.js your-main-app.js
If --require doesn't work which means app uses ESM modules, use --import or --loader instead of --require.
3 Add ENV Variables and Deploy to Google Cloud Run
Deploy your application to Google Cloud Run. The APM tracker will start automatically with the application.
Ensure your Dockerfile or deployment script installs the APM package and includes the correct entry point for initialization.
Add this environment variable to allow comprehensive collection of metadata about the application's runtime Environment Add ENV Variables and Deploy to Google Cloud Run
OTEL_NODE_RESOURCE_DETECTORS=all
4 Handle missing spans
In serverless environments like Google Cloud Run, you may encounter missing spans due to sudden instance termination. To mitigate this, you have two options:
OTEL_BSP_SCHEDULE_DELAY=500
This sets the delay to 500 ms (adjust as needed). A lower value means more frequent data exports, potentially reducing missing spans at the cost of slightly increased network usage.
This ensures that all pending telemetry is flushed and connections are closed gracefully before the application shuts down signal SIGTERM
or SIGNINT
.
const tracker = require('@middleware.io/node-apm'); // Initialize the tracker tracker.track({ // Your configuration options }); // Handle application shutdown process.on('SIGTERM', async () => { console.log('SIGTERM signal received. Shutting down gracefully');
5 Add Custom Instrumentation (Optional)
If you need to add custom spans or attributes, you can follow the instructions found here
Troubleshooting
If you encounter any issues, you can visit this link for basic troubleshooting guidelines.
Prerequisites
- .NET 6+:
Check your .NET version with the following command:
dotnet --version
Features Supported
Traces | Metrics | App Logs | Custom Logs | Profiling |
---|---|---|---|---|
✅ | ✅ | ✖ | ✅ | ✖ |
Installation
1 Install the Required Package
Add the Middleware package to your .NET project by running the following command using CLI:
dotnet add package MW.APM
If you are using Visual Studio IDE in Windows, then you can install it by going to below given path.
PATH - Tools > Nuget Package Manager > Manage Nuget Packages for Solutions > Browse
Now, search for MW.APM and Install the nuget package.

2 Add Code Configuration
Add the following code to your Program.cs
file:
Program.cs
var configuration = new ConfigurationBuilder() .SetBasePath(Directory.GetCurrentDirectory()) .AddJsonFile("appsettings.json", optional: false, reloadOnChange: true) .AddEnvironmentVariables() .Build(); builder.Services.ConfigureMWInstrumentation(configuration); builder.Logging.AddConfiguration(configuration.GetSection("Logging")); builder.Logging.AddConsole();
3 Configure Your Middleware Account Information
Add the following to your appsettings.json
file:
"MW": { "ApiKey": "<MW_API_KEY>", "TargetURL": "https://<MW_UID>.middleware.io:443", "ServiceName": "<service-name>", "ProjectName": "<project-name>", "ConsoleExporter": "true", "ExcludeLinks": "[\"https://localhost:3000/health\"]", "ApmCollectMetrics": "true", "ApmCollectTraces": "true", "ApmCollectLogs": "true"
If you want to know more about all 2 methods and its attributes. You can refer this link
This is a one-time configuration. After these configuration changes are made, each time the lambda function deployed, the .NET instrumentation will also run.
Prerequisites
- Python 3.8+: Confirm with
python --version
- requirements.txt: Your project should use a
requirements.txt
for dependencies. - middleware-io: middeware-io package version should be v2.4.1 or above.
Features Supported
Traces | Metrics | App Logs | Custom Logs | Profiling |
---|---|---|---|---|
✅ | ✅ | ✅ | ✅ | ✅ |
Installation
1 Add middleware-io
to requirements.txt
Add the following line to your requirements.txt
file:
middleware-io>=2.4.1 setuptools
This ensures the package is installed when your Cloud Run container builds.
2 Setup Options
Google Cloud Run provides three ways to do cloud deployment:
Method | Auto-instrumentation | Manual-instrumentaion |
---|---|---|
Deploy Container | ✅ | ✅ |
Connect Repo | ✅ | ✅ |
Write a Function | ❌ | ✅ |
Method 1: Auto-instrumentation
Auto instrumentation allows you to monitor your Python application without modifying the application code. This can be achieved by setting environment variables that configure the application with Middleware Application Performance Monitoring (APM) tool.
1 Setup Virtual Environment
python -m venv myenv source myenv/bin/activate
2 Install Requirements
To install requirements mentioned in the file requirements.txt run the command in your terminal:
pip install -r requirements.txt
3 Install OpenTelemetry automatic instrumentation libraries:
Run the command to install instrumentation library:
middleware-bootstrap -a install
The middleware-bootstrap -a install
command reads through the list of packages installed in your active site-packages
folder, and installs the corresponding instrumentation libraries for these packages, if applicable. For example, if you already installed the flask
package, running middleware-bootstrap -a install
will install opentelemetry-instrumentation-flask
for you. The Middleware Python agent will use monkey patching to modify functions in these libraries at runtime.
Ensure library is installed properly with command:
pip list | grep -i flask Flask opentelemetry-instrumentation-flask
For Containerized Application add command in dockerfile:
RUN middleware-bootstrap -a install
Example:
You can set the following environment variables in your shell to auto instrument:
export MW_API_KEY='<MW_API_KEY>' export MW_TARGET='https://<MW_UID>.middleware.io:443' export MW_SERVICE_NAME='MyFlaskServer' middleware-run python app.py
If you are facing ImportError: Failed to initialize: git cmd not found
error, adding this environment variable might solve the issue. export GIT_PYTHON_REFRESH='quiet'
Method 2: Manual-instrumentation
If you prefer more control and want to integrate APM directly into your application, you can use a middleware function like mw_tracker
. This method requires adding a specific function call in your application's code .
Set these environment variables in your Cloud Run service configuration or Dockerfile:
MW_TRACKER=True
Then, initialize in your code with:
Example: Using mw_tracker
Function from Middleware
main.py
from flask import Flask # Import the mw_tracker from middleware to your app from middleware import mw_tracker, MWOptions, record_exception, DETECT_GCP mw_tracker( MWOptions( access_token="<MW_API_KEY>", target="https://<MW_UID>.middleware.io:443", console_exporter=True, debug_log_file=True,
For more advanced configuration of MWOptions
check out this list of all possible options here.
3 Add Custom Instrumentation (Optional)
If you need to add custom spans or attributes, see Python APM configuration.
Troubleshooting
If you encounter any issues, visit Python troubleshooting.
Need assistance or want to learn more about Middleware? Contact our support team at [email protected].