ホームページ  >  記事  >  ウェブフロントエンド  >  Nodejsログモジュールwinstonの使用方法

Nodejsログモジュールwinstonの使用方法

php中世界最好的语言
php中世界最好的语言オリジナル
2018-06-01 11:45:551383ブラウズ

今回は、nodejsログモジュールwinstonの使い方と、nodejsログモジュールwinstonを使用する際の注意事項を紹介します。以下は実際的なケースです。

winston ログ モジュール

nodejs winston モジュールと 2 つの関連モジュールを使用すると、半分の労力で 2 倍の結果が得られます。

  1. express-winston

  2. winston-daily-rotate-file

express-winston

は、ログを出力するためのexpressのミドルウェアとして使用されるexpress-winstonのwinstonの追加バージョンです。 s 、リクエストヘッダー情報だけでなく、応答時間も含まれます。
ミドルウェアとして応答時間がかかるのはなぜですか? Express-winston は Express の res.end メソッドを書き換えるため、リクエストの完了後にログが生成されます。

コードスニペット

var end = res.end;
res.end = function(chunk, encoding) {
 res.responseTime = (new Date) - req._startTime;
 res.end = end;
 res.end(chunk, encoding);
 ...
 }

express-winstonはwinstonのトランスポートを変更または拡張するものではなく、winston-daily-rotate-fileはwinstonのトランスポートメソッドを拡張するだけです

winston-daily-rotate-file

winston-daily -rotate-ファイルは winston の拡張子であり、winston がログをローテーションできるようにトランスポート メソッドを追加します。

と組み合わせて使用​​すると、次の要件があります: ログを出力するときに、express-winston にリクエストパラメータとインターフェイス /api の応答データも出力させるにはどうすればよいですか?

  1. ログミドルウェアは、コールチェーン API の背後、api/* ビジネス処理の前にある必要があります。例: app.use('/api', apiRequestLogger, apiHandler)

  2. 応答データを取得するには、ビジネスが処理された後に送信した後でのみ取得できます。ここから応答データをキャプチャできます

コードは次のとおりです

import winston from 'winston'
import expressWinston from 'express-winston'
import 'winston-daily-rotate-file'
import path from 'path'
export let DailyRotateFileTransport = (fileName) => {
 return new (winston.transports.DailyRotateFile)({
 filename: path.join(process.env.LOGPATH, `${fileName}-%DATE%.log`),
 datePattern: 'YYYY-MM-DD-HH',
 // maxSize: '20m',
 maxFiles: '7d',
 timestamp: () => new Date().format('yyyy-MM-dd hh:mm:ss.S')
 })
}
export let pageRequestLogger = expressWinston.logger({
 transports: [
 DailyRotateFileTransport('page-request')
 ],
 meta: true, // optional: control whether you want to log the meta data about the request (default to true)
 msg: 'HTTP {{req.method}} {{req.url}}', // optional: customize the default logging message. E.g. "{{res.statusCode}} {{req.method}} {{res.responseTime}}ms {{req.url}}"
 expressFormat: true, // Use the default Express/morgan request formatting. Enabling this will override any msg if true. Will only output colors with colorize set to true
 colorize: false, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
 ignoreRoute: function (req, res) {
 // 只打印页面请求信息
 let notPageRequest = false
 let ignoreArr = ['/api', '.js', '.css', '.png', '.jpg', '.gif']
 ignoreArr.forEach(item => {
  if (req.url.indexOf(item) > -1) notPageRequest = true
 })
 return notPageRequest
 } // optional: allows to skip some log messages based on request and/or response
})
export let apiRequestLogger = (req, res, next) => {
 let send = res.send
 let content = ''
 let query = req.query || {}
 let body = req.body || {}
 res.send = function () {
 content = arguments[0]
 send.apply(res, arguments)
 }
 expressWinston.logger({
 transports: [
  DailyRotateFileTransport('api-request')
 ],
 meta: true, // optional: control whether you want to log the meta data about the request (default to true)
 msg () {
  return `HTTP ${req.method} ${req.url} query ${JSON.stringify(query)} body ${JSON.stringify(body)} resData ${content} `
 },
 colorize: true, // Color the text and status code, using the Express/morgan color palette (text: gray, status: default green, 3XX cyan, 4XX yellow, 5XX red).
 ignoreRoute: function (req, res) {
  if (req.headers.self) return true
  return false
 } // optional: allows to skip some log messages based on request and/or response
 })(req, res, next)
}

この記事の事例を読んだ後は、この方法を習得したと思います。さらに興味深い情報については、PHP 中国語に関する他の関連記事に注目してください。 Webサイト!

推奨読書:

JS を使用して文字列に含まれるコンテンツを決定する方法の概要

JS+HTML5 マウス イベントのリアル バインディング パーティクル アニメーション

以上がNodejsログモジュールwinstonの使用方法の詳細内容です。詳細については、PHP 中国語 Web サイトの他の関連記事を参照してください。

声明:
この記事の内容はネチズンが自主的に寄稿したものであり、著作権は原著者に帰属します。このサイトは、それに相当する法的責任を負いません。盗作または侵害の疑いのあるコンテンツを見つけた場合は、admin@php.cn までご連絡ください。