[第4] @のVUE /プラグインCLI3、SSRに基づく統合されたロギングシステム〔パートIII〕

前の記事に---- @のVUE / CLI3プラグと統合された関数を作成し、[II] [第SSR SSR、我々が作成した@vue/cli3プラグインを、そしてssrプラグインサービスに統合します。

この記事では、のは、プラグインにしましょうssrログシステムサービスを作成します。

私たちは、側面を、以下徐々に来ます。

  • ログツールライブラリを選択
  • 統合ロギングツールssrプラグイン
  • サポートは、環境を区別するログログの分類、サポートのログレベルをサポート
  • ログをカット

ログツールライブラリを選択

いくつかのロギングツールの中から選択するnodejsライブラリをベース:

ここでは、選択しwinston、ロギングツールの基礎として、当社へのアクセスssrエンジニアリング

統合ロギングツールssrプラグイン

私たちは、開かれたREADMEを参照してください、あなた自身のロガーの作成、私たちの作成を開始し、1をwinstonlogger

ロガーを作成します。

前回の記事では、我々が開いて[II]は@のVUEを作成/プラグイン、およびSSR SSRに第2の機能を統合しCLI3 ---- [作成しvue-cli-plugin-my_ssr_plugin_demoたプロジェクト

インストール winston

yarn add winston
复制代码

ルートフォルダにappフォルダを作成libし、lib作成しlogger.jsたファイルを、この文書では、当社独自のロガーをカスタマイズ

次のようにディレクトリ構造は次のとおりです。

├── app
│   ├── lib
│   │   ├── logger.js
│   ├── middlewares
│   │   ├── dev.ssr.js
│   │   ├── dev.static.js
│   │   └── prod.ssr.js
│   └── server.js
...
复制代码

logger.js これは次のように読み取ります。

const winston = require('winston')

const logger = winston.createLogger({
  transports: [
    new winston.transports.Console(),
    new winston.transports.File({ filename: 'combined.log' })
  ]
})

module.exports = {
  logger
}
复制代码

そして、私たちを開いてapp/server.js、サービス開始の過程で、グローバルオブジェクトは、我々だけで作成された上に取り付けられlogger

...

const { logger } = require('./lib/logger.js')

...

app.listen(port, host, () => {
  logger.info(`[${process.pid}]server started at ${host}:${port}`)
})

...
复制代码

サービスを開始し、出力端子を見に加えて、それはまたのルートディレクトリに複数見つかりますcombined.logファイルを、その内容は出力端子と一致しています

{"message":"[46071]server started at 127.0.0.1:3000","level":"info"}
复制代码

これまでのところ、我々は、サーバーへの最も基本的なログへのアクセス権を持って、そして、私たちは実際のログシーンを考えてみましょう。

サポートは、環境を区別するログログの分類、サポートのログレベルをサポート

簡単にするために、我々は以下の特定の要件に単純化レベルを記録し、環境、ログの分類を区別します:

  1. ログがファイルに書き込まれる必要があります。
  2. ログは、カスタムレベルをサポートする必要がある、降順でのレベルはerror以下のとおりです。warningnoticeinfodebug、。
  3. 開発環境、色の最高出力ログは、より簡単に端末内の形式を読み取ることができます。
  4. ユーザー要求ログ増やすaccessタイプを、このログは、ログ領域の他のタイプとは別の独立したファイルに書き込まれる必要があります。

最初の要求では、我々前の例では、経過winston.transports.File実現。

第二、3つの要件のために、私たちはターンlib/logger.js次のように関連するコードを追加するために、最終的なコードは次のようになります。

const winston = require('winston')

const options = {
  // 我们在这里定义日志的等级
  levels: { error: 0, warning: 1, notice: 2, info: 3, debug: 4 },
  transports: [
    // 文件中我们只打印 warning 级别以上的日志(包含 warning)
    new winston.transports.File({ filename: 'combined.log', level: 'warning' })
  ]
}

// 开发环境,我们将日志也输出到终端,并设置上颜色
if (process.env.NODE_ENV === 'development') {
  options.format = winston.format.combine(
    winston.format.colorize(),
    winston.format.json()
  )

  // 输出到终端的信息,我们调整为 simple 格式,方便看到颜色;
  // 并设置打印 debug 以上级别的日志(包含 debug)
  options.transports.push(new winston.transports.Console({
    format: winston.format.simple(), level: 'debug'
  }))
}

const logger = winston.createLogger(options)

module.exports = {
  logger
}
复制代码

私たちは、app/servier.js次のコードを入力します。

...

logger.error('this is the error log')
logger.warning('this is the warning log')
logger.notice('this is the info log')
logger.info('this is the info log')
logger.debug('this is the debug log')

...
复制代码

髪オープンな環境でサービスを開始した後、以下のアウト端子プリントを表示するには:

error: this is the error log
warning: this is the warning log
notice: this is the info log
info: this is the info log
debug: this is the debug log
复制代码

ログファイルのcombined.log内容は次のとおりです

{"message":"this is the error log","level":"\u001b[31merror\u001b[39m"}
{"message":"this is the warning log","level":"\u001b[31mwarning\u001b[39m"}
复制代码

テスト環境と本番環境の後、サービスを開始し、ログには、端末、ファイルへの出力のみに出力されません。

{"message":"this is the error log","level":"error"}
{"message":"this is the warning log","level":"warning"}
复制代码

次は第4条の要件を見て:

ユーザー要求ログ増やすaccessタイプを、このログは、ログ領域の他のタイプとは別の独立したファイルに書き込まれる必要があります。

私たちが追加する必要がある場合はaccess、ログの種類を、そして別のファイルにその内容を出力し、最も簡単な方法は、1つの作成することであるloggerインスタンスを:

...
winston.loggers.add('access', {
  levels: { access: 0 },
  level: 'access',
  format: winston.format.combine(
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'access.log', level: 'access' })
  ]
})
...
复制代码

