@midwayjs/web 3.0.13 → 3.0.14-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/dist/logger.js CHANGED
@@ -16,6 +16,34 @@ function isEmptyFile(p) {
16
16
  });
17
17
  return content === null || content === undefined || content === '';
18
18
  }
19
+ const levelTransform = level => {
20
+ if (!level) {
21
+ return undefined;
22
+ }
23
+ switch (level) {
24
+ case 'NONE':
25
+ case Infinity: // egg logger 的 none 是这个等级
26
+ return 'none';
27
+ case 0:
28
+ case 'DEBUG':
29
+ case 'debug':
30
+ return 'debug';
31
+ case 1:
32
+ case 'INFO':
33
+ case 'info':
34
+ return 'info';
35
+ case 2:
36
+ case 'WARN':
37
+ case 'warn':
38
+ return 'warn';
39
+ case 3:
40
+ case 'ERROR':
41
+ case 'error':
42
+ return 'error';
43
+ default:
44
+ return 'silly';
45
+ }
46
+ };
19
47
  function checkEggLoggerExistsAndBackup(dir, fileName) {
20
48
  const file = (0, path_1.isAbsolute)(fileName) ? fileName : (0, path_1.join)(dir, fileName);
21
49
  if ((0, fs_1.existsSync)(file) && !(0, fs_1.lstatSync)(file).isSymbolicLink()) {
@@ -32,6 +60,13 @@ function checkEggLoggerExistsAndBackup(dir, fileName) {
32
60
  }
33
61
  }
34
62
  }
