הגדרת Cloud Logging ל-Node.js

באפליקציות Node.js, יש תוספים לספריות הפופולריות של רישום ביומן Winston ו-Bunyan. ‫Winston היא ספרייה לשימוש כללי, שמיישמת מגוון של מעצבי פורמטים של יומנים והעברות. ‫Bunyan, שמתמחה ביומני JSON מובְנים, תומך בעיצוב יומנים באמצעות העברה בצינור לפקודה Bunyan בשורת הפקודה.

אפשר גם להשתמש ישירות בספריית הלקוח של Logging ל-Node.js, או ליצור שילובים משלכם עם ספריית הרישום המועדפת. לדוגמה, אפשר להשתמש בדוגמה של Pino log framework.

אין צורך להתקין את סוכן Logging כדי להשתמש ב-Winston או ב-Bunyan במופע של מכונה וירטואלית (VM) ב-Compute Engine.

לפני שמתחילים

  1. נכנסים לחשבון Google Cloud . אם אתם משתמשים חדשים ב- Google Cloud, צרו חשבון כדי שתוכלו להעריך את הביצועים של המוצרים שלנו בתרחישים מהעולם האמיתי. לקוחות חדשים מקבלים בחינם גם קרדיט בשווי 300$ להרצה, לבדיקה ולפריסה של עומסי העבודה.
  2. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  3. Verify that billing is enabled for your Google Cloud project.

  4. Enable the Cloud Logging API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  5. In the Google Cloud console, on the project selector page, select or create a Google Cloud project.

    Roles required to select or create a project

    • Select a project: Selecting a project doesn't require a specific IAM role—you can select any project that you've been granted a role on.
    • Create a project: To create a project, you need the Project Creator role (roles/resourcemanager.projectCreator), which contains the resourcemanager.projects.create permission. Learn how to grant roles.

    Go to project selector

  6. Verify that billing is enabled for your Google Cloud project.

  7. Enable the Cloud Logging API.

    Roles required to enable APIs

    To enable APIs, you need the serviceusage.services.enable permission. If you created the project, then you likely already have this permission through the Owner role (roles/owner). Otherwise, you can get this permission through the Service Usage Admin role (roles/serviceusage.serviceUsageAdmin). Learn how to grant roles.

    Enable the API

  8. מכינים את הסביבה לפיתוח ב-Node.js.

    למדריך ההגדרה של Node.js

הגדרת רישום ביומן

בקטע הזה מוסבר איך להתקין ולהגדיר את הפלאגינים של ספריות הרישום Winston ו-Bunyan. ב-Bunyan, יש מידע על אופן השימוש ב-Bunyan עם אפליקציית Node.js Express.

אפשר להשתמש בספריות או במסגרות אחרות. לדוגמה, אפשר להשתמש ב-Pino log framework. דוגמאות לקוד שמשתמש ב-OpenTelemetry כדי לאסוף מדדים ונתוני מעקב, ובמסגרת Pino log כדי לאסוף נתוני יומן, זמינות במאמר דוגמה לשדרוג של Node.js. אם אתם משתמשים ב-Pino, אתם צריכים להטמיע מיפוי בין רמות החומרה של Pino לבין אלה שמשמשות את Cloud Logging. דוגמאות לקוד מופיעות במאמר בנושא מיפוי רמות של יומן Pino.

התקנה והגדרה של הפלאגין Winston

‫Cloud Logging מספק תוסף לספריית הרישום ביומן Winston Node.js. התוסף Logging ל-Winston מספק שכבה פשוטה יותר ברמה גבוהה יותר לעבודה עם Logging.

כדי להתקין ולהגדיר את הפלאגין Winston:

  1. כדי להתקין את הפלאגין Logging Winston, משתמשים ב-npm:

    npm install @google-cloud/logging-winston winston
  2. מייבאים את הפלאגין ומוסיפים אותו להגדרות של Winston:

    const winston = require('winston');
    
    // Imports the Google Cloud client library for Winston
    const {LoggingWinston} = require('@google-cloud/logging-winston');
    
    const loggingWinston = new LoggingWinston();
    
    // Create a Winston logger that streams to Cloud Logging
    // Logs will be written to: "projects/YOUR_PROJECT_ID/logs/winston_log"
    const logger = winston.createLogger({
      level: 'info',
      transports: [
        new winston.transports.Console(),
        // Add Cloud Logging
        loggingWinston,
      ],
    });
    
    // Writes some log entries
    logger.error('warp nacelles offline');
    logger.info('shields at 99%');
  3. מגדירים את הפלאגין.

    אפשר להתאים אישית את ההתנהגות של הפלאגין Winston באמצעות אותן אפשרויות הגדרה שנתמכות על ידי ספריית הלקוח של Cloud Logging API ל-Node.js. אפשר להעביר את האפשרויות האלה באובייקט options שמועבר לקונסטרוקטור של התוסף.

התקנה והגדרה של הפלאגין Bunyan

‫Cloud Logging מספק תוסף לספריית הרישום ב-Node.js‏ Bunyan. התוסף Logging ל-Bunyan מספק שכבה פשוטה יותר ברמה גבוהה יותר לעבודה עם Logging.