私たちは、app/servier.js印刷の追加accessログコード:

const { logger, accessLogger } = require('./log.js')
...
accessLogger.access('this is the access log')

复制代码

サービス開発環境を起動した後、我々は他にことがわかっcombined.logたログファイルの外部の追加access.logファイルは、読み取ります。

{"message":"this is the access log","level":"access"}
复制代码

これまでのところ、我々は自動的にログインする現在の時刻を記録していない、私たちがしているlib/logger.js二つのカテゴリーがログ時間に追加され、次のコードを追加します。

const winston = require('winston')

const options = {
  // 我们在这里定义日志的等级
  levels: { error: 0, warning: 1, notice: 2, info: 3, debug: 4 },
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' })
  ),
  transports: [
    // 文件中我们只打印 warning 级别以上的日志(包含 warning)
    new winston.transports.File({ filename: 'combined.log', level: 'warning' })
  ]
}

// 开发环境,我们将日志也输出到终端,并设置上颜色
if (process.env.NODE_ENV === 'development') {
  options.format = winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    winston.format.colorize(),
    winston.format.json()
  )

  // 输出到终端的信息,我们调整为 simple 格式,方便看到颜色;
  // 并设置打印 debug 以上级别的日志(包含 debug)
  options.transports.push(new winston.transports.Console({
    format: winston.format.simple(), level: 'debug'
  }))
}

winston.loggers.add('access', {
  levels: { access: 0 },
  level: 'access',
  format: winston.format.combine(
    winston.format.timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
    winston.format.json()
  ),
  transports: [
    new winston.transports.File({ filename: 'access.log', level: 'access' })
  ]
})

const logger = winston.createLogger(options)

module.exports = {
  logger,
  accessLogger: winston.loggers.get('access')
}
复制代码

開発環境は、サービスを開始した後、我々は現在の時刻情報を運ぶログは、端末が読み込みが見つかりました:

error: this is the error log {"timestamp":"2019-06-06 17:02:36.736"}
warning: this is the warning log {"timestamp":"2019-06-06 17:02:36.740"}
notice: this is the info log {"timestamp":"2019-06-06 17:02:36.741"}
info: this is the info log {"timestamp":"2019-06-06 17:02:36.741"}
debug: this is the debug log {"timestamp":"2019-06-06 17:02:36.741"}
复制代码

次のように ``ファイルの内容は以下のとおりです。

{"message":"this is the error log","level":"\u001b[31merror\u001b[39m","timestamp":"2019-06-06 17:02:36.736"}
{"message":"this is the warning log","level":"\u001b[31mwarning\u001b[39m","timestamp":"2019-06-06 17:02:36.740"}
复制代码

次のように ``ファイルの内容は以下のとおりです。

{"message":"this is the access log","level":"access","timestamp":"2019-06-06 17:02:36.741"}
复制代码

ログをカット

オンライン・サービスの今後の展開後、コンテンツを記録し、サーバーログは長時間実行中のサービスのために、ログが大きすぎるリスクが存在し、同じファイルにログに書き込まれているように続けます。

ここでは、各時間以内ログの内容に応じて、時間あたりのログを分割し、異なるファイルを書き込みます。

また、商品やサービスの展開以来複数有するworkerプロセスおよびサービスを、私たちはすべてのログにこのプロセスを格納するプロセスごとに(プロセスID +日付を区別するために)別のフォルダを割り当てます。

logs
├──your_project_name
│   ├──pid_1236_2019_01_01
│   │   ├──access-2019-01-01-23.log
│   │   └──combined-2019-01-01-23.log
│   └──pid_1237_2019_01_01
│      ├──access-2019-01-01-23.log
│      └──combined-2019-01-01-23.log
复制代码

私たちの予想されるログカット機能を実現するために、我々はライブラリを導入する必要があります。winston-daily-rotate-file

yarn add winston-daily-rotate-file
复制代码

インストール後、我々はしているlib/logger.jsで導入します

require('winston-daily-rotate-file')
复制代码

導入後、我々はできるwinston.transports.DailyRotateFile自動カット機能tracsportsインスタンスの作成を持っています

const _getToday = (now = new Date()) => `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`

let dirPath += '/pid_' + pid + '_' + _getToday() + '/'

