Skip to content
This repository was archived by the owner on Mar 8, 2020. It is now read-only.

Commit 2a746b1

Browse files
authored
[0.19.x] Backport perf logging improvements (#4497)
Signed-off-by: Dave Kelsey <d_kelsey@uk.ibm.com>
1 parent b3529c6 commit 2a746b1

File tree

9 files changed

+81
-23
lines changed

9 files changed

+81
-23
lines changed

packages/composer-common/lib/log/logger.js

Lines changed: 9 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -70,7 +70,9 @@ const _logLevelAsString = {
7070

7171
// If composer[debug]:acls is provided, the debug level of trace will be used for specified string.
7272
const PROFILES = {
73-
'acls' : ['composer[#]:AccessController']
73+
'acls' : ['composer[#]:AccessController'],
74+
'hlfv1': ['composer[#]:HLFConnectionManager','composer[#]:HLFConnection',
75+
'composer[#]:HLFQueryHandler', 'composer[#]:HLFTxEventHandler']
7476
};
7577

7678
/**
@@ -304,7 +306,7 @@ class Logger {
304306
*
305307
* @param {String} method calling method
306308
* @param {String} msg Text Message
307-
* @param {TransactionID} txId The node-sdk transaction id
309+
* @param {TransactionID} txId The node-sdk transaction id or null if no txid
308310
* @param {Date} startTime Date object representing the start of the timed block
309311
*
310312
* @private
@@ -314,7 +316,11 @@ class Logger {
314316
return;
315317
}
316318
const timeTaken = (Date.now() - startTime).toFixed(2);
317-
this.intlog('verbose', method, `[${txId.getTransactionID().substring(0, 8)}] ${msg} ${timeTaken}ms`);
319+
if (txId && txId.getTransactionID) {
320+
this.intlog('verbose', method, `[${txId.getTransactionID().substring(0, 8)}] ${msg} ${timeTaken}ms`);
321+
} else {
322+
this.intlog('verbose', method, `[NO TXID ] ${msg} ${timeTaken}ms`);
323+
}
318324
}
319325

320326
/**
@@ -659,9 +665,7 @@ class Logger {
659665
const loggerToUse = localConfig.logger;
660666
let myLogger;
661667
try {
662-
// const mod = 'config';
663668
const req = require;
664-
// const config = req(mod);
665669
myLogger = req(loggerToUse);
666670
} catch (e) {
667671
// Print the error to the console and just use the null logger instead.

packages/composer-common/lib/log/winstonInjector.js

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -62,6 +62,8 @@ exports.getLogger = function (config){
6262
colorize: true,
6363
label: PRODUCT_LABEL,
6464
silent: (consoleLevel===null),
65+
timestamp: timestampFn,
66+
formatter: formatterFn,
6567
level: consoleLevel
6668
};
6769

packages/composer-common/test/log/logger.js

Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -24,6 +24,7 @@ const Identifiable = require('../../lib/model/identifiable');
2424
const Typed = require('../../lib/model/typed');
2525

2626
const chai = require('chai');
27+
2728
chai.use(require('chai-things'));
2829
const mockery = require('mockery');
2930
const sinon = require('sinon');
@@ -287,6 +288,11 @@ describe('Logger', () => {
287288
sinon.assert.calledWith(logger.intlog, 'verbose', 'Method', sinon.match.string);
288289
});
289290

291+
it('perf method should call verbose level and work without a txid, no args', () => {
292+
logger.perf('Method', 'Perf message', null, new Date());
293+
sinon.assert.calledOnce(logger.intlog);
294+
sinon.assert.calledWith(logger.intlog, 'verbose', 'Method', sinon.match.string);
295+
});
290296

291297
it('error method should call error level, no args', () => {
292298
logger.error('Method', 'Message', 'Data');

packages/composer-connector-hlfv1/lib/hlfconnection.js

Lines changed: 24 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -102,6 +102,12 @@ class HLFConnection extends Connection {
102102
// don't log the client, channel, caClient objects here they're too big
103103
LOG.entry(method, connectionManager, connectionProfile, businessNetworkIdentifier, connectOptions);
104104

105+
if (this.businessNetworkIdentifier) {
106+
LOG.info(method, `Creating a connection using profile ${connectionProfile} to network ${businessNetworkIdentifier}`);
107+
} else {
108+
LOG.info(method, `Creating a connection using profile ${connectionProfile} to fabric (no business network)`);
109+
}
110+
105111
// Validate all the arguments.
106112
if (!connectOptions) {
107113
throw new Error('connectOptions not specified');
@@ -139,6 +145,11 @@ class HLFConnection extends Connection {
139145
disconnect() {
140146
const method = 'disconnect';
141147
LOG.entry(method);
148+
if (this.businessNetworkIdentifier) {
149+
LOG.info(method, `Disconnecting the connection to ${this.businessNetworkIdentifier}`);
150+
} else {
151+
LOG.info(method, 'Disconnecting the connection to fabric (no business network)');
152+
}
142153

143154
if (this.exitListener) {
144155
process.removeListener('exit', this.exitListener);
@@ -197,8 +208,10 @@ class HLFConnection extends Connection {
197208
LOG.debug(method, 'Submitting enrollment request');
198209
let options = { enrollmentID: enrollmentID, enrollmentSecret: enrollmentSecret };
199210
let user;
211+
const t0 = Date.now();
200212
return this.caClient.enroll(options)
201213
.then((enrollment) => {
214+
LOG.perf(method, `Total duration to enroll ${enrollmentID}: `, null, t0);
202215
// Store the certificate data in a new user object.
203216
LOG.debug(method, 'Successfully enrolled, creating user object');
204217
user = HLFConnection.createUser(enrollmentID, this.client);
@@ -216,12 +229,13 @@ class HLFConnection extends Connection {
216229
return this._initializeChannel();
217230
})
218231
.then(() => {
219-
LOG.exit(method, user);
232+
// Don't log the user, it's too big
233+
LOG.exit(method);
220234
return user;
221235
})
222236
.catch((error) => {
237+
LOG.error(method, error);
223238
const newError = new Error('Error trying to enroll user or load channel configuration. ' + error);
224-
LOG.error(method, newError);
225239
throw newError;
226240
});
227241
}
@@ -876,8 +890,10 @@ class HLFConnection extends Connection {
876890
let txId = this.client.newTransactionID();
877891

878892
const t0 = Date.now();
893+
LOG.perf(method, `start of querying chaincode ${functionName}(${args})`, txId, t0);
894+
879895
let result = await this.queryHandler.queryChaincode(txId, functionName, args);
880-
LOG.perf(method, 'Total duration for queryChaincode: ', txId, t0);
896+
LOG.perf(method, `Total duration for queryChaincode to ${functionName}: `, txId, t0);
881897
LOG.exit(method, result ? result : null);
882898
return result ? result : null;
883899
}
@@ -934,6 +950,8 @@ class HLFConnection extends Connection {
934950
let validResponses;
935951

936952
let t0 = Date.now();
953+
LOG.perf(method, `start of chaincode invocation ${functionName}(${args})`, txId, t0);
954+
937955
try {
938956

939957
// initialize the channel if it hasn't been initialized already otherwise verification will fail.
@@ -950,7 +968,7 @@ class HLFConnection extends Connection {
950968
fcn: functionName,
951969
args: args
952970
};
953-
LOG.perf(method, 'Total duration to initialize channel: ', txId, t0);
971+
LOG.perf(method, 'Total duration to initialize: ', txId, t0);
954972
t0 = Date.now();
955973

956974
let results;
@@ -960,11 +978,11 @@ class HLFConnection extends Connection {
960978
LOG.error(method, error);
961979
throw new Error(`Error received from sendTransactionProposal: ${error}`);
962980
}
963-
LOG.perf(method, 'Total duration for sendTransactionProposal: ', txId, t0);
981+
LOG.perf(method, `Total duration for sendTransactionProposal ${functionName}: `, txId, t0);
964982
t0 = Date.now();
965983

966984
// Validate the endorsement results.
967-
LOG.debug(method, `Received ${results.length} result(s) from invoking the composer runtime chaincode`, results);
985+
LOG.debug(method, `Received ${results.length} result(s) from invoking the composer runtime chaincode`);
968986
const proposalResponses = results[0];
969987
validResponses = this._validatePeerResponses(proposalResponses, true).validResponses;
970988

packages/composer-connector-hlfv1/lib/hlfconnectionmanager.js

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -259,7 +259,7 @@ class HLFConnectionManager extends ConnectionManager {
259259
*/
260260
static async setupWallet(client, wallet) {
261261
const method = 'setupWallet';
262-
LOG.entry(method, client, wallet);
262+
LOG.entry(method, wallet);
263263
try {
264264
let store = await new HLFWalletProxy(wallet);
265265
client.setStateStore(store);
@@ -285,7 +285,7 @@ class HLFConnectionManager extends ConnectionManager {
285285
*/
286286
static async setupHSM(client, ccp, wallet) {
287287
const method = 'setupHSM';
288-
LOG.entry(method, client, wallet);
288+
LOG.entry(method, wallet);
289289
let keyValStorePath = HLFConnectionManager.getStoreLocation(ccp);
290290
let store;
291291
try {

packages/composer-connector-hlfv1/lib/hlfqueryhandler.js

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -130,7 +130,7 @@ class HLFQueryHandler {
130130
*/
131131
async querySinglePeer(peer, txId, functionName, args) {
132132
const method = 'querySinglePeer';
133-
LOG.entry(method, peer, txId, functionName, args);
133+
LOG.entry(method, peer.getName(), txId, functionName, args);
134134
const request = {
135135
targets: [peer],
136136
chaincodeId: this.connection.businessNetworkIdentifier,
@@ -139,7 +139,9 @@ class HLFQueryHandler {
139139
args: args
140140
};
141141

142+
const t0 = Date.now();
142143
let payloads = await this.connection.channel.queryByChaincode(request);
144+
LOG.perf(method, `Total duration for node-sdk queryByChaincode to ${functionName}: `, txId, t0);
143145
LOG.debug(method, `Received ${payloads.length} payloads(s) from querying the composer runtime chaincode`);
144146
if (!payloads.length) {
145147
LOG.error(method, 'No payloads were returned from the query request:' + functionName);

packages/composer-connector-hlfv1/lib/hlftxeventhandler.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -103,7 +103,7 @@ class HLFTxEventHandler {
103103
LOG.exit(method);
104104
return Promise.all(this.listenerPromises);
105105
}
106-
LOG.warn(method, 'No event hubs available to listen on to wait for transaction commits');
106+
LOG.warn(method, `No event hubs available to listen on to wait for a commit for transaction '${this.txId}'`);
107107
LOG.exit(method);
108108
return Promise.resolve();
109109
}

packages/composer-connector-hlfv1/test/hlfconnection.js

Lines changed: 31 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -57,12 +57,12 @@ describe('HLFConnection', () => {
5757
let mockPeer1, mockPeer2, mockPeer3, mockEventHub1, mockEventHub2, mockEventHub3, mockQueryHandler;
5858
let connectOptions;
5959
let connection;
60-
let mockTransactionID, logWarnSpy, logErrorSpy;
60+
let mockTransactionID, logWarnSpy, logErrorSpy, logInfoSpy, LOG;
6161

6262
beforeEach(() => {
6363
sandbox = sinon.sandbox.create();
6464
clock = sinon.useFakeTimers();
65-
const LOG = Logger.getLog('HLFConnection');
65+
LOG = Logger.getLog('HLFConnection');
6666
logWarnSpy = sandbox.spy(LOG, 'warn');
6767
logErrorSpy = sandbox.spy(LOG, 'error');
6868
mockConnectionManager = sinon.createStubInstance(HLFConnectionManager);
@@ -161,19 +161,32 @@ describe('HLFConnection', () => {
161161
}).should.throw(/channel not specified/);
162162
});
163163

164-
165164
it('should throw if caClient not specified', () => {
166165
(() => {
167166
new HLFConnection(mockConnectionManager, 'hlfabric1', mockBusinessNetwork.getName(), { type: 'hlfv1' }, mockClient, mockChannel, null);
168167
}).should.throw(/caClient not specified/);
169168
});
169+
170+
it('should log at info a fabric level connection being created', () => {
171+
logInfoSpy = sandbox.spy(LOG, 'info');
172+
connection = new HLFConnection(mockConnectionManager, 'hlfabric1', null, {'x-requiredEventHubs': 'fred'}, mockClient, mockChannel, mockCAClient);
173+
sinon.assert.calledWith(logInfoSpy, 'constructor', sinon.match(/no business network/));
174+
});
175+
176+
it('should log at info a business network level connection being created', () => {
177+
logInfoSpy = sandbox.spy(LOG, 'info');
178+
connection = new HLFConnection(mockConnectionManager, 'hlfabric1', 'test-business-network', {'x-requiredEventHubs': 'fred'}, mockClient, mockChannel, mockCAClient);
179+
sinon.assert.calledWith(logInfoSpy, 'constructor', sinon.match(/test-business-network/));
180+
});
181+
170182
});
171183

172184
describe('#_connectToEventHubs', () => {
173185
beforeEach(() => {
174186
mockChannel.getPeers.returns([mockPeer1]);
175187
mockPeer1.isInRole.withArgs(FABRIC_CONSTANTS.NetworkConfig.EVENT_SOURCE_ROLE).returns(true);
176-
mockChannel.newChannelEventHub.withArgs(mockPeer1).returns(mockEventHub1); });
188+
mockChannel.newChannelEventHub.withArgs(mockPeer1).returns(mockEventHub1);
189+
});
177190

178191
it('should ignore a disconnected event hub on process exit', () => {
179192
sandbox.stub(process, 'on').withArgs('exit').yields();
@@ -497,8 +510,6 @@ describe('HLFConnection', () => {
497510
});
498511
});
499512

500-
501-
502513
it('should handle being called twice', () => {
503514
mockEventHub1.isconnected.returns(true);
504515
connection._connectToEventHubs();
@@ -512,6 +523,20 @@ describe('HLFConnection', () => {
512523
});
513524
});
514525

526+
it('should log at info a fabric level connection being disconnected', () => {
527+
logInfoSpy = sandbox.spy(LOG, 'info');
528+
connection = new HLFConnection(mockConnectionManager, 'hlfabric1', null, {'x-requiredEventHubs': 'fred'}, mockClient, mockChannel, mockCAClient);
529+
connection.disconnect();
530+
sinon.assert.calledWith(logInfoSpy.secondCall, 'disconnect', sinon.match(/no business network/));
531+
});
532+
533+
it('should log at info a business network level connection being created', () => {
534+
logInfoSpy = sandbox.spy(LOG, 'info');
535+
connection = new HLFConnection(mockConnectionManager, 'hlfabric1', 'test-business-network', {'x-requiredEventHubs': 'fred'}, mockClient, mockChannel, mockCAClient);
536+
connection.disconnect();
537+
sinon.assert.calledWith(logInfoSpy.secondCall, 'disconnect', sinon.match(/test-business-network/));
538+
});
539+
515540
});
516541

517542
describe('#enroll', () => {

packages/composer-connector-hlfv1/test/hlfqueryhandler.js

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -46,6 +46,7 @@ describe('HLFQueryHandler', () => {
4646
mockPeer3.index = 3;
4747
mockConnection = sinon.createStubInstance(HLFConnection);
4848
mockTransactionID = sinon.createStubInstance(TransactionID);
49+
mockTransactionID.getTransactionID.returns('0987654321');
4950
mockChannel = sinon.createStubInstance(Channel);
5051
mockConnection.channel = mockChannel;
5152
mockConnection.getChannelPeersInOrg.withArgs([FABRIC_CONSTANTS.NetworkConfig.CHAINCODE_QUERY_ROLE]).returns([mockPeer2, mockPeer1, mockPeer3]);
@@ -222,7 +223,7 @@ describe('HLFQueryHandler', () => {
222223
});
223224

224225
it('should throw any responses that are errors and code 1 being unavailable.', () => {
225-
const response = new Error('14 UNAVAILABLE: Connect Failed');
226+
const response = new Error('1 UNAVAILABLE: Connect Failed');
226227
response.code = 1;
227228
mockChannel.queryByChaincode.resolves([response]);
228229
mockConnection.businessNetworkIdentifier = 'org-acme-biznet';
@@ -231,7 +232,7 @@ describe('HLFQueryHandler', () => {
231232
});
232233

233234
it('should throw any responses that are errors and code 4 being unavailable.', () => {
234-
const response = new Error('14 UNAVAILABLE: Connect Failed');
235+
const response = new Error('4 UNAVAILABLE: Connect Failed');
235236
response.code = 4;
236237
mockChannel.queryByChaincode.resolves([response]);
237238
mockConnection.businessNetworkIdentifier = 'org-acme-biznet';

0 commit comments

Comments
 (0)