# 5) Google Cloud Logging

1.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">GCP Logging</mark>**  
    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 Logging
    
2.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Setup GCP Logging</mark>**  
    **i) Enable APIs**
    
    ```javascript
    gcloud services enable logging.googleapis.com
    ```
    
    **ii) Create Service Account**  
    Go to: IAM & Admin → Service Accounts  
    Create: Name: nodejs-logger-sa  
    Role: **Logging Admin** OR **Logging Writer** (preferred)
    
    ```javascript
    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 → JSON
    
    ```javascript
    gcloud iam service-accounts keys create key.json \
      --iam-account=logging-sa@PROJECT_ID.iam.gserviceaccount.com
    ```
    
    Download file like: `nodejs-logger-sa-key.json`  
    **iv) Authentication - Use a Service Account Key**
    
    ```javascript
    export GOOGLE_APPLICATION_CREDENTIALS="./key.json"
    ```
    
    **v) Install SDK**
    
    ```javascript
    npm install @google-cloud/logging
    ```
    
3.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Node.js Logging Implementation</mark>**  
    i) Basic Logger Setup
    
    ```javascript
    const { Logging } = require('@google-cloud/logging');
    
    const logging = new Logging();
    const log = logging.log('my-app-log'); // log name
    ```
    
    ii) Write structured logs
    
    ```javascript
    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
    
    ```javascript
    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 });
      }
    });
    ```
    
4.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Logging Best Practices (Node.js)</mark>**  
    i) Use Structured Logs
    
    ```javascript
    {
      "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 endpoint
    
5.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">React Integration (Frontend Logging)</mark>**  
    React should NOT directly call GCP Logging instead it sends Logs to Backend
    
    ```javascript
    // 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
    
    ```javascript
    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
    
    ```javascript
    app.post('/api/logs', async (req, res) => {
      const { level, message, meta } = req.body;
    
      await writeLog(level, message, {
        source: 'react-app',
        ...meta
      });
    
      res.sendStatus(200);
    });
    ```
    
6.  **<mark class="bg-yellow-200 dark:bg-yellow-500/30">Viewing Logs in GCP</mark>**  
    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.
