소스 검색

优化日志,环境变量修改

zhusiqing 3 년 전
부모
커밋
b22d8a7f7e
5개의 변경된 파일24개의 추가작업 그리고 16개의 파일을 삭제
  1. 1 1
      .vscode/launch.json
  2. 1 1
      package.json
  3. 2 2
      pm2.config.js
  4. 3 2
      src/app.ts
  5. 17 10
      src/utils/logger.ts

+ 1 - 1
.vscode/launch.json

@@ -19,7 +19,7 @@
     //   ],
     //   // "program": "${workspaceFolder}/src/app.ts"
     //   "program": "${workspaceFolder}/node_modules/.bin/cross-env",
-    //   "args": ["NODE_ENV=dev nodemon -e ts --exec ts-node -r tsconfig-paths/register ${workspaceFolder}/src/app.ts"]
+    //   "args": ["NODE_ENV=development nodemon -e ts --exec ts-node -r tsconfig-paths/register ${workspaceFolder}/src/app.ts"]
     // }
   ]
 }

+ 1 - 1
package.json

@@ -19,7 +19,7 @@
   "main": "index.js",
   "license": "MIT",
   "scripts": {
-    "dev": "cross-env NODE_ENV=dev nodemon -e ts --exec ts-node -r tsconfig-paths/register src/app.ts",
+    "dev": "cross-env NODE_ENV=development nodemon -e ts --exec ts-node -r tsconfig-paths/register src/app.ts",
     "start": "rm -rf ./dist && cross-env NODE_ENV=prod tsc --inlineSourceMap false"
   },
   "dependencies": {

+ 2 - 2
pm2.config.js

@@ -17,11 +17,11 @@ module.exports = {
       cwd: './',
       args: '',
       env: {
-        NODE_ENV: 'prod',
+        NODE_ENV: 'production',
         API_ENV: 'production'
       },
       env_dev: {
-        NODE_ENV: 'dev',
+        NODE_ENV: 'development',
         API_ENV: 'development'
       }
     }

+ 3 - 2
src/app.ts

@@ -41,10 +41,11 @@ app.use(koaStatic(path.join(__dirname, config.staticPath)))
 app.use(responseMiddleware());
 // post params解析
 app.use(bodyParser());
-// 本地嵌入式数据库
-app.use(localDbMiddleware())
 // 日志
 app.use(logsMiddleware());
+
+// 本地嵌入式数据库
+app.use(localDbMiddleware())
 // redis
 app.use(redisMiddleware());
 // 限流

+ 17 - 10
src/utils/logger.ts

@@ -2,15 +2,23 @@ import log4js from 'log4js';
 import path from 'path';
 import { Context } from 'koa';
 import config from '@config';
-
+interface commonInfo {
+  serverIp: string,
+  params?: any,
+  time?: number
+}
 // 输出配置
-const output = (ctx, message = '', commonInfo = {}) => {
+const output = (ctx, message: string | null | undefined , commonInfo: commonInfo) => {
   const {
     method, // 请求方式
     headers, // 请求headers
     origin, // 获取URL的来源,包括 protocol 和 host。
     originalUrl // 获取请求原始URL。
   } = ctx.request;
+  const {
+    time,
+    ...newCommonInfo
+   } = commonInfo
   interface client {
     originalUrl: string,
     userAgent: string,
@@ -23,8 +31,8 @@ const output = (ctx, message = '', commonInfo = {}) => {
   if (ctx.querystring) {
     client.query = ctx.querystring;
   };
-  let text = `[${method}] ${ctx.status} [${origin}${originalUrl}]
-req: ${JSON.stringify(Object.assign(client, commonInfo))}`;
+  let text = `[${method}] ${ctx.status} [${origin}${originalUrl}] ${time}ms
+req: ${JSON.stringify(Object.assign(client, newCommonInfo))}`;
 
   if (Object.prototype.toString.call(message) === '[object Object]'
   || Object.prototype.toString.call(message) === '[object Error]') {
@@ -43,7 +51,7 @@ const methods: string[] = ['trace', 'debug', 'info', 'warn', 'error', 'fatal', '
 const defaultConfig = {
   logLevel: 'debug', // 日志级别
   dir: path.resolve(__dirname, '../log'), // 指定日志存放目录名
-  env: 'dev', // 指定当前环境,当开发时控制台也输出
+  env: 'development', // 指定当前环境,当开发时控制台也输出
   serverIp: '127.0.0.1'
 };
 
@@ -158,19 +166,18 @@ export const middlewareLog = () => {
       };
     });
     ctx.$log = contextLogger;
+    const a = Date.now()
     await next();
+    const b = Date.now()
     if (ctx.response && ctx.status < 400) {
-      interface commonInfo {
-        serverIp: string,
-        params?: any
-      }
       const commonInfo: commonInfo = {
         serverIp,
+        time: b - a
       };
       if (ctx.request.body) {
         commonInfo.params = ctx.request.body;
       };
-      // logger.info(output(ctx, null, commonInfo))
+      logger.info(output(ctx, null, commonInfo))
     }
     else {
       ctx.throw(ctx.status, ctx.response);