63
+ function cleanUndefinedProperty(obj) {
64
+ Object.keys(obj).forEach(key => {
65
+ if (obj[key] === undefined) {
66
+ delete obj[key];
67
+ }
68
+ });
69
+ }
35
70
  class MidwayLoggers extends Map {
36
71
  /**
37
72
  * @constructor
@@ -51,59 +86,30 @@ class MidwayLoggers extends Map {
51
86
  * - {String} eol - end of line char
52
87
  * - {String} [concentrateError = duplicate] - whether write error logger to common-error.log, `duplicate` / `redirect` / `ignore`
53
88
  * - customLogger
54
- * @param options
55
89
  * @param app
56
90
  */
57
- constructor(options, app, processType) {
58
- var _a, _b;
91
+ constructor(app) {
59
92
  super();
60
93
  /**
61
- * 日志创建的几种场景,主要考虑 2,4
62
- * 1、单进程,使用 egg logger
63
- * 2、单进程,使用 midway logger
64
- * 3、egg-scripts 多进程,使用 egg-logger
65
- * 4、egg-scripts 多进程,使用 midway logger
94
+ * egg 这里创建 loggers,并初始化 loggerService
66
95
  */
67
96
  // 这么改是为了防止 egg 日志切割时遍历属性,导致报错
68
97
  Object.defineProperty(this, 'app', {
69
98
  value: app,
70
99
  enumerable: false,
71
100
  });
72
- /**
73
- * 提前备份 egg 日志
74
- */
75
- for (const name of [
76
- options.logger.appLogName,
77
- options.logger.coreLogName,
78
- options.logger.agentLogName,
79
- options.logger.errorLogName,
80
- ]) {
81
- checkEggLoggerExistsAndBackup(options.logger.dir, name);
82
- }
83
- /**
84
- * 走到这里,有几种情况
85
- * 1、egg-scripts 启动,并使用了 midway logger,egg 先启动了
86
- * 2、单进程启动,但是没有 configuration,midway 没读到配置,日志服务没初始化
87
- * 3、再走一遍日志创建,把 egg 插件配置的日志再初始化一遍
88
- */
89
- const loggerService = new core_1.MidwayLoggerService(null);
90
- loggerService.configService = {
91
- getConfiguration(configKey) {
92
- if (configKey) {
93
- return (0, core_1.safelyGet)(configKey, options);
94
- }
95
- return this.configuration;
96
- },
97
- };
98
- const midwayLoggerConfig = loggerService.transformEggLogger(options);
99
- (0, core_1.extend)(true, options, midwayLoggerConfig);
100
- if ((_a = options === null || options === void 0 ? void 0 : options.midwayLogger) === null || _a === void 0 ? void 0 : _a.clients) {
101
- // 从 egg 过来,这里有可能没有 dir
102
- if (!((_b = options.midwayLogger['default']) === null || _b === void 0 ? void 0 : _b.dir)) {
103
- options.midwayLogger.default['dir'] = options.logger.dir;
101
+ const configService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayConfigService);
102
+ // 先把 egg 的日志配置转为 midway logger 配置
103
+ if (configService.getConfiguration('customLogger')) {
104
+ const eggLoggerConfig = this.transformEggLogger(configService.getConfiguration('customLogger'));
105
+ if (eggLoggerConfig) {
106
+ configService.addObject(eggLoggerConfig);
104
107
  }
105
- for (const id of Object.keys(options.midwayLogger.clients)) {
106
- const config = Object.assign({}, options.midwayLogger['default'], options.midwayLogger.clients[id]);
108
+ }
109
+ const loggerConfig = configService.getConfiguration('midwayLogger');
110
+ if (loggerConfig) {
111
+ for (const id of Object.keys(loggerConfig.clients)) {
112
+ const config = Object.assign({}, loggerConfig['default'], loggerConfig.clients[id]);
107
113
  this.createLogger(config, id);
108
114
  }
109
115
  }
@@ -111,16 +117,18 @@ class MidwayLoggers extends Map {
111
117
  this['logger'] = logger_1.loggers.getLogger('appLogger');
112
118
  this.set('logger', logger_1.loggers.getLogger('appLogger'));
113
119
  }
114
- if (logger_1.loggers.has('coreLogger')) {
115
- this.createLogger({}, 'coreLogger');
116
- this.createLogger({}, 'appLogger');
117
- this.createLogger({}, 'agentLogger');
118
- }
119
- else {
120
- console.log('-----请在 logger 里配置 clients');
121
- }
120
+ // 初始化日志服务
121
+ this.loggerService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayLoggerService, [(0, core_1.getCurrentApplicationContext)()]);
122
+ // 防止循环枚举报错
123
+ Object.defineProperty(this, 'loggerService', {
124
+ enumerable: false,
125
+ });
122
126
  }
123
127
  createLogger(options, loggerKey) {
128
+ /**
129
+ * 提前备份 egg 日志
130
+ */
131
+ checkEggLoggerExistsAndBackup(options.dir, options.fileLogName);
124
132
  const logger = logger_1.loggers.createLogger(loggerKey, options);
125
133
  // overwrite values for pandora collect
126
134
  logger.values = () => {
@@ -149,25 +157,36 @@ class MidwayLoggers extends Map {
149
157
  }
150
158
  }
151
159
  }
160
+ transformEggLogger(eggCustomLogger) {
161
+ var _a, _b, _c;
162
+ const transformLoggerConfig = {
163
+ midwayLogger: {
164
+ clients: {},
165
+ },
166
+ };
167
+ for (const name in eggCustomLogger) {
168
+ transformLoggerConfig.midwayLogger.clients[name] = {
169
+ fileLogName: (_a = eggCustomLogger[name]) === null || _a === void 0 ? void 0 : _a.file,
170
+ level: levelTransform((_b = eggCustomLogger[name]) === null || _b === void 0 ? void 0 : _b.level),
171
+ consoleLevel: levelTransform((_c = eggCustomLogger[name]) === null || _c === void 0 ? void 0 : _c.consoleLevel),
172
+ };
173
+ cleanUndefinedProperty(transformLoggerConfig.midwayLogger.clients[name]);
174
+ }
175
+ return transformLoggerConfig;
176
+ }
152
177
  }
153
178
  const createLoggers = (app, processType) => {
154
- const loggerConfig = app.config.logger;
155
- loggerConfig.type = app.type;
156
- if (app.config.env === 'prod' &&
157
- loggerConfig.level === 'DEBUG' &&
158
- !loggerConfig.allowDebugAtProd) {
159
- loggerConfig.level = 'INFO';
160
- }
161
179
  // 现在只走 midway logger
162
- const loggers = new MidwayLoggers(app.config, app, processType);
180
+ const loggers = new MidwayLoggers(app);
163
181
  // won't print to console after started, except for local and unittest
164
182
  app.ready(() => {
165
- if (loggerConfig.disableConsoleAfterReady) {
183
+ var _a;
184
+ if ((_a = app.config.logger) === null || _a === void 0 ? void 0 : _a.disableConsoleAfterReady) {
166
185
  loggers.disableConsole();
167
186
  }
168
187
  });
169
188
  debug(`[egg]: create loggers in ${processType}`);
170
- loggers['coreLogger'].info('[egg:logger] init all loggers with options: %j', loggerConfig);
189
+ loggers['coreLogger'].info('[egg:logger] init all loggers with options: %j', app.config.midwayLogger);
171
190
  return loggers;
172
191
  };
173
192
  exports.createLoggers = createLoggers;
package/dist/utils.d.ts CHANGED
@@ -1,4 +1,3 @@
1
- import { IMidwayBootstrapOptions } from '@midwayjs/core';
2
1
  export declare function isTypeScriptEnvironment(): boolean;
3
2
  export declare const parseNormalDir: (baseDir: string, isTypescript?: boolean) => {
4
3
  baseDir: string;
@@ -6,5 +5,5 @@ export declare const parseNormalDir: (baseDir: string, isTypescript?: boolean) =
6
5
  };
7
6
  export declare const findLernaRoot: (findRoot?: string) => string;
8
7
  export declare const getCurrentDateString: (timestamp?: number) => string;
9
- export declare function initializeAgentApplicationContext(agent: any, globalOptions: Omit<IMidwayBootstrapOptions, 'applicationContext'>): Promise<import("@midwayjs/core").IMidwayContainer>;
8
+ export declare function initializeAgentApplicationContext(agent: any): Promise<import("@midwayjs/core").IMidwayContainer>;
10
9
  //# sourceMappingURL=utils.d.ts.map
package/dist/utils.js CHANGED
@@ -66,75 +66,12 @@ const getCurrentDateString = (timestamp = Date.now()) => {
66
66
  .padStart(2, '0')}-${d.getDate().toString().padStart(2, '0')}`;
67
67
  };
68
68
  exports.getCurrentDateString = getCurrentDateString;
69
- async function initializeAgentApplicationContext(agent, globalOptions) {
70
- var _a, _b, _c;
71
- if (!(0, core_1.getCurrentApplicationContext)()) {
72
- debug('[egg]: start "initializeGlobalApplicationContext"');
73
- const appDir = (_a = globalOptions.appDir) !== null && _a !== void 0 ? _a : '';
74
- const baseDir = (_b = globalOptions.baseDir) !== null && _b !== void 0 ? _b : '';
75
- // new container
76
- const applicationContext = new core_1.MidwayContainer();
77
- debug('[egg]: delegate module map from decoratorManager');
78
- (0, decorator_1.bindContainer)(applicationContext);
79
- global['MIDWAY_APPLICATION_CONTEXT'] = applicationContext;
80
- // register baseDir and appDir
81
- applicationContext.registerObject('baseDir', baseDir);
82
- applicationContext.registerObject('appDir', appDir);
83
- if (globalOptions.moduleDirector !== false) {
84
- if (globalOptions.moduleDetector === undefined ||
85
- globalOptions.moduleDetector === 'file') {
86
- applicationContext.setFileDetector(new core_1.DirectoryFileDetector({
87
- loadDir: baseDir,
88
- ignore: (_c = globalOptions.ignore) !== null && _c !== void 0 ? _c : [],
89
- }));
90
- }
91
- else if (globalOptions.moduleDetector) {
92
- applicationContext.setFileDetector(globalOptions.moduleDetector);
93
- }
94
- }
95
- // bind inner service
96
- applicationContext.bindClass(core_1.MidwayEnvironmentService);
97
- applicationContext.bindClass(core_1.MidwayInformationService);
98
- applicationContext.bindClass(core_1.MidwayDecoratorService);
99
- applicationContext.bindClass(core_1.MidwayConfigService);
100
- applicationContext.bindClass(core_1.MidwayAspectService);
101
- applicationContext.bindClass(core_1.MidwayLoggerService);
102
- // bind preload module
103
- if (globalOptions.preloadModules && globalOptions.preloadModules.length) {
104
- for (const preloadModule of globalOptions.preloadModules) {
105
- applicationContext.bindClass(preloadModule);
106
- }
107
- }
108
- // init default config
109
- const configService = await applicationContext.getAsync(core_1.MidwayConfigService);
110
- // add egg config here, it will be ignore midway and component config
111
- configService.add([
112
- {
113
- default: agent.config,
114
- },
115
- ]);
69
+ async function initializeAgentApplicationContext(agent) {
70
+ if (process.env['EGG_CLUSTER_MODE'] === 'true') {
116
71
  // init aop support
117
- const aspectService = await applicationContext.getAsync(core_1.MidwayAspectService, [applicationContext]);
72
+ const aspectService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayAspectService);
118
73
  // init decorator service
119
- const decoratorService = await applicationContext.getAsync(core_1.MidwayDecoratorService, [applicationContext]);
120
- if (!globalOptions.imports) {
121
- globalOptions.imports = [
122
- (0, core_1.safeRequire)((0, path_1.join)(globalOptions.baseDir, 'configuration')),
123
- ];
124
- }
125
- for (const configurationModule of [].concat(globalOptions.imports)) {
126
- // load configuration and component
127
- applicationContext.load(configurationModule);
128
- }
129
- // bind user code module
130
- await applicationContext.ready();
131
- // merge config
132
- await configService.load();
133
- debug('[core]: Current config = %j', configService.getConfiguration());
134
- // init logger
135
- await applicationContext.getAsync(core_1.MidwayLoggerService, [
136
- applicationContext,
137
- ]);
74
+ const decoratorService = (0, core_1.getCurrentApplicationContext)().get(core_1.MidwayDecoratorService);
138
75
  // framework/config/plugin/logger/app decorator support
139
76
  // register base config hook
140
77
  decoratorService.registerPropertyHandler(decorator_1.CONFIG_KEY, (propertyName, meta) => {
@@ -164,6 +101,7 @@ async function initializeAgentApplicationContext(agent, globalOptions) {
164
101
  });
165
102
  // init aspect module
166
103
  await aspectService.loadAspect();
104
+ debug('[egg]: added extra for "initializeAgentApplicationContext" in cluster mode');
167
105
  }
168
106
  else {
169
107
  debug('[egg]: "initializeAgentApplicationContext" ignore re-init in single process');
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "@midwayjs/web",
3
- "version": "3.0.13",
3
+ "version": "3.0.14-beta.1",
4
4
  "description": "Midway Web Framework for Egg.js",
5
5
  "main": "dist/index",
6
6
  "typings": "dist/index.d.ts",
@@ -48,6 +48,7 @@
48
48
  "@eggjs/router": "^2.0.0",
49
49
  "@midwayjs/core": "^3.0.13",
50
50
  "egg": "^2.28.0",
51
+ "egg-cluster": "^1.27.1",
51
52
  "find-up": "5.0.0",
52
53
  "mkdirp": "^1.0.4"
53
54
  },
@@ -59,5 +60,5 @@
59
60
  "engines": {
60
61
  "node": ">=12"
61
62
  },
62
- "gitHead": "8c8338f4488ec65765c342dd5238ed3e61872b37"
63
+ "gitHead": "a603d2348d6141f8f723901498f03a162a037708"
63
64
  }
package/LICENSE DELETED
@@ -1,21 +0,0 @@
1
- MIT License
2
-
3
- Copyright (c) 2013 - Now midwayjs
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy
6
- of this software and associated documentation files (the "Software"), to deal
7
- in the Software without restriction, including without limitation the rights
8
- to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
- copies of the Software, and to permit persons to whom the Software is
10
- furnished to do so, subject to the following conditions:
11
-
12
- The above copyright notice and this permission notice shall be included in all
13
- copies or substantial portions of the Software.
14
-
15
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
- IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
- FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
- AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
- LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
- OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
- SOFTWARE.
@@ -1,54 +0,0 @@
1
- 'use strict';
2
-
3
- const path = require('path');
4
- const mkdirp = require('mkdirp');
5
- const os = require('os');
6
- const fs = require('fs');
7
-
8
- module.exports = appInfo => {
9
- const exports = {};
10
-
11
- exports.rundir = path.join(appInfo.appDir, 'run');
12
- // 修改默认的日志名
13
- exports.midwayLogger = {
14
- clients: {
15
- coreLogger: {
16
- fileLogName: 'midway-core.log',
17
- },
18
- appLogger: {
19
- fileLogName: 'midway-web.log',
20
- aliasName: 'logger',
21
- },
22
- agentLogger: {
23
- fileLogName: 'midway-agent.log',
24
- },
25
- },
26
- };
27
-
28
- exports.pluginOverwrite = false;
29
-
30
- exports.security = {
31
- csrf: {
32
- ignoreJSON: false,
33
- },
34
- };
35
-
36
- // alinode runtime 写入的日志策略是: 如果 NODE_LOG_DIR 有设置,写入 NODE_LOG_DIR 设置的目录;否则为 /tmp
37
- let alinodeLogdir = fs.existsSync('/tmp') ? '/tmp' : os.tmpdir();
38
- // try to use NODE_LOG_DIR first
39
- if (process.env.NODE_LOG_DIR) {
40
- alinodeLogdir = process.env.NODE_LOG_DIR;
41
- }
42
- mkdirp.sync(alinodeLogdir);
43
-
44
- exports.alinode = {
45
- logdir: alinodeLogdir,
46
- error_log: [
47
- path.join(appInfo.root, `logs/${appInfo.pkg.name}/common-error.log`),
48
- path.join(appInfo.root, 'logs/stderr.log'),
49
- ],
50
- packages: [path.join(appInfo.appDir, 'package.json')],
51
- };
52
-
53
- return exports;
54
- };