5) Google Cloud Logging
GCP Logging
Google Cloud Logging is a centralized logging service that lets you,
i) Collect logs from apps, servers, and services,
ii) Search & filter logs
iii) Create alerts & dashboards
iv) Debug production issues
React does NOT directly send logs to GCP (security risk)
React sends events → Node.js API → GCP LoggingSetup GCP Logging
i) Enable APIsgcloud services enable logging.googleapis.comii) Create Service Account
Go to: IAM & Admin → Service Accounts
Create: Name: nodejs-logger-sa
Role: Logging Admin OR Logging Writer (preferred)gcloud iam service-accounts create logging-sa gcloud projects add-iam-policy-binding PROJECT_ID \ --member="serviceAccount:logging-sa@PROJECT_ID.iam.gserviceaccount.com" \ --role="roles/logging.logWriter"iii) Create Key (JSON)
Click → Keys → Add Key → JSONgcloud iam service-accounts keys create key.json \ --iam-account=logging-sa@PROJECT_ID.iam.gserviceaccount.comDownload file like:
nodejs-logger-sa-key.json
iv) Authentication - Use a Service Account Keyexport GOOGLE_APPLICATION_CREDENTIALS="./key.json"v) Install SDK
npm install @google-cloud/loggingNode.js Logging Implementation
i) Basic Logger Setupconst { Logging } = require('@google-cloud/logging'); const logging = new Logging(); const log = logging.log('my-app-log'); // log nameii) Write structured logs
async function writeLog(severity, message, meta = {}) { const entry = log.entry( { resource: { type: 'global' }, severity: severity, }, { message, ...meta, } ); await log.write(entry); }iii) Example Usage in API
const express = require('express'); const app = express(); app.use(express.json()); app.post('/api/user', async (req, res) => { try { const user = req.body; // Simulate DB save if (!user.name) { throw new Error('Name is required'); } await writeLog('INFO', 'User created', { user, endpoint: '/api/user', }); res.status(201).send({ message: 'User created' }); } catch (error) { await writeLog('ERROR', error.message, { stack: error.stack, endpoint: '/api/user', }); res.status(500).send({ error: error.message }); } });Logging Best Practices (Node.js)
i) Use Structured Logs{ "message": "User login failed", "userId": "123", "ip": "1.2.3.4" }ii) Use Severity Levels - DEBUG, INFO, WARNING, ERROR, CRITICAL
iii) Add Context - requestId, userId, API endpointReact Integration (Frontend Logging)
React should NOT directly call GCP Logging instead it sends Logs to Backend// logger.js export const logEvent = async (level, message, meta = {}) => { await fetch('/api/logs', { method: 'POST', headers: { 'Content-Type': 'application/json' }, body: JSON.stringify({ level, message, meta }) }); };Use in React App
import { logEvent } from './logger'; const handleLogin = async () => { try { // login logic await logEvent('INFO', 'User clicked login', { page: 'LoginPage' }); } catch (error) { await logEvent('ERROR', 'Login failed', { error: error.message }); } };Backend Endpoint for Frontend Logs
app.post('/api/logs', async (req, res) => { const { level, message, meta } = req.body; await writeLog(level, message, { source: 'react-app', ...meta }); res.sendStatus(200); });Viewing Logs in GCP
Once logs are sent from your Node.js application, they can be viewed in the Logs Explorer within the Google Cloud Console:
Navigate to the Google Cloud Console.
Go to Logging > Logs Explorer.
Select the specific log (e.g.,my-log) and view entries.
You can search, filter, and analyze logs based on severity, timestamps, or any custom fields you've added to your log entries.We implemented centralized structured logging using @google-cloud/logging in Node.js. The React app sends client-side events to a backend logging endpoint, which enriches logs with metadata and pushes them to GCP Logging. We also implemented request tracing, severity-based logging, and middleware-based automatic request logging.