diff --git a/cicd/test_script/ca-gen.sh b/cicd/test_script/ca-gen.sh index 66005e23..8d6a4728 100755 --- a/cicd/test_script/ca-gen.sh +++ b/cicd/test_script/ca-gen.sh @@ -1,8 +1,7 @@ -#!/bin/bash -ve +#! /bin/bash -ve -export NODE_ENV=development # testing development production +export NODE_ENV=production # testing development production export BDK_NETWORK_NAME=shell-network-ca -export DOCKER_LOGGING=true export BDK_ORG_TYPE=peer ICA_DOMAIN_BEN='ica.ben.cathaybc.com' diff --git a/cicd/test_script/crypto-gen.sh b/cicd/test_script/crypto-gen.sh index d20324dc..5a62e03e 100755 --- a/cicd/test_script/crypto-gen.sh +++ b/cicd/test_script/crypto-gen.sh @@ -1,8 +1,7 @@ -#!/bin/bash -ve +#! /bin/bash -ve -export NODE_ENV=development # testing development production +export NODE_ENV=production # testing development production export BDK_NETWORK_NAME=shell-network-cryptogen -export DOCKER_LOGGING=true export BDK_ORG_TYPE=peer ORDERER_ORG_DOMAIN_BEN=$(jq --raw-output '.ordererOrgs[0].domain' ./cicd/test_script/network-create.json) diff --git a/package-lock.json b/package-lock.json index 85189c1a..faed1d16 100644 --- a/package-lock.json +++ b/package-lock.json @@ -35,18 +35,19 @@ "@types/sinon": "^9.0.8", "@types/source-map-support": "^0.5.3", "@types/string-format": "^2.0.0", + "@types/triple-beam": "^1.3.2", "@types/yargs": "^15.0.5", "ericlint": "^1.1.3", "mocha": "^9.1.3", "mocha-sonarqube-reporter": "^1.0.2", - "nodemon": "^2.0.4", + "nodemon": "^2.0.15", "nyc": "^15.1.0", "semver": "^7.3.5", "sinon": "^9.2.0", "source-map-support": "^0.5.19", - "ts-node": "^9.0.0", + "ts-node": "^10.4.0", "typedoc": "^0.21.2", - "typescript": "^4.3" + "typescript": "^4.5.4" }, "engines": { "node": ">=12.0.0" @@ -488,6 +489,27 @@ "node": ">=6.9.0" } }, + "node_modules/@cspotcode/source-map-consumer": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz", + "integrity": "sha512-41qniHzTU8yAGbCp04ohlmSrZf8bkf/iJsl3V0dRGsQN/5GFfx+LbCSsCpp2gqrqjTVg/K6O8ycoV35JIwAzAg==", + "dev": true, + "engines": { + "node": ">= 12" + } + }, + "node_modules/@cspotcode/source-map-support": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.7.0.tgz", + "integrity": "sha512-X4xqRHqN8ACt2aHVe51OxeA2HjbcL4MqFqXkrmQszJ1NOUuUu5u6Vqx/0lZSVNku7velL5FC/s5uEAj1lsBMhA==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-consumer": "0.8.0" + }, + "engines": { + "node": ">=12" + } + }, "node_modules/@dabh/diagnostics": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.2.tgz", @@ -779,6 +801,30 @@ "node": ">=6" } }, + "node_modules/@tsconfig/node10": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz", + "integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==", + "dev": true + }, + "node_modules/@tsconfig/node12": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz", + "integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==", + "dev": true + }, + "node_modules/@tsconfig/node14": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz", + "integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==", + "dev": true + }, + "node_modules/@tsconfig/node16": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz", + "integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==", + "dev": true + }, "node_modules/@types/axios": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.0.tgz", @@ -906,6 +952,12 @@ "integrity": "sha512-mMwtmgN0ureESnJ3SuMM4W9lsi4CgOxs43YxNo14SDHgzJ+OPYO3yM7nOTJTh8x5YICseBdtrySUbvxnpb+NYQ==", "dev": true }, + "node_modules/@types/triple-beam": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.2.tgz", + "integrity": "sha512-txGIh+0eDFzKGC25zORnswy+br1Ha7hj5cMVwKIU7+s0U2AxxJru/jZSMU6OC9MJWP6+pc/hc6ZjyZShpsyY2g==", + "dev": true + }, "node_modules/@types/yargs": { "version": "15.0.14", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.14.tgz", @@ -1111,6 +1163,15 @@ "acorn": "^6.0.0 || ^7.0.0 || ^8.0.0" } }, + "node_modules/acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true, + "engines": { + "node": ">=0.4.0" + } + }, "node_modules/aggregate-error": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", @@ -5708,29 +5769,44 @@ "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==" }, "node_modules/ts-node": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-9.1.1.tgz", - "integrity": "sha512-hPlt7ZACERQGf03M253ytLY3dHbGNGrAq9qIHWUY9XHYl1z7wYngSr3OQ5xmui8o2AaxsONxIzjafLUiWBo1Fg==", - "dev": true, - "dependencies": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz", + "integrity": "sha512-g0FlPvvCXSIO1JDF6S232P5jPYqBkRL9qly81ZgAOSU7rwI0stphCgd2kLiCrU9DjQCrJMWEqcNSjQL02s6d8A==", + "dev": true, + "dependencies": { + "@cspotcode/source-map-support": "0.7.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", "arg": "^4.1.0", "create-require": "^1.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", - "source-map-support": "^0.5.17", "yn": "3.1.1" }, "bin": { "ts-node": "dist/bin.js", + "ts-node-cwd": "dist/bin-cwd.js", "ts-node-script": "dist/bin-script.js", "ts-node-transpile-only": "dist/bin-transpile.js", "ts-script": "dist/bin-script-deprecated.js" }, - "engines": { - "node": ">=10.0.0" - }, "peerDependencies": { + "@swc/core": ">=1.2.50", + "@swc/wasm": ">=1.2.50", + "@types/node": "*", "typescript": ">=2.7" + }, + "peerDependenciesMeta": { + "@swc/core": { + "optional": true + }, + "@swc/wasm": { + "optional": true + } } }, "node_modules/ts-node/node_modules/diff": { @@ -5878,9 +5954,9 @@ } }, "node_modules/typescript": { - "version": "4.4.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.4.4.tgz", - "integrity": "sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", + "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", "dev": true, "bin": { "tsc": "bin/tsc", @@ -6640,6 +6716,21 @@ "to-fast-properties": "^2.0.0" } }, + "@cspotcode/source-map-consumer": { + "version": "0.8.0", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-consumer/-/source-map-consumer-0.8.0.tgz", + "integrity": "sha512-41qniHzTU8yAGbCp04ohlmSrZf8bkf/iJsl3V0dRGsQN/5GFfx+LbCSsCpp2gqrqjTVg/K6O8ycoV35JIwAzAg==", + "dev": true + }, + "@cspotcode/source-map-support": { + "version": "0.7.0", + "resolved": "https://registry.npmjs.org/@cspotcode/source-map-support/-/source-map-support-0.7.0.tgz", + "integrity": "sha512-X4xqRHqN8ACt2aHVe51OxeA2HjbcL4MqFqXkrmQszJ1NOUuUu5u6Vqx/0lZSVNku7velL5FC/s5uEAj1lsBMhA==", + "dev": true, + "requires": { + "@cspotcode/source-map-consumer": "0.8.0" + } + }, "@dabh/diagnostics": { "version": "2.0.2", "resolved": "https://registry.npmjs.org/@dabh/diagnostics/-/diagnostics-2.0.2.tgz", @@ -6872,6 +6963,30 @@ "defer-to-connect": "^1.0.1" } }, + "@tsconfig/node10": { + "version": "1.0.8", + "resolved": "https://registry.npmjs.org/@tsconfig/node10/-/node10-1.0.8.tgz", + "integrity": "sha512-6XFfSQmMgq0CFLY1MslA/CPUfhIL919M1rMsa5lP2P097N2Wd1sSX0tx1u4olM16fLNhtHZpRhedZJphNJqmZg==", + "dev": true + }, + "@tsconfig/node12": { + "version": "1.0.9", + "resolved": "https://registry.npmjs.org/@tsconfig/node12/-/node12-1.0.9.tgz", + "integrity": "sha512-/yBMcem+fbvhSREH+s14YJi18sp7J9jpuhYByADT2rypfajMZZN4WQ6zBGgBKp53NKmqI36wFYDb3yaMPurITw==", + "dev": true + }, + "@tsconfig/node14": { + "version": "1.0.1", + "resolved": "https://registry.npmjs.org/@tsconfig/node14/-/node14-1.0.1.tgz", + "integrity": "sha512-509r2+yARFfHHE7T6Puu2jjkoycftovhXRqW328PDXTVGKihlb1P8Z9mMZH04ebyajfRY7dedfGynlrFHJUQCg==", + "dev": true + }, + "@tsconfig/node16": { + "version": "1.0.2", + "resolved": "https://registry.npmjs.org/@tsconfig/node16/-/node16-1.0.2.tgz", + "integrity": "sha512-eZxlbI8GZscaGS7kkc/trHTT5xgrjH3/1n2JDwusC9iahPKWMRvRjJSAN5mCXviuTGQ/lHnhvv8Q1YTpnfz9gA==", + "dev": true + }, "@types/axios": { "version": "0.14.0", "resolved": "https://registry.npmjs.org/@types/axios/-/axios-0.14.0.tgz", @@ -6998,6 +7113,12 @@ "integrity": "sha512-mMwtmgN0ureESnJ3SuMM4W9lsi4CgOxs43YxNo14SDHgzJ+OPYO3yM7nOTJTh8x5YICseBdtrySUbvxnpb+NYQ==", "dev": true }, + "@types/triple-beam": { + "version": "1.3.2", + "resolved": "https://registry.npmjs.org/@types/triple-beam/-/triple-beam-1.3.2.tgz", + "integrity": "sha512-txGIh+0eDFzKGC25zORnswy+br1Ha7hj5cMVwKIU7+s0U2AxxJru/jZSMU6OC9MJWP6+pc/hc6ZjyZShpsyY2g==", + "dev": true + }, "@types/yargs": { "version": "15.0.14", "resolved": "https://registry.npmjs.org/@types/yargs/-/yargs-15.0.14.tgz", @@ -7121,6 +7242,12 @@ "dev": true, "requires": {} }, + "acorn-walk": { + "version": "8.2.0", + "resolved": "https://registry.npmjs.org/acorn-walk/-/acorn-walk-8.2.0.tgz", + "integrity": "sha512-k+iyHEuPgSw6SbuDpGQM+06HQUa04DZ3o+F6CSzXMvvI5KMvnaEqXe+YVe555R9nn6GPt404fos4wcgpw12SDA==", + "dev": true + }, "aggregate-error": { "version": "3.1.0", "resolved": "https://registry.npmjs.org/aggregate-error/-/aggregate-error-3.1.0.tgz", @@ -10553,16 +10680,22 @@ "integrity": "sha512-XrHUvV5HpdLmIj4uVMxHggLbFSZYIn7HEWsqePZcI50pco+MPqJ50wMGY794X7AOOhxOBAjbkqfAbEe/QMp2Lw==" }, "ts-node": { - "version": "9.1.1", - "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-9.1.1.tgz", - "integrity": "sha512-hPlt7ZACERQGf03M253ytLY3dHbGNGrAq9qIHWUY9XHYl1z7wYngSr3OQ5xmui8o2AaxsONxIzjafLUiWBo1Fg==", - "dev": true, - "requires": { + "version": "10.4.0", + "resolved": "https://registry.npmjs.org/ts-node/-/ts-node-10.4.0.tgz", + "integrity": "sha512-g0FlPvvCXSIO1JDF6S232P5jPYqBkRL9qly81ZgAOSU7rwI0stphCgd2kLiCrU9DjQCrJMWEqcNSjQL02s6d8A==", + "dev": true, + "requires": { + "@cspotcode/source-map-support": "0.7.0", + "@tsconfig/node10": "^1.0.7", + "@tsconfig/node12": "^1.0.7", + "@tsconfig/node14": "^1.0.0", + "@tsconfig/node16": "^1.0.2", + "acorn": "^8.4.1", + "acorn-walk": "^8.1.1", "arg": "^4.1.0", "create-require": "^1.1.0", "diff": "^4.0.1", "make-error": "^1.1.1", - "source-map-support": "^0.5.17", "yn": "3.1.1" }, "dependencies": { @@ -10676,9 +10809,9 @@ "dev": true }, "typescript": { - "version": "4.4.4", - "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.4.4.tgz", - "integrity": "sha512-DqGhF5IKoBl8WNf8C1gu8q0xZSInh9j1kJJMqT3a94w1JzVaBU4EXOSMrz9yDqMT0xt3selp83fuFMQ0uzv6qA==", + "version": "4.5.4", + "resolved": "https://registry.npmjs.org/typescript/-/typescript-4.5.4.tgz", + "integrity": "sha512-VgYs2A2QIRuGphtzFV7aQJduJ2gyfTljngLzjpfW9FoYZF6xuw1W0vW9ghCKLfcWrCFxK81CSGRAvS1pn4fIUg==", "dev": true }, "uglify-js": { diff --git a/package.json b/package.json index 459ef3da..bbb20146 100644 --- a/package.json +++ b/package.json @@ -63,18 +63,19 @@ "@types/sinon": "^9.0.8", "@types/source-map-support": "^0.5.3", "@types/string-format": "^2.0.0", + "@types/triple-beam": "^1.3.2", "@types/yargs": "^15.0.5", "ericlint": "^1.1.3", "mocha": "^9.1.3", "mocha-sonarqube-reporter": "^1.0.2", - "nodemon": "^2.0.4", + "nodemon": "^2.0.15", "nyc": "^15.1.0", "semver": "^7.3.5", "sinon": "^9.2.0", "source-map-support": "^0.5.19", - "ts-node": "^9.0.0", + "ts-node": "^10.4.0", "typedoc": "^0.21.2", - "typescript": "^4.3" + "typescript": "^4.5.4" }, "engines": { "node": ">=12.0.0" diff --git a/src/command/chaincode/install.ts b/src/command/chaincode/install.ts index 5c8a2f78..e76ce39a 100644 --- a/src/command/chaincode/install.ts +++ b/src/command/chaincode/install.ts @@ -24,7 +24,7 @@ export const builder = (yargs: Argv) => { } export const handler = async (argv: Arguments) => { - logger.debug('[*] exec chaincode install') + logger.debug('exec chaincode install') const chaincode = new Chaincode(config) diff --git a/src/command/chaincode/invoke.ts b/src/command/chaincode/invoke.ts index 01aa89e2..bf598629 100644 --- a/src/command/chaincode/invoke.ts +++ b/src/command/chaincode/invoke.ts @@ -124,8 +124,7 @@ export const handler = async (argv: Arguments) => { const invokeResult = await chaincode.invoke(invokeChannelInput) if (!('stdout' in invokeResult)) { - logger.error('command only for docker infra') throw new Error('command only for docker infra') } - logger.info(`invoke result =>\n${JSON.stringify(Chaincode.parser.invoke(invokeResult))}`) + logger.info(`${JSON.stringify(Chaincode.parser.invoke(invokeResult))}`) } diff --git a/src/command/chaincode/query.ts b/src/command/chaincode/query.ts index 73235fa9..36391f19 100644 --- a/src/command/chaincode/query.ts +++ b/src/command/chaincode/query.ts @@ -76,8 +76,7 @@ export const handler = async (argv: Arguments) => { const queryResult = await chaincode.query(queryChannelInput) if (!('stdout' in queryResult)) { - logger.error('command only for docker infra') throw new Error('command only for docker infra') } - logger.info(`query result =>\n${JSON.stringify(Chaincode.parser.query(queryResult))}`) + logger.info(`${JSON.stringify(Chaincode.parser.query(queryResult))}`) } diff --git a/src/command/config/ls.ts b/src/command/config/ls.ts index 7dd7adf9..1be6d3d1 100644 --- a/src/command/config/ls.ts +++ b/src/command/config/ls.ts @@ -15,5 +15,5 @@ export const handler = () => { const envConfig = configService.ls() - logger.info(`current .env config =>\n${JSON.stringify(envConfig)}`) + logger.info(`${JSON.stringify(envConfig)}`) } diff --git a/src/command/hello.ts b/src/command/hello.ts index 93edb7cf..b8b25038 100644 --- a/src/command/hello.ts +++ b/src/command/hello.ts @@ -1,32 +1,14 @@ import { Argv, Arguments } from 'yargs' import { hello } from '../service/hello' -export const command = 'hello [yyy]' +export const command = 'hello' export const desc = '歡迎使用 Cathay BDK' -interface ArgType { - xxx: string - yyy?: string -} -interface OptType { - a: boolean - b?: string - c?: number - interactive: boolean -} - -export const builder = (yargs: Argv) => { +export const builder = (yargs: Argv) => { return yargs - .positional('xxx', { type: 'string' }) - .positional('yyy', { type: 'number' }) - .option('a', { type: 'boolean', default: false }) - .option('b', { type: 'string' }) - .option('c', { type: 'string', choices: ['1', '2', '3'], alias: 'chill' }) - .option('interactive', { type: 'boolean', default: true, description: '是否使用 Cathay BDK 互動式問答', alias: 'i' }) } -export const handler = (argv: Arguments) => { - console.log(process.env.NODE_ENV) +export const handler = (argv: Arguments) => { hello(argv) } diff --git a/src/config.ts b/src/config.ts index 7a0bc9bc..7d70c7d2 100644 --- a/src/config.ts +++ b/src/config.ts @@ -43,7 +43,7 @@ export interface Config { environment: EnvironmentEnum isDevMode: boolean isTestMode: boolean - dockerLogging: boolean + isSillyMode: boolean infraConfig: InfraConfig networkName: string orgName: string @@ -82,7 +82,7 @@ const config: Config = { environment: environment, isDevMode: isDevMode, isTestMode: isTestMode, - dockerLogging: (process.env.DOCKER_LOGGING?.toLowerCase() === 'true') || false, + isSillyMode: (process.env.LOGGER_SILLY?.toLowerCase() === 'true') || false, infraConfig: { bdkPath: bdkPath, dockerHostPath: process.env.BDK_DOCKER_HOST_PATH || bdkPath, diff --git a/src/instance/ca.ts b/src/instance/ca.ts index a24c68c7..33e1e495 100644 --- a/src/instance/ca.ts +++ b/src/instance/ca.ts @@ -15,12 +15,12 @@ export default class CA extends AbstractInstance { } public async up (): Promise { - logger.info(`[*] CA instance up: ${this.caName}`) + logger.debug(`CA instance up: ${this.caName}`) return await this.infra.upInBackground(this.dockerComposePath) } public async down (): Promise { - logger.info(`[*] CA instance down: ${this.caName}`) + logger.debug(`CA instance down: ${this.caName}`) return await this.infra.downAndRemoveVolumes(this.dockerComposePath) } } diff --git a/src/instance/explorer.ts b/src/instance/explorer.ts index f4949d8e..2091c12f 100644 --- a/src/instance/explorer.ts +++ b/src/instance/explorer.ts @@ -12,17 +12,17 @@ export default class Explorer extends AbstractInstance { } public async up (): Promise { - logger.info('[*] Explorer instance up') + logger.debug('Explorer instance up') return await this.infra.upInBackground(this.dockerComposePath) } public async down (): Promise { - logger.info('[*] Explorer instance down') + logger.debug('Explorer instance down') return await this.infra.downAndRemoveVolumes(this.dockerComposePath) } public async restart (): Promise { - logger.info('[*] Explorer instance restart') + logger.debug('Explorer instance restart') return await this.infra.restart(this.dockerComposePath, [`explorer.${this.config.networkName}`]) } } diff --git a/src/instance/infra/InfraRunner.interface.ts b/src/instance/infra/InfraRunner.interface.ts index 48340a05..73310d6c 100644 --- a/src/instance/infra/InfraRunner.interface.ts +++ b/src/instance/infra/InfraRunner.interface.ts @@ -1,10 +1,16 @@ import { DockerRunCommandType } from '../../model/type/docker.type' +/** + * Infra return type when direct use docker + */ export interface DockerResultType { statusCode?: number stdout: string } +/** + * Infra return type when use agent or custom infra + */ export interface InfraResultType { uuid: string } @@ -16,7 +22,7 @@ export interface InfraRunner { runCommand(payload: DockerRunCommandType): Promise upInBackground(dockerComposeFile: string): Promise downAndRemoveVolumes(dockerComposeFile: string): Promise - restart (dockerComposeFile: string, service: string[]): Promise + restart(dockerComposeFile: string, service: string[]): Promise } // Strategy diff --git a/src/instance/infra/docker/runner.ts b/src/instance/infra/docker/runner.ts index 4e43f18f..43e9aaa7 100644 --- a/src/instance/infra/docker/runner.ts +++ b/src/instance/infra/docker/runner.ts @@ -25,10 +25,6 @@ export class Runner implements InfraRunner { }) } - private logger = (content: string) => { - config.dockerLogging && logger.debug(content) - } - public runCommand = async (payload: DockerRunCommandType): Promise => { await this.checkAndCreateNetwork(payload.network) const { image, tag, commands } = payload @@ -53,7 +49,7 @@ export class Runner implements InfraRunner { this.existingImages[`${image}:${tag}`] = true } } - this.logger(`docker command: \ndocker run ${createOptions.HostConfig?.AutoRemove ? '--rm ' : ''} -u ${config.UID}:${config.GID} ${createOptions.HostConfig?.NetworkMode ? `--network ${createOptions.HostConfig?.NetworkMode} ` : ''}${(createOptions.HostConfig?.Binds || []).map(x => `-v ${x} `).join('')}${(createOptions.Env || []).map(x => `--env ${x} `).join('')}${image}:${tag || 'latest'} ${commands.join(' ')}`) + logger.silly(`docker command: \ndocker run ${createOptions.HostConfig?.AutoRemove ? '--rm ' : ''} -u ${config.UID}:${config.GID} ${createOptions.HostConfig?.NetworkMode ? `--network ${createOptions.HostConfig?.NetworkMode} ` : ''}${(createOptions.HostConfig?.Binds || []).map(x => `-v ${x} `).join('')}${(createOptions.Env || []).map(x => `--env ${x} `).join('')}${image}:${tag || 'latest'} ${commands.join(' ')}`) const startOptions: DockerStartOptionsType = payload.startOptions || {} as DockerStartOptionsType try { const stdout = new WritableStream() @@ -63,7 +59,7 @@ export class Runner implements InfraRunner { stdout, createOptions, startOptions) - this.logger(`run command output: \n${stdout.toString()}`) + logger.silly(`run command output: \n${stdout.toString()}`) logger.debug(`docker run\n image: ${image}\n commands: ${commands.join(' ')}`) if (dockerRunResult[0].StatusCode !== 0) { throw new FabricContainerError(`[x] [in-docker-container error] ${stdout.toString().split('\r\n').filter(x => x.match(/error/i))}`, stdout.toString()) @@ -93,7 +89,7 @@ export class Runner implements InfraRunner { if (spawnReturn.error) { throw new DockerError(`[x] command [docker-compose]: ${spawnReturn.error.message}`) } - this.logger(spawnReturn.output.join('\n')) + logger.silly(spawnReturn.output.join('\n')) return spawnReturn.output.join('\n') } diff --git a/src/instance/orderer.ts b/src/instance/orderer.ts index 6f41f61d..bc812638 100644 --- a/src/instance/orderer.ts +++ b/src/instance/orderer.ts @@ -15,13 +15,13 @@ export default class Orderer extends AbstractInstance { } public async up (): Promise { - logger.info(`[*] Orderer instance up: ${this.ordererOrgName}`) + logger.debug(`Orderer instance up: ${this.ordererOrgName}`) return await this.infra.upInBackground(this.dockerComposePath) } public async down (): Promise { - logger.info(`[*] Orderer instance down: ${this.ordererOrgName}`) + logger.debug(`Orderer instance down: ${this.ordererOrgName}`) return await this.infra.downAndRemoveVolumes(this.dockerComposePath) } } diff --git a/src/instance/peer.ts b/src/instance/peer.ts index 613ca9cd..0cf3e5a1 100644 --- a/src/instance/peer.ts +++ b/src/instance/peer.ts @@ -15,12 +15,12 @@ export default class Peer extends AbstractInstance { } public async up (): Promise { - logger.info(`[*] Peer instance up: ${this.peerOrgName}`) + logger.debug(`Peer instance up: ${this.peerOrgName}`) return await this.infra.upInBackground(this.dockerComposePath) } public async down (): Promise { - logger.info(`[*] Peer instance down: ${this.peerOrgName}`) + logger.debug(`Peer instance down: ${this.peerOrgName}`) return await this.infra.downAndRemoveVolumes(this.dockerComposePath) } } diff --git a/src/model/type/config.type.ts b/src/model/type/config.type.ts index 6ad6a043..4e24464d 100644 --- a/src/model/type/config.type.ts +++ b/src/model/type/config.type.ts @@ -7,7 +7,7 @@ import { EnvironmentEnum } from '../../config' * @requires BDK_ORG_NAME - [string] org 的名稱 * @requires BDK_ORG_DOMAIN - [string] org 的 domain 名稱 * @requires BDK_HOSTNAME - [string] hostname 的名稱 - * @requires DOCKER_LOGGING - [boolean] 是否要顯示 docker log 資訊 + * @requires LOGGER_SILLY - [boolean] 是否要顯示 silly log 資訊 */ export interface ConfigEnvType { NODE_ENV: EnvironmentEnum @@ -16,7 +16,7 @@ export interface ConfigEnvType { BDK_ORG_NAME: string BDK_ORG_DOMAIN: string BDK_HOSTNAME: string - DOCKER_LOGGING: boolean + LOGGER_SILLY: boolean BDK_DOCKER_HOST_PATH?: string } diff --git a/src/service/caService.ts b/src/service/caService.ts index 25e01253..f959a4f9 100644 --- a/src/service/caService.ts +++ b/src/service/caService.ts @@ -64,7 +64,7 @@ export default class Ca extends AbstractService { public enrollSteps () { return { enrollMsp: async (arg: CaEnrollType): Promise => { - logger.info('[*] enroll step 1 (msp)') + logger.debug('enroll step 1 (msp)') if (arg.type === CaEnrollCommandTypeEnum.orderer) { return await (new FabricCa(this.config, this.infra)).enroll( CaEnrollTypeEnum.msp, @@ -102,7 +102,7 @@ export default class Ca extends AbstractService { } }, enrollTls: async (arg: CaEnrollType): Promise => { - logger.info('[*] enroll step 2 (tls)') + logger.debug('enroll step 2 (tls)') if (arg.type === CaEnrollCommandTypeEnum.orderer) { return await (new FabricCa(this.config, this.infra)).enroll( CaEnrollTypeEnum.tls, @@ -124,7 +124,7 @@ export default class Ca extends AbstractService { } }, format: (arg: CaEnrollType) => { - logger.info('[*] enroll step 3 (format)') + logger.debug('enroll step 3 (format)') if (arg.type === CaEnrollCommandTypeEnum.orderer) { this.bdkFile.caFormatOrderer(arg.upstream, arg.clientId, arg.orgHostname) } else if (arg.type === CaEnrollCommandTypeEnum.peer) { diff --git a/src/service/chaincode.ts b/src/service/chaincode.ts index 03f69aed..a0890b01 100644 --- a/src/service/chaincode.ts +++ b/src/service/chaincode.ts @@ -28,7 +28,7 @@ export default class Chaincode extends AbstractService { * @returns 在 ./chaincode 中 [chaincode 的名稱]_[cahincode 的版本].tar */ public async package (payload: ChaincodePackageType) { - logger.info('[*] Package chaincode') + logger.debug('Package chaincode') this.bdkFile.createChaincodeFolder() await (new FabricTools(this.config, this.infra)).packageChaincode(payload.name, payload.version, path.resolve(payload.path)) } @@ -38,7 +38,7 @@ export default class Chaincode extends AbstractService { * @returns 執行 chaincode function 的回覆 */ public async invoke (payload: ChaincodeInvokeType): Promise { - logger.info('[*] invoke chaincode') + logger.debug('invoke chaincode') return await (new FabricInstance(this.config, this.infra)).invokeChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeFunction, payload.args, payload.isInit, payload.orderer, payload.peerAddresses) } @@ -47,7 +47,7 @@ export default class Chaincode extends AbstractService { * @returns 執行 chaincode function 的回覆 */ public async query (payload: ChaincodeQueryType): Promise { - logger.info('[*] query chaincode') + logger.debug('query chaincode') return await (new FabricInstance(this.config, this.infra)).queryChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeFunction, payload.args) } @@ -70,11 +70,11 @@ export default class Chaincode extends AbstractService { public installSteps () { return { installToPeer: async (dto: ChaincodeInstallType): Promise => { - logger.info('[*] install chaincode step 1 (install chaincode)') + logger.debug('install chaincode step 1 (install chaincode)') return await (new FabricInstance(this.config, this.infra)).installChaincode(dto.chaincodeLabel) }, savePackageId: (dto: ChaincodeInstallType): string => { - logger.info('[*] install chaincode step 2 (save package id)') + logger.debug('install chaincode step 2 (save package id)') this.bdkFile.savePackageId(dto.chaincodeLabel, dto.packageId || '') return dto.packageId || '' }, @@ -87,7 +87,7 @@ export default class Chaincode extends AbstractService { * @returns chaincode 的安裝編號 */ public async getChaincodePackageId (): Promise { - logger.info('[*] query installed and get package id') + logger.debug('query installed and get package id') return await (new FabricInstance(this.config, this.infra)).queryInstalledChaincode() } @@ -95,7 +95,7 @@ export default class Chaincode extends AbstractService { * @description 同意 chaincode */ public async approve (payload: ChaincodeApproveType): Promise { - logger.info('[*] approve for my org') + logger.debug('approve for my org') const packageId = this.bdkFile.getPackageId(`${payload.chaincodeName}_${payload.chaincodeVersion}`) return await (new FabricInstance(this.config, this.infra)).approveChaincode(payload.channelId, payload.chaincodeName, payload.chaincodeVersion, packageId, payload.initRequired, payload.orderer) } @@ -104,7 +104,7 @@ export default class Chaincode extends AbstractService { * @description 發布 chaincode */ public async commit (payload: ChaincodeCommitType): Promise { - logger.info('[*] Commit chaincode definition') + logger.debug('Commit chaincode definition') return await (new FabricInstance(this.config, this.infra)).commitChaincode(payload.channelId, payload.chaincodeName.replace('_', '-'), payload.chaincodeVersion, payload.initRequired, payload.orderer, payload.peerAddresses) } @@ -112,7 +112,7 @@ export default class Chaincode extends AbstractService { * @description 查詢已發布的chaincode */ public async getCommittedChaincode (channelId: string): Promise { - logger.info('[*] Get committed chaincode') + logger.debug('Get committed chaincode') return await (new FabricInstance(this.config, this.infra)).queryCommittedChaincode(channelId) } } diff --git a/src/service/channel.ts b/src/service/channel.ts index 4b6dd70e..de30a5eb 100644 --- a/src/service/channel.ts +++ b/src/service/channel.ts @@ -19,7 +19,7 @@ export default class Channel extends AbstractService { * @description 建立 channel */ public async create (data: ChannelCreateType): Promise { - logger.info('[*] Channel create') + logger.debug('Channel create') await this.createSteps().createChannelArtifact(data) await this.createSteps().createOnInstance(data) } @@ -44,9 +44,9 @@ export default class Channel extends AbstractService { * @description 加入 channel */ public async join (data: ChannelJoinType): Promise { - logger.info('[*] Channel join step 1') + logger.debug('Channel join step 1') await this.joinSteps().fetchChannelBlock(data) - logger.info('[*] Channel join step 2') + logger.debug('Channel join step 2') await this.joinSteps().joinOnInstance(data) } @@ -68,7 +68,7 @@ export default class Channel extends AbstractService { * @description 更新 channel 設定檔上 peer org 的 anchor peer */ public async updateAnchorPeer (data: ChannelUpdateAnchorPeerType): Promise { - logger.info('[*] Channel update anchor peer') + logger.debug('Channel update anchor peer') await this.updateAnchorPeerSteps().fetchChannelBlock(data) await this.updateAnchorPeerSteps().computeUpdateConfigTx(data) await this.updateAnchorPeerSteps().signConfigTx(data) @@ -84,7 +84,7 @@ export default class Channel extends AbstractService { const { channelName } = dto const signType = this.config.orgType - logger.info(`[*] Channel Update Anchor Peer: fetch ${ChannelConfigEnum.CONFIG_BLOCK} block in ${channelName}`) + logger.debug(`Channel Update Anchor Peer: fetch ${ChannelConfigEnum.CONFIG_BLOCK} block in ${channelName}`) this.bdkFile.createChannelArtifact(channelName) return await this.fetchChannelConfig(channelName, signType) @@ -95,7 +95,7 @@ export default class Channel extends AbstractService { const orgType = this.config.orgType const host = `${this.config.hostname}.${this.config.orgDomainName}` - logger.info(`[*] Channel Update Anchor Peer: add ${host} anchor peer config in ${channelName} - compute update`) + logger.debug(`Channel Update Anchor Peer: add ${host} anchor peer config in ${channelName} - compute update`) const configBlock = await this.getConfigBlock(channelName) @@ -128,7 +128,7 @@ export default class Channel extends AbstractService { const signType = this.config.orgType const host = `${this.config.hostname}.${this.config.orgDomainName}` - logger.info(`[*] Channel Update Anchor Peer: add ${host} anchor peer config in ${channelName} - sign `) + logger.debug(`Channel Update Anchor Peer: add ${host} anchor peer config in ${channelName} - sign `) const channelCreateChannelConfigUpdate: ChannelCreateChannelConfigUpdateType = { signType, orderer, @@ -140,7 +140,7 @@ export default class Channel extends AbstractService { updateChannelConfig: async (data: ChannelUpdateAnchorPeerType): Promise => { const { orderer, channelName } = data - logger.info(`[*] Channel Update Anchor Peer: update ${channelName} config`) + logger.debug(`Channel Update Anchor Peer: update ${channelName} config`) const signType = this.config.orgType const channelCreateChannelConfigUpdate: ChannelCreateChannelConfigUpdateType = { signType, @@ -156,7 +156,7 @@ export default class Channel extends AbstractService { * @description */ public async fetchChannelBlock (data: ChannelFetchBlockType): Promise { - logger.info(`[*] Channel fetch block: fetch ${data.configType} block in ${data.channelName}`) + logger.debug(`Channel fetch block: fetch ${data.configType} block in ${data.channelName}`) switch (data.configType) { case ChannelConfigEnum.LATEST_BLOCK: return await this.fetchChannelBlockSteps().fetchChannelNewestBlock(data) @@ -197,7 +197,7 @@ export default class Channel extends AbstractService { /** @ignore */ private generateChannelConfigtxYaml (configtxInput: ChannelCreateType) { - logger.info('[*] Create configtx.yaml') + logger.debug('Create configtx.yaml') const configtx = new ConfigtxYaml() configtx.importOrgs(this.bdkFile.getConfigtxOrgs()) @@ -253,11 +253,11 @@ export default class Channel extends AbstractService { public getChannelGroupSteps () { return { fetchChannelConfig: async (channelName: string): Promise => { - logger.info(`[*] Get Channel Group step 1: ${channelName}`) + logger.debug(`Get Channel Group step 1: ${channelName}`) return await (new FabricInstance(this.config, this.infra)).fetchChannelConfig(channelName, channelName, 'block', undefined, OrgTypeEnum.PEER) }, decodeFetchedChannelConfig: async (channelName: string): Promise<{ anchorPeer: string[]; orderer: string[] }> => { - logger.info(`[*] Get Channel Group step 2: ${channelName}`) + logger.debug(`Get Channel Group step 2: ${channelName}`) await (new FabricTools(this.config, this.infra)).decodeChannelConfig(channelName) const channelConfigJson = this.bdkFile.getDecodedChannelConfig(channelName) const anchorPeer: string[] = [] diff --git a/src/service/config.ts b/src/service/config.ts index 1c42e66e..bc9df1db 100644 --- a/src/service/config.ts +++ b/src/service/config.ts @@ -11,7 +11,7 @@ const defaultEnv: ConfigEnvType = { BDK_ORG_NAME: 'Org1', BDK_ORG_DOMAIN: 'org1.example.com', BDK_HOSTNAME: 'peer0', - DOCKER_LOGGING: false, + LOGGER_SILLY: false, } export default class Config extends AbstractService { @@ -20,7 +20,7 @@ export default class Config extends AbstractService { * @returns .env 檔案(在 ~/.bdk 資料夾底下) */ public init (args: ConfigEnvType = defaultEnv) { - logger.info('[*] Config init') + logger.debug('Config init') const initEnv = Object.assign({}, defaultEnv, args) this.bdkFile.createEnv(initEnv) @@ -30,7 +30,7 @@ export default class Config extends AbstractService { * @description 設定/修改 blockchain network 環境變數設定 */ public set (args: ConfigSetType) { - logger.info(`[*] Config set: set ${args.key} to ${args.value}`) + logger.debug(`Config set: set ${args.key} to ${args.value}`) const envObj = this.bdkFile.getEnv() this.bdkFile.createEnv(Object.assign({}, envObj, { [args.key]: args.value })) @@ -40,7 +40,7 @@ export default class Config extends AbstractService { * @description 在 log 列出 blockchain network 環境變數設定 */ public ls () { - logger.info('[*] Config ls') + logger.debug('Config ls') return this.bdkFile.getEnv() } diff --git a/src/service/explorer.ts b/src/service/explorer.ts index f93ed373..e0fbe8ec 100644 --- a/src/service/explorer.ts +++ b/src/service/explorer.ts @@ -27,7 +27,7 @@ export default class Explorer extends AbstractService { /** @ignore */ private createExplorerConfig (data: ExplorerUpForMyOrgType | ExplorerUpdateForMyOrgType) { - logger.info(`[*] Create file: ${this.config.networkName}.json`) + logger.debug(`Create file: ${this.config.networkName}.json`) const explorerConnectionProfileYaml = new ExplorerConnectionProfileYaml() explorerConnectionProfileYaml.setName(this.config.networkName) explorerConnectionProfileYaml.loadFromPeerConnectionProfile(this.bdkFile.getConnectionFile(this.config.orgName, this.config.orgDomainName)) @@ -50,11 +50,11 @@ export default class Explorer extends AbstractService { explorerConnectionProfileYaml.setClientOrganization(this.config.orgName) this.bdkFile.createExplorerConnectionProfile(this.config.networkName, explorerConnectionProfileYaml) - logger.info(`[*] Blockchain Explorer create network ${this.config.networkName} config`) + logger.debug(`Blockchain Explorer create network ${this.config.networkName} config`) const explorerConfigYaml = new ExplorerConfigYaml() explorerConfigYaml.addNetwork(this.config.networkName) - logger.info('[*] Create file: config.json') + logger.debug('Create file: config.json') this.bdkFile.createExplorerConfig(explorerConfigYaml) } @@ -62,7 +62,7 @@ export default class Explorer extends AbstractService { * @description 關閉 explorer */ public async down (): Promise { - logger.info('[*] Explorer down') + logger.debug('Explorer down') return await (new ExplorerInstance(this.config, this.infra)).down() } @@ -85,15 +85,15 @@ export default class Explorer extends AbstractService { public upForMyOrgSteps () { return { listJoinedChannel: async (): Promise => { - logger.info('[*] up explorer for my org step 1 (fetch joined channel)') + logger.debug('up explorer for my org step 1 (fetch joined channel)') return await (new Channel(this.config)).listJoinedChannel() }, up: async (payload: ExplorerUpForMyOrgType): Promise => { - logger.info('[*] up explorer for my org step 2 (start explorer)') + logger.debug('up explorer for my org step 2 (start explorer)') this.createExplorerConfig(payload) const dockerComposeYaml = new ExplorerDockerComposeYaml(this.config, payload.port) this.bdkFile.createExplorerDockerComposeYaml(dockerComposeYaml) - logger.info('[*] Starting explorer container') + logger.debug('Starting explorer container') return await (new ExplorerInstance(this.config, this.infra)).up() }, } @@ -118,11 +118,11 @@ export default class Explorer extends AbstractService { public updateForMyOrgSteps () { return { listJoinedChannel: async (): Promise => { - logger.info('[*] update explorer for my org step 1 (fetch joined channel)') + logger.debug('update explorer for my org step 1 (fetch joined channel)') return await (new Channel(this.config, this.infra)).listJoinedChannel() }, restart: async (payload: ExplorerUpdateForMyOrgType): Promise => { - logger.info('[*] update explorer for my org step 2 (restart explorer)') + logger.debug('update explorer for my org step 2 (restart explorer)') this.createExplorerConfig(payload.channels || {}) return await (new ExplorerInstance(this.config, this.infra)).restart() }, diff --git a/src/service/hello.ts b/src/service/hello.ts index e9e49b27..d19f2b76 100644 --- a/src/service/hello.ts +++ b/src/service/hello.ts @@ -1,9 +1,9 @@ +import config from '../config' import { logger } from '../util/logger' export const hello = (argv: any) => { - // 呼叫 servicer 並使用 logger - // console.log() - logger.debug(`Hello World! ${argv}`) - logger.info(`Hello World! ${argv}`) - logger.warn(`Hello World! ${argv}`) + logger.debug('[%s] Hello debug! %s', config.environment, argv) + logger.info('[%s] Hello info! %s', config.environment, argv) + logger.warn('[%s] Hello warn! %s', config.environment, argv) + logger.error('[%s] Hello error! %s', config.environment, argv) } diff --git a/src/service/network.ts b/src/service/network.ts index 64f46ecf..a10bcdcb 100644 --- a/src/service/network.ts +++ b/src/service/network.ts @@ -38,7 +38,7 @@ export default class Network extends AbstractService { * @param networkName blockchain network 的名稱 */ public async delete (networkName: string) { - logger.info(`Delete network ${networkName}`) + logger.debug(`Delete network ${networkName}`) const hostNames = this.bdkFile.getDockerComposeList() @@ -66,7 +66,7 @@ export default class Network extends AbstractService { * @returns 憑證和私鑰 */ public async cryptogen (dto: NetworkCreateType) { - logger.info(`[*] Network create cryptogen: ${this.config.networkName}`) + logger.debug(`Network create cryptogen: ${this.config.networkName}`) const cryptoConfigYaml = this.createCryptoConfigYaml(dto) await this.cryptogenGenerate(cryptoConfigYaml) @@ -77,7 +77,7 @@ export default class Network extends AbstractService { * @returns 複製 TLS CA 到 blockchain network 底下的資料夾 tlsca/[peer hostname 的名稱].[domain 的名稱]/ca.crt */ public copyTLSCa (dto: NetworkCreateType) { - logger.info(`[*] Network create copyTLSCa: ${this.config.networkName}`) + logger.debug(`Network create copyTLSCa: ${this.config.networkName}`) dto.ordererOrgs && dto.ordererOrgs.forEach((ordererOrg: NetworkCreateOrdererOrgType) => { for (let i = 0; i < ordererOrg.hostname.length; i++) { @@ -97,7 +97,7 @@ export default class Network extends AbstractService { * @returns 創始區塊檔案(~/.bdk/bdk/channel-artifacts/system-channel/genesis.block) */ public async createGenesisBlock (dto: NetworkCreateType) { - logger.info(`[*] Network create genesis.block: ${this.config.networkName}`) + logger.debug(`Network create genesis.block: ${this.config.networkName}`) this.createGenesisConfigtxYaml(dto) await (new FabricTools(this.config, this.infra)).cryptogenGenerateGenesisBlock(this.profileName) @@ -108,7 +108,7 @@ export default class Network extends AbstractService { * @returns blockchain network 連線設定的 yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/peerOrganizations/[domain 的名稱]/connection-[peer org 的名稱].yaml) */ public createConnectionProfile (dto: NetworkCreateType) { - logger.info(`[*] Network create connection config profile: ${this.config.networkName}`) + logger.debug(`Network create connection config profile: ${this.config.networkName}`) if (dto.peerOrgs === undefined) { throw new ParamsError('Invalid params: Required parameter missing') @@ -122,7 +122,7 @@ export default class Network extends AbstractService { * @returns peer org 和 orderer org 的 docker compose yaml 檔案 */ public createDockerCompose (dto: NetworkCreateType) { - logger.info(`[*] Network create docker-compose-{ordererOrgName/peerOrgName}.yaml: ${this.config.networkName}`) + logger.debug(`Network create docker-compose-{ordererOrgName/peerOrgName}.yaml: ${this.config.networkName}`) dto.ordererOrgs && dto.ordererOrgs.forEach((ordererOrg: NetworkCreateOrdererOrgType) => { (new Orderer(this.config, this.infra)).add({ @@ -146,7 +146,7 @@ export default class Network extends AbstractService { /** @ignore */ private createCryptoConfigYaml (dto: NetworkCreateType): CryptoConfigYaml { - logger.info('[*] Create crypto-config.yaml') + logger.debug('Create crypto-config.yaml') const cryptoConfigYaml = new CryptoConfigYaml() @@ -166,7 +166,7 @@ export default class Network extends AbstractService { /** @ignore */ private async cryptogenGenerate (cryptoConfigYaml: CryptoConfigYaml) { - logger.info('[*] Create configtx.yaml by cryptogen') + logger.debug('Create configtx.yaml by cryptogen') this.bdkFile.createCryptoConfigYaml(cryptoConfigYaml) @@ -175,7 +175,7 @@ export default class Network extends AbstractService { /** @ignore */ private createGenesisConfigtxYaml (dto: NetworkCreateType): ConfigtxYaml { - logger.info('[*] Create genesis.block') + logger.debug('Create genesis.block') if (dto.ordererOrgs === undefined) throw new ParamsError('Invalid params: Required parameter missing') if (dto.peerOrgs === undefined) throw new ParamsError('Invalid params: Required parameter missing') diff --git a/src/service/orderer.ts b/src/service/orderer.ts index aca32770..22556537 100644 --- a/src/service/orderer.ts +++ b/src/service/orderer.ts @@ -18,7 +18,7 @@ export default class Orderer extends AbstractService { * @description 啟動 orderer org 的機器 */ public async up (dto: OrdererUpType): Promise { - logger.info(`[*] Orderer up: ${dto.ordererHostname}`) + logger.debug(`Orderer up: ${dto.ordererHostname}`) return await new OrdererInstance(dto.ordererHostname, this.config, this.infra).up() } @@ -26,7 +26,7 @@ export default class Orderer extends AbstractService { * @description 關閉 orderer org 的機器並且刪除其 volume 資料 */ public async down (dto: OrdererUpType): Promise { - logger.info(`[*] Orderer down: ${dto.ordererHostname}`) + logger.debug(`Orderer down: ${dto.ordererHostname}`) return await new OrdererInstance(dto.ordererHostname, this.config, this.infra).down() } @@ -36,7 +36,7 @@ export default class Orderer extends AbstractService { */ public async cryptogen (dto: OrgOrdererCreateType) { const { ordererOrgs } = dto - logger.info('[*] Orderer create cryptogen') + logger.debug('Orderer create cryptogen') const cryptoConfigYaml = new CryptoConfigYaml() const ordererOrgCryptoConfigYaml = this.createCryptoConfigYaml(ordererOrgs) @@ -59,7 +59,7 @@ export default class Orderer extends AbstractService { const configtxYaml = new ConfigtxYaml() for (const ordererOrg of ordererOrgs) { - logger.info(`[*] Orderer create configtx: ${ordererOrg.name}`) + logger.debug(`Orderer create configtx: ${ordererOrg.name}`) const ports = ordererOrg.ports?.map(port => port.port) @@ -95,7 +95,7 @@ export default class Orderer extends AbstractService { public copyTLSCa (dto: OrgOrdererCreateType) { const { ordererOrgs } = dto ordererOrgs.forEach((ordererOrg: NetworkCreateOrdererOrgType) => { - logger.info(`[*] Orderer create copyTLSCa: ${ordererOrg.name}`) + logger.debug(`Orderer create copyTLSCa: ${ordererOrg.name}`) for (const ordererHostname of ordererOrg.hostname) { this.bdkFile.copyOrdererOrgTLSCa(ordererHostname, ordererOrg.domain) } @@ -107,7 +107,7 @@ export default class Orderer extends AbstractService { * @returns orderer org 的 docker compose yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/docker-compose/[domain 的名稱]/docker-compose-orderer-[orderer 的 hostname].[orderer org 的名稱].yaml) */ public add (dto: OrdererAddType) { // if port[i] is not undefine, use this port and publish a container's port to the host. else use default port. - logger.info('[*] Orderer add') + logger.debug('Orderer add') this.createOrdererOrgDockerComposeYaml(dto.orgName || this.config.orgName, dto.orgDomain || this.config.orgDomainName, dto.ordererHostnames, dto.genesisFileName, dto.ports) } @@ -124,7 +124,7 @@ export default class Orderer extends AbstractService { } ordererOrgs.forEach((ordererOrg) => { - logger.info(`[*] Orderer create docker-compose: ${ordererOrg.name}`) + logger.debug(`Orderer create docker-compose: ${ordererOrg.name}`) this.createOrdererOrgDockerComposeYaml(ordererOrg.name, ordererOrg.domain, ordererOrg.hostname, genesisFileName, ordererOrg.ports) }) } @@ -174,7 +174,7 @@ export default class Orderer extends AbstractService { * @description 將 orderer org 資訊加入到 channel 設定檔中 */ public async addOrgToChannel (dto: OrdererAddOrgToChannelType): Promise { - logger.info(`[*] Org Orderer Add Org: add ${dto.orgName} in ${dto.channelName}`) + logger.debug(`Org Orderer Add Org: add ${dto.orgName} in ${dto.channelName}`) await this.addOrgToChannelSteps().fetchChannelConfig(dto) await this.addOrgToChannelSteps().orgConfigComputeUpdateConfigTx(dto) @@ -186,11 +186,11 @@ export default class Orderer extends AbstractService { public addOrgToChannelSteps () { return { fetchChannelConfig: async (dto: OrdererAddOrgToChannelType): Promise => { - logger.info('[*] add org to channel step1 (fetchChannelConfig)') + logger.debug('add org to channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName, this.config.orgType, dto.orderer) }, orgConfigComputeUpdateConfigTx: async (dto: OrdererAddOrgToChannelType) => { - logger.info('[*] add org to channel step2 (orgConfigComputeUpdateAndSignConfigTx)') + logger.debug('add org to channel step2 (orgConfigComputeUpdateAndSignConfigTx)') const { channelName, orgName } = dto const configBlock = await (new Channel(this.config, this.infra)).getConfigBlock(channelName) @@ -216,7 +216,7 @@ export default class Orderer extends AbstractService { * @description 將 orderer consenter 資訊加入到 channel 設定檔中 */ public async addConsenterToChannel (dto: OrdererAddConsenterToChannelType): Promise { - logger.info(`[*] Org Orderer Add Consenter: add ${dto.hostname} of ${dto.orgName} in ${dto.channelName}`) + logger.debug(`Org Orderer Add Consenter: add ${dto.hostname} of ${dto.orgName} in ${dto.channelName}`) await this.addConsenterToChannelSteps().fetchChannelConfig(dto) await this.addConsenterToChannelSteps().hostnameComputeUpdateConfigTx(dto) @@ -228,11 +228,11 @@ export default class Orderer extends AbstractService { public addConsenterToChannelSteps () { return { fetchChannelConfig: async (dto: OrdererAddConsenterToChannelType): Promise => { - logger.info('[*] add consenter to channel step1 (fetchChannelConfig)') + logger.debug('add consenter to channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName, this.config.orgType, dto.orderer) }, hostnameComputeUpdateConfigTx: async (dto: OrdererAddConsenterToChannelType) => { - logger.info('[*] add consenter to channel step2 (hostnameComputeUpdateAndSignConfigTx)') + logger.debug('add consenter to channel step2 (hostnameComputeUpdateAndSignConfigTx)') const { orderer, channelName } = dto const orgType = this.config.orgType @@ -262,7 +262,7 @@ export default class Orderer extends AbstractService { } public async approve (dto: OrdererApproveType): Promise { - logger.info(`[*] Org Orderer Approve: ${this.config.orgName} sign ${dto.channelName} config update`) + logger.debug(`Org Orderer Approve: ${this.config.orgName} sign ${dto.channelName} config update`) const { channelName } = dto const channelCreateChannelConfigUpdate: ChannelCreateChannelConfigSignType = { @@ -274,7 +274,7 @@ export default class Orderer extends AbstractService { } public async update (dto: OrdererUpdateType): Promise { - logger.info(`[*] Org Orderer update: ${this.config.orgName} update ${dto.channelName}`) + logger.debug(`Org Orderer update: ${this.config.orgName} update ${dto.channelName}`) const { orderer, channelName } = dto const orgType = this.config.orgType diff --git a/src/service/org.ts b/src/service/org.ts index 7e6a5865..81c29c1c 100644 --- a/src/service/org.ts +++ b/src/service/org.ts @@ -10,7 +10,7 @@ export default class Org extends AbstractService { */ public importConfig (data: OrgJsonType[]) { data.forEach(org => { - logger.info(`[*] Import org config: ${org.name}`) + logger.debug(`Import org config: ${org.name}`) this.bdkFile.createOrgDefinitionJson(org.name, org.json) }) @@ -37,7 +37,7 @@ export default class Org extends AbstractService { */ // create new org configtx yaml public async createOrgDefinitionJson (orgName: string, configtxYaml: ConfigtxYaml) { - logger.info(`[*] Generate ${orgName} config json file: configtxgen ${this.config.infraConfig.bdkPath}/${this.config.networkName}/org-json/${orgName}.json`) + logger.debug(`Generate ${orgName} config json file: configtxgen ${this.config.infraConfig.bdkPath}/${this.config.networkName}/org-json/${orgName}.json`) this.bdkFile.createConfigtx(configtxYaml) const orgJson = (await (new FabricTools(this.config, this.infra)).printOrgDefinitionJson(orgName)).stdout.match(/{.*}/s)?.[0] || '' diff --git a/src/service/peer.ts b/src/service/peer.ts index fc7d5134..49b9a0d4 100644 --- a/src/service/peer.ts +++ b/src/service/peer.ts @@ -21,7 +21,7 @@ export default class Peer extends AbstractService { * @description 啟動 peer 的機器 */ public async up (dto: PeerUpType): Promise { - logger.info(`[*] Peer up: ${dto.peerHostname}`) + logger.debug(`Peer up: ${dto.peerHostname}`) return await (new PeerInstance(dto.peerHostname, this.config, this.infra)).up() } @@ -29,7 +29,7 @@ export default class Peer extends AbstractService { * @description 關閉 peer 的機器並且刪除其 volume 的資料 */ public async down (dto: PeerDownType): Promise { - logger.info(`[*] Peer down: ${dto.peerHostname}`) + logger.debug(`Peer down: ${dto.peerHostname}`) return await (new PeerInstance(dto.peerHostname, this.config, this.infra).down()) } @@ -39,7 +39,7 @@ export default class Peer extends AbstractService { */ public async cryptogen (dto: OrgPeerCreateType) { const { peerOrgs } = dto - logger.info('[*] Peer create cryptogen') + logger.debug('Peer create cryptogen') const cryptoConfigYaml = new CryptoConfigYaml() const peerOrgCryptoConfigYaml = this.createCryptoConfigYaml(peerOrgs) @@ -62,7 +62,7 @@ export default class Peer extends AbstractService { const configtxYaml = new ConfigtxYaml() for (const peerOrg of peerOrgs) { - logger.info(`[*] Peer create configtx: ${peerOrg.name}`) + logger.debug(`Peer create configtx: ${peerOrg.name}`) const newOrg = configtxYaml.addPeerOrg({ name: peerOrg.name, @@ -82,7 +82,7 @@ export default class Peer extends AbstractService { public copyTLSCa (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg: NetworkCreatePeerOrgType) => { - logger.info(`[*] Peer create copyTLSCa: ${peerOrg.name}`) + logger.debug(`Peer create copyTLSCa: ${peerOrg.name}`) for (let i = 0; i < peerOrg.peerCount; i++) { this.bdkFile.copyPeerOrgTLSCa(`peer${i}`, peerOrg.domain) } @@ -96,7 +96,7 @@ export default class Peer extends AbstractService { public createConnectionProfileYaml (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg) => { - logger.info(`[*] Peer create connection config: ${peerOrg.name}`) + logger.debug(`Peer create connection config: ${peerOrg.name}`) const connectionProfileYaml = new ConnectionProfileYaml() connectionProfileYaml.setName(`${this.config.networkName}-${peerOrg.name}`) @@ -120,7 +120,7 @@ export default class Peer extends AbstractService { * @returns peer org 的 docker compose yaml 檔案(在 ~/.bdk/[blockchain network 名稱]/docker-compose/[domain 的名稱]/docker-compose-peer-[peer 的 hostname].[peer org 的名稱].yaml) */ public add (dto: PeerAddType) { // if port[i] is not undefine, use this port and publish a container's port to the host. else use default port. - logger.info('[*] Peer add') + logger.debug('Peer add') this.createPeerOrgDockerComposeYaml(dto.orgName || this.config.orgName, dto.orgDomain || this.config.orgDomainName, dto.peerCount, dto.ports) } @@ -132,7 +132,7 @@ export default class Peer extends AbstractService { public createDockerCompose (dto: OrgPeerCreateType) { const { peerOrgs } = dto peerOrgs.forEach((peerOrg) => { - logger.info(`[*] Peer create docker-compose: ${peerOrg.name}`) + logger.debug(`Peer create docker-compose: ${peerOrg.name}`) this.createPeerOrgDockerComposeYaml(peerOrg.name, peerOrg.domain, peerOrg.peerCount, peerOrg.ports) }) } @@ -195,11 +195,11 @@ export default class Peer extends AbstractService { public addOrgToChannelSteps () { return { fetchChannelConfig: async (dto: PeerAddOrgToChannelType): Promise => { - logger.info('[*] add org to channel step1 (fetchChannelConfig)') + logger.debug('add org to channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName, this.config.orgType) }, computeUpdateConfigTx: async (dto: PeerAddOrgToChannelType) => { - logger.info('[*] add org to channel step2 (orgConfigComputeUpdateAndSignConfigTx)') + logger.debug('add org to channel step2 (orgConfigComputeUpdateAndSignConfigTx)') const { channelName, orgName } = dto const configBlock = await (new Channel(this.config, this.infra)).getConfigBlock(channelName) @@ -235,11 +235,11 @@ export default class Peer extends AbstractService { public addOrgToSystemChannelSteps () { return { fetchChannelConfig: async (dto: PeerAddOrgToSystemChannelType): Promise => { - logger.info('[*] add org to system channel step1 (fetchChannelConfig)') + logger.debug('add org to system channel step1 (fetchChannelConfig)') return await (new Channel(this.config, this.infra)).fetchChannelConfig(dto.channelName, this.config.orgType, dto.orderer) }, computeUpdateConfigTx: async (dto: PeerAddOrgToSystemChannelType) => { - logger.info('[*] add org to system channel step2 (orgConfigComputeUpdateAndSignConfigTx)') + logger.debug('add org to system channel step2 (orgConfigComputeUpdateAndSignConfigTx)') const { channelName, orgName } = dto const configBlock = await (new Channel(this.config, this.infra)).getConfigBlock(channelName) @@ -262,7 +262,7 @@ export default class Peer extends AbstractService { } public async approve (dto: PeerApproveType): Promise { - logger.info(`[*] Org Peer Approve: ${this.config.orgName} sign ${dto.channelName} config update`) + logger.debug(`Org Peer Approve: ${this.config.orgName} sign ${dto.channelName} config update`) const { channelName } = dto const channelCreateChannelConfigSignType: ChannelCreateChannelConfigSignType = { @@ -273,7 +273,7 @@ export default class Peer extends AbstractService { } public async update (dto: PeerUpdateType): Promise { - logger.info(`[*] Org Peer update: ${this.config.orgName} update ${dto.channelName}`) + logger.debug(`Org Peer update: ${this.config.orgName} update ${dto.channelName}`) const { orderer, channelName } = dto const channelCreateChannelConfigUpdate: ChannelCreateChannelConfigUpdateType = { diff --git a/src/util/error.ts b/src/util/error.ts index f0d6edb3..8a2d2624 100644 --- a/src/util/error.ts +++ b/src/util/error.ts @@ -25,12 +25,12 @@ export const onCancel = (prompt: prompts.PromptObject, answers: any) => export const errorHandler = (err: Error) => { if (err instanceof FabricContainerError) { logger.error(err.message) - config.isDevMode && console.error(err.stdout) } else if (err instanceof BdkError) { logger.error(err.message) } else { logger.error('Unexpected error.\n') + logger.error(err.message) } - config.isDevMode && console.error(err) + config.isDevMode && logger.error(err.stack) } diff --git a/src/util/logger.ts b/src/util/logger.ts index b4de7635..393cd0fa 100644 --- a/src/util/logger.ts +++ b/src/util/logger.ts @@ -1,27 +1,40 @@ import config from '../config' import { transports, format, createLogger } from 'winston' +import { LEVEL } from 'triple-beam' -// TODO logs to cloudwatch -// TODO logs for user - -const transportsConfig = { +const defaultLoggerConfig = { + level: config.isSillyMode ? 'silly' : 'debug', + silent: config.isTestMode, format: format.combine( - format.colorize(), + format.splat(), format.timestamp(), - format.align(), + format.colorize(), format.printf( - info => `[bdk] ${info.timestamp} - ${info.level}: ${info.message}`, + info => { + if (info[LEVEL as any] === 'info') { + return info.message.trim() + } else { + return `[bdk] ${info.timestamp} - ${info.level}: ${info.message}` + } + }, ), ), + transports: [new transports.Console({ stderrLevels: ['debug', 'warn', 'error'] })], } -const logger = createLogger({ - level: config.isDevMode ? 'debug' : 'info', - silent: config.isTestMode, - transports: [ - // - Write to all logs with specified level to console. - new transports.Console(transportsConfig), - ], -}) +const devLoggerConfig = { + ...defaultLoggerConfig, +} + +const prodLoggerConfig = { + ...defaultLoggerConfig, + level: 'info', +} + +const logger = createLogger( + config.isDevMode + ? devLoggerConfig + : prodLoggerConfig, +) export { logger } diff --git a/test/service/config.test.ts b/test/service/config.test.ts index 78dc7107..9bdd528d 100644 --- a/test/service/config.test.ts +++ b/test/service/config.test.ts @@ -14,7 +14,7 @@ describe('Config service: ', () => { BDK_ORG_NAME: 'TestOrg', BDK_ORG_DOMAIN: 'test.domain.com', BDK_HOSTNAME: 'peer0', - DOCKER_LOGGING: true, + LOGGER_SILLY: true, } const configSetEnv: ConfigSetType = { @@ -37,7 +37,7 @@ describe('Config service: ', () => { it('.env content and inputs should be the same', () => { (new Config(config)).init() - const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=org1.example.com\nBDK_HOSTNAME=peer0\nDOCKER_LOGGING=false\n' + const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=org1.example.com\nBDK_HOSTNAME=peer0\nLOGGER_SILLY=false\n' assert.strictEqual(fs.readFileSync(`${config.infraConfig.bdkPath}/.env`).toString(), checkConfig) }) @@ -57,7 +57,7 @@ describe('Config service: ', () => { it('.env content and inputs should be the same', () => { (new Config(config)).init(configEnv) - const checkConfig = 'NODE_ENV=testing\nBDK_NETWORK_NAME=test-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=TestOrg\nBDK_ORG_DOMAIN=test.domain.com\nBDK_HOSTNAME=peer0\nDOCKER_LOGGING=true\n' + const checkConfig = 'NODE_ENV=testing\nBDK_NETWORK_NAME=test-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=TestOrg\nBDK_ORG_DOMAIN=test.domain.com\nBDK_HOSTNAME=peer0\nLOGGER_SILLY=true\n' assert.strictEqual(fs.readFileSync(`${config.infraConfig.bdkPath}/.env`).toString(), checkConfig) }) @@ -78,7 +78,7 @@ describe('Config service: ', () => { (new Config(config)).init(); (new Config(config)).set(configSetEnv) - const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=test.set.domain.com\nBDK_HOSTNAME=peer0\nDOCKER_LOGGING=false\n' + const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=test.set.domain.com\nBDK_HOSTNAME=peer0\nLOGGER_SILLY=false\n' assert.strictEqual(fs.readFileSync(`${config.infraConfig.bdkPath}/.env`).toString(), checkConfig) }) @@ -98,7 +98,7 @@ describe('Config service: ', () => { (new Config(config)).init(); (new Config(config)).ls() - const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=org1.example.com\nBDK_HOSTNAME=peer0\nDOCKER_LOGGING=false\n' + const checkConfig = 'NODE_ENV=production\nBDK_NETWORK_NAME=bdk-network\nBDK_ORG_TYPE=peer\nBDK_ORG_NAME=Org1\nBDK_ORG_DOMAIN=org1.example.com\nBDK_HOSTNAME=peer0\nLOGGER_SILLY=false\n' assert.strictEqual(fs.readFileSync(`${config.infraConfig.bdkPath}/.env`).toString(), checkConfig) })