I'm trying to implement google trace in my MERN project, hosted in google cloud platform.
I've followed the guide and the examples offered by Google, but I can't make it work in any way.
import gCloudTrace from '@google-cloud/trace-agent';
// initialize gcloud trace
if (process.env.NODE_ENV === 'production') {
console.log(`Starting google cloud trace...`);
const tracer = gCloudTrace.start();
console.log(JSON.stringify(tracer,null,2));
};
import express from 'express';
import apiRoute from './api.js';
import indexRoute from './index/indexRoute.js';
try {
// setup
const host = process.env.HOST || '0.0.0.0';
const port = process.env.PORT || 5050;
const app = express();
// routes
app.use('/', indexRoute);
app.use('/api', checkGloblalSettings, apiRoute);
// create and run HTTP server
app.listen(port, host, () => {
console.log(`EXPRESS SERVER HTTP BACKEND UP AND RUNNING ON ${host} : ${port}`);
});
} catch(error) {
globalErrorHandler(error);
};
When I deploy (google app engine, flex env) everything works great, all route works but I can't find any trace in my project. I've double checked gcloud settings: Trace API is enabled, no need to create custom credentials.
Any suggestion?
I finally solved the problem. While the code in the question seems correct, the problem inherently lies in how NodeJS handles ES6 import() instead of require().
Throughout the Google Trace documentation you will find only examples with require(). Here an example:
The fact is that while using require the import order is respected (so if you place require('@ google-cloud/trace-agent').start(); in the first place everything works), using import() the code runs AFTER importing the express module as well, so nothing is tracked.
To solve, I recreated the require syntax (here the documentation), then using require() everything worked perfectly:
I hope this can serve others and avoid the headaches it caused me :)