let accessTransport = new (winston.transports.DailyRotateFile)({
  filename: dirPath + 'access-%DATE%.log', // 日志文件存储路径 + 日志文件名称
  datePattern: 'YYYY-MM-DD-HH', // 日志文件切割的粒度,这里为每小时
  zippedArchive: true, // 是否压缩
  maxSize: '1g', // 每个日志文件最大的容量,如果达到此容量则触发切割
  maxFiles: '30d' // 日志文件保留的时间,这里为 30 天,30天之前的日志会被删除掉
})
复制代码

機能切削添加した後lib/logger.js、以下のように:

const winston = require('winston')
const { format } = winston
const { combine, timestamp, json } = format

const _getToday = (now = new Date()) => `${now.getFullYear()}-${now.getMonth() + 1}-${now.getDate()}`

const rotateMap = {
  'hourly': 'YYYY-MM-DD-HH',
  'daily': 'YYYY-MM-DD',
  'monthly': 'YYYY-MM'
}

module.exports = (dirPath = './', rotateMode = '') => {

  if (!~Object.keys(rotateMap).indexOf(rotateMode)) rotateMode = ''

  let accessTransport
  let combineTransport

  if (rotateMode) {
    require('winston-daily-rotate-file')

    const pid = process.pid

    dirPath += '/pid_' + pid + '_' + _getToday() + '/'

    const accessLogPath = dirPath + 'access-%DATE%.log'
    const combineLogPath = dirPath + 'combine-%DATE%.log'

    const datePattern = rotateMap[rotateMode] || 'YYYY-MM'

    accessTransport = new (winston.transports.DailyRotateFile)({
      filename: accessLogPath,
      datePattern: datePattern,
      zippedArchive: true,
      maxSize: '1g',
      maxFiles: '30d'
    })

    combineTransport = new (winston.transports.DailyRotateFile)({
      filename: combineLogPath,
      datePattern: datePattern,
      zippedArchive: true,
      maxSize: '500m',
      maxFiles: '30d'
    })
  }

  const options = {
    // 我们在这里定义日志的等级
    levels: { error: 0, warning: 1, notice: 2, info: 3, debug: 4 },
    format: combine(
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' })
    ),
    transports: rotateMode ? [
      combineTransport
    ] : []
  }

  // 开发环境,我们将日志也输出到终端,并设置上颜色
  if (process.env.NODE_ENV === 'development') {
    options.format = combine(
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
      winston.format.colorize(),
      json()
    )

    // 输出到终端的信息,我们调整为 simple 格式,方便看到颜色;
    // 并设置打印 debug 以上级别的日志(包含 debug)
    options.transports.push(new winston.transports.Console({
      format: format.simple(), level: 'debug'
    }))
  }

  winston.loggers.add('access', {
    levels: { access: 0 },
    level: 'access',
    format: combine(
      timestamp({ format: 'YYYY-MM-DD HH:mm:ss.SSS' }),
      json()
    ),
    transports: rotateMode ? [
      accessTransport
    ] : []
  })

  const logger = winston.createLogger(options)

  return {
    logger: logger,
    accessLogger: winston.loggers.get('access')
  }
}
复制代码

app/server.js導入lib/logger.jsも次のように調整する必要があります。

const { logger, accessLogger } = require('./lib/logger.js')('./', 'hourly')
复制代码

サービスを開始するための開発環境では、我々は次のようにログの出力端子に加えて、我々は構造にファイルを記録していることがわかります。

./pid_48794_2019-6-6
├── access-2019-06-06-18.log
└── combine-2019-06-06-18.log
复制代码

最終的には、プラグインでvue-cli-plugin-my_ssr_plugin_demo、次のように完全なディレクトリ構造は次のとおりです。

├── app
│   ├── middlewares
│   │   ├── dev.ssr.js
│   │   ├── dev.static.js
│   │   └── prod.ssr.js
│   ├── lib
│   │   └── logger.js
│   └── server.js
├── generator
│   ├── index.js
│   └── template
│       ├── src
│       │   ├── App.vue
│       │   ├── assets
│       │   │   └── logo.png
│       │   ├── components
│       │   │   └── HelloWorld.vue
│       │   ├── entry-client.js
│       │   ├── entry-server.js
│       │   ├── main.js
│       │   ├── router
│       │   │   └── index.js
│       │   ├── store
│       │   │   ├── index.js
│       │   │   └── modules
│       │   │       └── book.js
│       │   └── views
│       │       ├── About.vue
│       │       └── Home.vue
│       └── vue.config.js
├── index.js
└── package.json
复制代码

これまでのところ、我々は、ロギングシステムを完成させました。次の記事では、我々はする方法について話vue-cli-plugin-my_ssr_plugin_demo監視システムを設計し、統合されました。


メールボックスにあなたの履歴書を送るために歓迎、パートナーを募集するために、フロントエンドのチームをドロップ:[email protected]

ます。https://juejin.im/post/5d030cc4f265da1bd04edc64で再現

おすすめ

転載: blog.csdn.net/weixin_34038652/article/details/93182168