Skip to content

Commit

Permalink
feat(bif-common): adds new pkg with logger
Browse files Browse the repository at this point in the history
It is a universal package by design meaning that it works in the
browser and also in NodeJS which allows both the API server
and the cockpit to use the logger from the common package.

Signed-off-by: Peter Somogyvari <peter.somogyvari@accenture.com>
  • Loading branch information
petermetz committed May 19, 2020
1 parent b4b0f83 commit 210df1d
Show file tree
Hide file tree
Showing 17 changed files with 225 additions and 2 deletions.
1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@
"private": true,
"scripts": {
"configure": "lerna clean --yes && lerna bootstrap && npm run build && node ./tools/generate-api-server-config.js",
"start": "node ./packages/bif-cmd-api-server/dist/lib/main/typescript/cmd/bif-api.js --config-file=.config.json",
"tsc": "lerna exec --stream --ignore '*/*cockpit' -- tsc --project ./tsconfig.json",
"clean": "lerna exec --stream --ignore '*/*cockpit' -- del-cli dist/**",
"build": "npm-run-all --parallel build:frontend build:backend",
Expand Down
1 change: 1 addition & 0 deletions packages/bif-cmd-api-server/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@
"homepage": "https://github.com/hyperledger-labs/blockchain-integration-framework#readme",
"dependencies": {
"@hyperledger-labs/bif-cockpit": "0.2.0",
"@hyperledger-labs/bif-common": "0.2.0",
"@hyperledger-labs/bif-core-api": "0.2.0",
"@hyperledger-labs/bif-plugin-keychain-memory": "0.2.0",
"@hyperledger-labs/bif-plugin-kv-storage-memory": "0.2.0",
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -8,20 +8,24 @@ import { IPluginKVStorage, PluginFactory } from '@hyperledger-labs/bif-core-api'
import { CreateConsortiumEndpointV1 } from './consortium/routes/create-consortium-endpoint-v1';
import { IBifApiServerOptions, ConfigService } from './config/config-service';
import { BIF_OPEN_API_JSON } from './openapi-spec';
import { Logger, LoggerProvider } from '@hyperledger-labs/bif-common';

export interface IApiServerConstructorOptions {
config: Config<IBifApiServerOptions>;
}

export class ApiServer {

private readonly log: Logger;

constructor(public readonly options: IApiServerConstructorOptions) {
if (!options) {
throw new Error(`ApiServer#ctor options was falsy`);
}
if (!options.config) {
throw new Error(`ApiServer#ctor options.config was falsy`);
}
this.log = LoggerProvider.getOrCreate({ label: 'api-server', level: options.config.get('logLevel') });
}

async start(): Promise<void> {
Expand All @@ -34,7 +38,10 @@ export class ApiServer {
const app: Express = express();

const cockpitWwwRoot = this.options.config.get('cockpitWwwRoot');
app.use(express.static(cockpitWwwRoot));
this.log.info(`cockpitWwwRoot: ${cockpitWwwRoot}`);
const resolvedWwwRoot = path.resolve(process.cwd(), cockpitWwwRoot);
this.log.info(`resolvedWwwRoot: ${resolvedWwwRoot}`);
app.use(express.static(resolvedWwwRoot));

const cockpitPort: number = this.options.config.get('cockpitPort');
const cockpitHost: string = this.options.config.get('cockpitHost');
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,10 +2,12 @@ import { randomBytes } from 'crypto';
import convict, { Schema, Config, SchemaObj } from 'convict';
import secp256k1 from 'secp256k1';
import { v4 as uuidV4 } from 'uuid';
import { LoggerProvider, Logger } from '@hyperledger-labs/bif-common';

export interface IBifApiServerOptions {
configFile: string;
bifNodeId: string;
logLevel: string;
cockpitHost: string;
cockpitPort: number;
cockpitWwwRoot: string;
Expand Down Expand Up @@ -64,6 +66,14 @@ export class ConfigService {
env: 'BIF_NODE_ID',
arg: 'bif-node-id',
},
logLevel: {
doc: 'The level at which loggers should be configured. Supported values include the following: ' +
'error, warn, info, debug, trace',
format: ConfigService.formatNonBlankString,
default: 'warn',
env: 'LOG_LEVEL',
arg: 'log-level',
},
cockpitHost: {
doc: 'The host to bind the Cockpit webserver to. Secure default is: 127.0.0.1. Use 0.0.0.0 to bind for any host.',
format: 'ipaddress',
Expand All @@ -83,7 +93,7 @@ export class ConfigService {
format: '*',
env: 'COCKPIT_WWW_ROOT',
arg: 'cockpit-www-root',
default: 'node_modules/@hyperledger-labs/bif-cockpit/www/',
default: 'packages/bif-cmd-api-server/node_modules/@hyperledger-labs/bif-cockpit/www/',
},
apiHost: {
doc: 'The host to bind the API to. Secure default is: 127.0.0.1. Use 0.0.0.0 to bind for any host.',
Expand Down Expand Up @@ -200,6 +210,7 @@ export class ConfigService {
return {
configFile: '.config.json',
bifNodeId: uuidV4(),
logLevel: 'debug',
publicKey,
privateKey,
apiCorsDomainCsv: (schema.apiCorsDomainCsv as SchemaObj).default,
Expand Down Expand Up @@ -227,6 +238,9 @@ export class ConfigService {
}
ConfigService.config.validate();
this.validateKeyPairMatch();
const level = ConfigService.config.get('logLevel');
const logger: Logger = LoggerProvider.getOrCreate({ label: 'config-service', level });
logger.info('Configuration validation OK.');
}
return ConfigService.config;
}
Expand Down
1 change: 1 addition & 0 deletions packages/bif-cockpit/package.json
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,7 @@
"@angular/platform-browser-dynamic": "8.2.14",
"@angular/router": "8.2.14",
"@capacitor/core": "1.5.1",
"@hyperledger-labs/bif-common": "0.2.0",
"@ionic-native/core": "5.0.0",
"@ionic-native/splash-screen": "5.0.0",
"@ionic-native/status-bar": "5.0.0",
Expand Down
7 changes: 7 additions & 0 deletions packages/bif-cockpit/src/app/app.component.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ import { Platform } from '@ionic/angular';
import { SplashScreen } from '@ionic-native/splash-screen/ngx';
import { StatusBar } from '@ionic-native/status-bar/ngx';

import { LoggerProvider, Logger } from '@hyperledger-labs/bif-common';

@Component({
selector: 'app-root',
templateUrl: 'app.component.html',
Expand Down Expand Up @@ -45,18 +47,23 @@ export class AppComponent implements OnInit {
];
public labels = ['Family', 'Friends', 'Notes', 'Work', 'Travel', 'Reminders'];

private readonly logger: Logger;

constructor(
private platform: Platform,
private splashScreen: SplashScreen,
private statusBar: StatusBar
) {
this.logger = LoggerProvider.getOrCreate({ label: 'app-component', level: 'debug' });
this.logger.info('Initializing app...');
this.initializeApp();
}

initializeApp() {
this.platform.ready().then(() => {
this.statusBar.styleDefault();
this.splashScreen.hide();
this.logger.info('App initialized OK. Splashscreen was hidden.');
});
}

Expand Down
9 changes: 9 additions & 0 deletions packages/bif-common/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
# `@hyperledger-labs/bif-common`

> TODO: description
## Usage

```
// TODO: DEMONSTRATE API
```
18 changes: 18 additions & 0 deletions packages/bif-common/package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

52 changes: 52 additions & 0 deletions packages/bif-common/package.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
{
"name": "@hyperledger-labs/bif-common",
"version": "0.2.0",
"description": "Universal library used by both front end and back end components of BIF. Aims to be a developer swiss army knife.",
"main": "dist/bif-common.node.umd.js",
"mainMinified": "dist/bif-common.node.umd.min.js",
"browser": "dist/bif-common.web.umd.js",
"browserMinified": "dist/bif-common.web.umd.min.js",
"module": "dist/lib/main/typescript/index.js",
"types": "dist/types/main/typescript/index.d.ts",
"files": [
"dist/*"
],
"publishConfig": {
"access": "public"
},
"engines": {
"node": ">=10",
"npm": ">=6"
},
"repository": {
"type": "git",
"url": "git+https://github.com/hyperledger-labs/blockchain-integration-framework.git"
},
"keywords": [
"Hyperledger",
"Blockchain",
"Interoperability",
"Integration"
],
"author": {
"name": "Peter Somogyvari",
"email": "peter.somogyvari@accenture.com",
"url": "https://accenture.com"
},
"contributors": [
{
"name": "Please add yourself to the list of contributors",
"email": "your.name@example.com",
"url": "https://example.com"
}
],
"license": "Apache-2.0",
"bugs": {
"url": "https://github.com/hyperledger-labs/blockchain-integration-framework/issues"
},
"homepage": "https://github.com/hyperledger-labs/blockchain-integration-framework#readme",
"dependencies": {
"loglevel": "1.6.7",
"loglevel-plugin-prefix": "0.8.4"
}
}
1 change: 1 addition & 0 deletions packages/bif-common/src/main/typescript/index.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
export * from './public-api';
15 changes: 15 additions & 0 deletions packages/bif-common/src/main/typescript/logging/logger-provider.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
import { Logger, ILoggerOptions } from './logger';

export class LoggerProvider {

private static loggers: Map<string, Logger> = new Map();

public static getOrCreate(loggerOptions: ILoggerOptions) {
let logger: Logger | undefined = LoggerProvider.loggers.get(loggerOptions.label);
if (!logger) {
logger = new Logger(loggerOptions);
LoggerProvider.loggers.set(loggerOptions.label, logger);
}
return logger;
}
}
63 changes: 63 additions & 0 deletions packages/bif-common/src/main/typescript/logging/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,63 @@
import libLogLevel, { Logger as LogLevelLogger, levels } from 'loglevel';
import prefix from 'loglevel-plugin-prefix';

prefix.reg(libLogLevel);

prefix.apply(libLogLevel, {
template: '[%t] %l (%n):',
levelFormatter(level) {
return level.toUpperCase();
},
nameFormatter(name) {
return name || 'global';
},
timestampFormatter(date) {
return date.toISOString();
},
});

export interface ILoggerOptions {
label: string;
level?: string;
}

/**
* Levels:
* - error: 0,
* - warn: 1,
* - info: 2,
* - debug: 3,
* - trace: 4
*/
export class Logger {

private readonly backend: LogLevelLogger;

constructor(public readonly options: ILoggerOptions) {
const level: string = options.level || 'warn';
this.backend = libLogLevel.getLogger(options.label);
this.backend.setLevel(level.toUpperCase() as any);
}

public async shutdown(gracePeriodMillis: number = 60000): Promise<void> {
this.backend.info('Shut down logger OK.');
}

public error(...msg: any[]): void {
this.backend.error(...msg);
}

public warn(...msg: any[]): void {
this.backend.warn(...msg);
}
public info(...msg: any[]): void {
this.backend.info(...msg);
}
public debug(...msg: any[]): void {
this.backend.debug(...msg);
}
public trace(...msg: any[]): void {
this.backend.trace(...msg);
}

}
2 changes: 2 additions & 0 deletions packages/bif-common/src/main/typescript/public-api.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
export { LoggerProvider } from './logging/logger-provider';
export { Logger, ILoggerOptions } from './logging/logger';
11 changes: 11 additions & 0 deletions packages/bif-common/src/test/typescript/integration/api-surface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// tslint:disable-next-line: no-var-requires
const tap = require('tap');
import { Logger, LoggerProvider } from '../../../main/typescript/public-api';

tap.pass('Test file can be executed');

tap.test('Library can be loaded', (assert: any) => {
assert.plan(2);
assert.ok(Logger);
assert.ok(LoggerProvider);
});
Empty file.
11 changes: 11 additions & 0 deletions packages/bif-common/src/test/typescript/unit/api-surface.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
// tslint:disable-next-line: no-var-requires
const tap = require('tap');
import { Logger, LoggerProvider } from '../../../main/typescript/public-api';

tap.pass('Test file can be executed');

tap.test('Library can be loaded', (assert: any) => {
assert.plan(2);
assert.ok(Logger);
assert.ok(LoggerProvider);
});
10 changes: 10 additions & 0 deletions packages/bif-common/tsconfig.json
Original file line number Diff line number Diff line change
@@ -0,0 +1,10 @@
{
"extends": "../../tsconfig.json",
"compilerOptions": {
"outDir": "./dist/lib/", /* Redirect output structure to the directory. */
"declarationDir": "dist/types",
},
"include": [
"./src"
]
}

0 comments on commit 210df1d

Please sign in to comment.