כדי להתקין ולהגדיר את הפלאגין Bunyan:

  1. כדי להתקין את הפלאגין Logging Bunyan, משתמשים ב-npm:

    npm install bunyan @google-cloud/logging-bunyan
  2. מייבאים את הפלאגין ומוסיפים אותו להגדרות של Bunyan:

    const bunyan = require('bunyan');
    
    // Imports the Google Cloud client library for Bunyan
    const {LoggingBunyan} = require('@google-cloud/logging-bunyan');
    
    // Creates a Bunyan Cloud Logging client
    const loggingBunyan = new LoggingBunyan();
    
    // Create a Bunyan logger that streams to Cloud Logging
    // Logs will be written to: "projects/YOUR_PROJECT_ID/logs/bunyan_log"
    const logger = bunyan.createLogger({
      // The JSON payload of the log as it appears in Cloud Logging
      // will contain "name": "my-service"
      name: 'my-service',
      streams: [
        // Log to the console at 'info' and above
        {stream: process.stdout, level: 'info'},
        // And log to Cloud Logging, logging at 'info' and above
        loggingBunyan.stream('info'),
      ],
    });
    
    // Writes some log entries
    logger.error('warp nacelles offline');
    logger.info('shields at 99%');
  3. מגדירים את הפלאגין.

    אפשר להתאים אישית את ההתנהגות של הפלאגין Bunyan באמצעות אותן אפשרויות הגדרה שנתמכות על ידי ספריית הלקוח של Cloud Logging API ל-Node.js. אפשר להעביר את האפשרויות האלה באובייקט options שמועבר לקונסטרוקטור של התוסף.

שימוש ב-Bunyan וב-Express

אפשר להגדיר את Bunyan ולהשתמש בו עם Logging באפליקציית Node.js Express.

// Imports the Google Cloud client library for Bunyan.
const lb = require('@google-cloud/logging-bunyan');

// Import express module and create an http server.
const express = require('express');

async function startServer() {
  const {logger, mw} = await lb.express.middleware({
    logName: 'samples_express',
  });
  const app = express();

  // Install the logging middleware. This ensures that a Bunyan-style `log`
  // function is available on the `request` object. This should be the very
  // first middleware you attach to your app.
  app.use(mw);

  // Setup an http route and a route handler.
  app.get('/', (req, res) => {
    // `req.log` can be used as a bunyan style log method. All logs generated
    // using `req.log` use the current request context. That is, all logs
    // corresponding to a specific request will be bundled in the Stackdriver
    // UI.
    req.log.info('this is an info log message');
    res.send('hello world');
  });

  const port = process.env.PORT || 8080;

  // `logger` can be used as a global logger, one not correlated to any specific
  // request.
  logger.info({port}, 'bonjour');

  // Start listening on the http server.
  const server = app.listen(port, () => {
    console.log(`http server listening on port ${port}`);
  });

  app.get('/shutdown', (req, res) => {
    res.sendStatus(200);
    server.close();
  });
}

startServer();

מידע נוסף על התקנה מופיע במסמכי התיעוד של ספריות Cloud Logging ל-Node.js. אפשר גם לדווח על בעיות באמצעות הכלי למעקב אחרי בעיות.

כתיבת יומנים באמצעות ספריית הלקוח של Cloud Logging

מידע על שימוש ישיר בספריית הלקוח של Cloud Logging עבור Node.js מופיע במאמר ספריות הלקוח של Cloud Logging.

ריצה ב- Google Cloud

כדי שאפליקציה תוכל לכתוב יומנים באמצעות ספריות Cloud Logging ל-Node.js, לחשבון השירות של המשאב הבסיסי צריך להיות תפקיד Logs Writer (roles/logging.logWriter) IAM. ברוב הסביבות, חשבון השירות שמוגדר כברירת מחדל מוגדר אוטומטית עם התפקיד הזה. Google Cloud

App Engine

‫Cloud Logging מופעל באופן אוטומטי ב-App Engine, ולחשבון השירות שמוגדר כברירת מחדל של האפליקציה יש הרשאות IAM כברירת מחדל לכתיבת רשומות ביומן.

כדי לכתוב רשומות ביומן מהאפליקציה, מומלץ להשתמש ב-Bunyan או ב-Winston כמו שמתואר בדף הזה.

מידע נוסף זמין במאמר בנושא כתיבה וצפייה ביומנים.

Google Kubernetes Engine (GKE)

GKE מעניק באופן אוטומטי לחשבון השירות שמוגדר כברירת מחדל את תפקיד ה-IAM‏ Logs Writer (roles/logging.logWriter). אם אתם משתמשים באיחוד זהויות של עומסי עבודה ל-GKE עם חשבון השירות שמוגדר כברירת מחדל כדי לאפשר לעומסי עבודה לגשת ל-APIs ספציפיים שלGoogle Cloud , לא נדרש שום שינוי נוסף בהגדרות. עם זאת, אם משתמשים באיחוד שירותי אימות הזהות של עומסי עבודה ב-GKE עם חשבון שירות מותאם אישית של IAM, צריך לוודא שלחשבון השירות המותאם אישית יש את התפקיד Logs Writer ‏ (roles/logging.logWriter).

