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

באפליקציות Node.js, הפלאגינים מתוחזקים בספריות הפופולריות של רישום ביומן Winston ו-Bunyan. ‫Winston היא ספרייה לשימוש כללי, שמטמיעה מגוון של מעצבי פורמטים וטרנספורטים של יומנים. Bunyan, שמתמחה ביומני JSON מובְנים, תומך בעיצוב יומנים באמצעות העברה בצינור עיבוד נתונים (piping) לשורת הפקודה של 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, if it is not already enabled.

    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, if it is not already enabled.

    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. במאמר דוגמה להטמעת מכשור ב-Node.js תוכלו למצוא קוד לדוגמה שמשתמש ב-OpenTelemetry כדי לאסוף מדדים ונתוני מעקב, ובמסגרת Pino כדי לאסוף נתוני יומנים. אם אתם משתמשים ב-Pino, אתם צריכים להטמיע מיפוי בין רמות החומרה של Pino לבין אלה שמשמשות את Cloud Logging. לדוגמה של קוד, ראו מיפוי רמות של יומני Pino.

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

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

כדי להתקין ולהגדיר את הפלאגין של 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 שמועבר ל-constructor של הפלאגין.

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

ב-Cloud Logging יש פלאגין לספריית הרישום ביומן Bunyan ב-Node.js. הפלאגין של 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 שמועבר ל-constructor של הפלאגין.

שימוש ב-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. אפשר גם לדווח על בעיות באמצעות Issue Tracker.

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

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

הפעלה ב- Google Cloud

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

App Engine

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

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

למידע נוסף, קראו את המאמר כתיבה והצגה של יומנים.

Google Kubernetes Engine (GKE)

‫GKE מקצה באופן אוטומטי לחשבון השירות שמוגדר כברירת מחדל את התפקיד כתיבת יומנים (roles/logging.logWriter) ב-IAM. אם אתם משתמשים באיחוד זהויות של עומסי עבודה ל-GKE עם חשבון השירות שמוגדר כברירת מחדל כדי לאפשר לעומסי עבודה לגשת לממשקי API ספציפיים שלGoogle Cloud , לא נדרשת הגדרה נוספת. עם זאת, אם אתם משתמשים באיחוד הזהויות של עומסי עבודה ל-GKE עם חשבון שירות בהתאמה אישית ב-IAM, ודאו שלחשבון השירות בהתאמה אישית יש את התפקיד "כתיבת יומנים" (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. כשיוצרים מכונה חדשה דרך המסוף, אפשר לעשות זאת בקטע Identity and API access בחלונית Create Instance.Google Cloud משתמשים בחשבון השירות שמוגדר כברירת מחדל ב-Compute Engine או בחשבון שירות אחר לבחירתכם, ובוחרים באפשרות Allow full access to all Cloud APIs בקטע Identity and API access. לא משנה באיזה חשבון שירות תבחרו, ודאו שהוקצה לו התפקיד 'כתיבת יומנים' בקטע IAM & Admin במסוףGoogle Cloud .

פונקציות Cloud Run

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

אפשר להשתמש בספריות של 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.