Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> JavaScript

การบันทึก log (Logging) ใน Node.js

การบันทึก log (Logging) เป็นส่วนสำคัญของแอปพลิเคชันทุกประเภท ไม่ว่าจะเขียนด้วย Node.js หรือภาษาอื่น Log ช่วยตรวจจับพฤติกรรมผิดปกติ ข้อผิดพลาด (errors) และข้อยกเว้น (exceptions) แบบเรียลไทม์ นักพัฒนาควรวาง log อย่างมีเหตุผล เพื่อช่วยระบุและแก้ไขปัญหาได้รวดเร็ว

ระดับ Log (Log Levels) ปัจจุบันมี 5 ระดับ

  • error – ข้อผิดพลาดร้ายแรงที่ทำให้ระบบทำงานไม่ได้
  • warn – คำเตือนที่อาจนำไปสู่ปัญหาในอนาคต
  • info – ข้อมูลทั่วไปเกี่ยวกับการทำงานของระบบ
  • verbose – ข้อมูลรายละเอียดมากกว่า info ใช้สำหรับ debug ลึก
  • debug – ข้อมูลสำหรับนักพัฒนาในการแก้ไขบั๊ก

การกำหนดค่า log level ให้เหมาะสมจะช่วยได้ประโยชน์สูงสุดจาก log

Middleware สำหรับ Logging

สามารถนำ middleware วางไว้ใน request pipeline เพื่อใช้งานร่วมกับโมดูล debug ซึ่งโมดูลส่วนใหญ่ใช้ debug สำหรับพิมพ์ log Middleware ทำหน้าที่เป็นช่องทางกลาง ส่ง log, request และ response ไปบันทึกในไฟล์ log เหมาะสำหรับแอป Express การตั้งค่า middleware ง่ายและใช้ได้กับเฟรมเวิร์กต่างๆ

การกำหนดค่าไฟล์สำหรับ Middleware

ระดับแอปพลิเคชัน (Application)

const app = express();
const logMiddleware = require('my-logging-middleware');
app.use(logMiddleware);

ระดับ Router

const router = express.Router();
const routeLoggingMiddleware = require('my-route-logging-middleware');
router.use(routeLoggingMiddleware);

สำหรับ Error Handling

const app = express();
const errorLoggingMiddleware = require('my-error-logging-middleware');
app.use(errorLoggingMiddleware);

แพ็กเกจ Winston

Winston เป็นแพ็กเกจ logging ยอดนิยม รองรับ log levels หลายระดับ query และ profiler

ตัวอย่างการใช้งาน Winston

const app = express();
const winston = require('winston');

const consoleTransport = new winston.transports.Console();
const myWinstonOptions = {
  transports: [consoleTransport]
};

const logger = winston.createLogger(myWinstonOptions);

function logRequest(req, res, next) {
  logger.info(req.url);
  next();
}
app.use(logRequest);

function logError(err, req, res, next) {
  logger.error(err);
  next();
}
app.use(logError);