במקרה הצורך, אפשר להשתמש גם בפקודה הבאה כדי להוסיף את logging.write היקף הגישה כשיוצרים את האשכול:

gcloud container clusters create example-cluster-name \
    --scopes https://www.googleapis.com/auth/logging.write

Compute Engine

כשמשתמשים במופעים של מכונות וירטואליות ב-Compute Engine, צריך להוסיף את היקף הגישה cloud-platform לכל מופע. כשיוצרים מכונה חדשה דרך מסוףGoogle Cloud , אפשר לעשות זאת בקטע Identity and API access (זהות וגישה ל-API) בחלונית Create Instance (יצירת מכונה). משתמשים בחשבון השירות שמוגדר כברירת המחדל ב-Compute Engine או בחשבון שירות אחר לפי בחירתכם, ובקטע Identity and API access בוחרים באפשרות Allow full access to all Cloud APIs. לא משנה איזה חשבון שירות תבחרו, חשוב לוודא שניתן לו התפקיד Logs Writer בקטע IAM & Admin במסוףGoogle Cloud .

פונקציות Cloud Run

פונקציות Cloud Run מקבלות כברירת מחדל את התפקיד Logs Writer.

אפשר להשתמש בספריות Cloud Logging ל-Node.js בלי לספק פרטי כניסה באופן מפורש.

פונקציות Cloud Run מוגדרות לשימוש אוטומטי ב-Cloud Logging.

הרצה באופן מקומי ובמקומות אחרים

כדי להשתמש בספריות Cloud Logging ל-Node.js מחוץ ל- Google Cloud, כולל הפעלת הספרייה בתחנת העבודה שלכם, במחשבים של מרכז הנתונים או במכונות וירטואליות של ספק שירותי ענן אחר, אתם צריכים להגדיר Application Default Credentials ‏ (ADC) בסביבה המקומית כדי לבצע אימות לספריות Cloud Logging ל-Node.js.

למידע נוסף אפשר לעיין במאמר הגדרת ADC לספק שירותי ענן מקומי או אחר.

שימוש ב-Winston:

// Imports the Google Cloud client library for Winston
const {LoggingWinston} = require('@google-cloud/logging-winston');

// Creates a client
const loggingWinston = new LoggingWinston({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
});

שימוש ב-Bunyan:

// Imports the Google Cloud client library for Bunyan
const {LoggingBunyan} = require('@google-cloud/logging-bunyan');

// Creates a client
const loggingBunyan = new LoggingBunyan({
  projectId: 'your-project-id',
  keyFilename: '/path/to/key.json',
});

צפייה ביומנים

במסוף Google Cloud , נכנסים לדף Logs Explorer:

כניסה אל Logs Explorer

אם משתמשים בסרגל החיפוש כדי למצוא את הדף הזה, בוחרים בתוצאה שכותרת המשנה שלה היא Logging.

בכלי Logs Explorer, צריך לציין משאב אחד או יותר, אבל יכול להיות שלא ברור איך לבחור את המשאב. ריכזנו כאן כמה טיפים שיעזרו לכם להתחיל:

  • אם אתם פורסים את האפליקציה ב-App Engine או משתמשים בספריות ספציפיות ל-App Engine, צריך להגדיר את המשאב לערך GAE Application.

  • אם אתם פורסים את האפליקציה ב-Compute Engine, צריך להגדיר את המשאב ל-GCE VM Instance.

  • אם אתם פורסים את האפליקציה ב-Google Kubernetes Engine, הגדרת רישום היומנים של האשכול קובעת את סוג המשאב של רשומות היומן. במאמר מעבר לפתרון Google Cloud Observability Kubernetes Monitoring מוסבר בפירוט על הפתרונות Legacy Google Cloud Observability ו-Google Cloud Observability Kubernetes Monitoring, ועל ההשפעה של האפשרויות האלה על סוג המשאב.

  • אם האפליקציה שלכם משתמשת ישירות ב-Cloud Logging API, המשאב תלוי ב-API ובהגדרה שלכם. לדוגמה, באפליקציה שלכם תוכלו לציין משאב או להשתמש במשאב שמוגדר כברירת מחדל.

  • אם לא מופיעים יומנים ב-Logs Explorer, כדי לראות את כל רשומות היומן, צריך לעבור למצב שאילתה מתקדם ולהשתמש בשאילתה ריקה.

    1. כדי לעבור למצב שאילתות מתקדם, לוחצים על תפריט (▾) בחלק העליון של הכלי Logs Explorer ואז בוחרים באפשרות המרה למסנן מתקדם.
    2. מנקים את התוכן שמופיע בתיבת הסינון.
    3. לוחצים על שליחת המסנן.

    אפשר לבדוק את הרשומות בנפרד כדי לזהות את המשאבים.

מידע נוסף זמין במאמר שימוש ב-Logs Explorer.