Skip to content

Commit

Permalink
PharmaLedger-IMI/epi-workspace#918 using custom logger for apihub logs
Browse files Browse the repository at this point in the history
  • Loading branch information
skutner committed Sep 21, 2022
1 parent 3738246 commit fa95e5b
Show file tree
Hide file tree
Showing 42 changed files with 229 additions and 212 deletions.
8 changes: 5 additions & 3 deletions components/admin/demo.pla.js
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
require("../../../../psknode/bundles/openDSU");
openDSURequire('overwrite-require');
const logger = $$.getLogger("demo.pla.js", "apihub/admin");

const opendsu = openDSURequire("opendsu");
const http = opendsu.loadApi("http");

Expand Down Expand Up @@ -55,7 +57,7 @@ async function storeVariable(dns, prop, value) {
"variableName": prop,
"variableContent": value
}));
console.log(`Finished storing variable ${prop}=${value} for ${dns}`);
logger.info(`Finished storing variable ${prop}=${value} for ${dns}`);
} catch (e) {
console.trace(e);
process.exit(1);
Expand All @@ -69,7 +71,7 @@ async function createDomain(domainName, cloneFrom) {
"domainName": domainName,
"cloneFromDomain": cloneFrom
}));
console.log(`Finished createDomain ${domainName} based on ${cloneFrom}`);
logger.info(`Finished createDomain ${domainName} based on ${cloneFrom}`);
} catch (e) {
console.trace(e);
process.exit(1);
Expand All @@ -83,7 +85,7 @@ async function registerTemplate(path, content) {
path,
content
}));
console.log(`Finished registering template for path ${path}`);
logger.info(`Finished registering template for path ${path}`);
} catch (e) {
console.trace(e);
process.exit(1);
Expand Down
8 changes: 4 additions & 4 deletions components/anchoring/controllers/index.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
const {ALIAS_SYNC_ERR_CODE} = require("../utils");
const utils = require("../utils");
const anchoringStrategies = require("../strategies");

const logger = $$.getLogger("controllers", "apihub/anchoring");
const getStrategy = async (request) => {
let receivedDomain;
let domainConfig;
Expand Down Expand Up @@ -49,7 +49,7 @@ function getWritingHandler(response) {
} else if (err.code === 403) {
return response.send(403, errorMessage);
}
console.log(err);
logger.error(err);
return response.send(500, errorMessage);
}

Expand All @@ -62,7 +62,7 @@ async function updateAnchor(action, request, response) {
try {
strategy = await getStrategy(request);
} catch (e) {
console.log(e);
logger.error(e);
return response.send(500, e);
}
strategy[action](getWritingHandler(response));
Expand Down Expand Up @@ -92,7 +92,7 @@ async function readDataForAnchor(action, request, response) {
try {
strategy = await getStrategy(request);
} catch (e) {
console.log(e);
logger.error(e);
return response.send(500, e);
}
strategy[action](getReadingHandler(response));
Expand Down
4 changes: 2 additions & 2 deletions components/anchoring/strategies/ethx/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@ const {ALIAS_SYNC_ERR_CODE} = require("../../utils");
function Ethx(server, domainConfig, anchorId, newAnchorValue, jsonData) {
const openDSU = require("opendsu");
const http = openDSU.loadAPI("http");

const logger = $$.getLogger("Eth", "apihub/anchoring");
const createEndpoint = (action) => {
let endpoint = domainConfig.option.endpoint;

Expand Down Expand Up @@ -46,7 +46,7 @@ function Ethx(server, domainConfig, anchorId, newAnchorValue, jsonData) {
error.code = ALIAS_SYNC_ERR_CODE;
return callback(error);
}
console.log(err);
logger.error(err);
callback(err);
return;
}
Expand Down
6 changes: 3 additions & 3 deletions components/anchoring/strategies/fsx/filePersistence.js
Original file line number Diff line number Diff line change
Expand Up @@ -116,7 +116,7 @@ function FileOperations() {
const path = require('path');
let anchoringFolder;
const endOfLine = require("os").EOL;

const logger = $$.getLogger("FileOperations", "apihub/anchoring");
self.InitializeFolderStructure = function (rootFolder, configuredPath) {
let storageFolder = path.join(rootFolder, configuredPath);
anchoringFolder = path.resolve(storageFolder);
Expand All @@ -125,7 +125,7 @@ function FileOperations() {
fs.mkdirSync(anchoringFolder, {recursive: true});
}
} catch (e) {
console.log("error creating anchoring folder", e);
logger.error("error creating anchoring folder", e);
throw new Error(`Failed to create folder ${anchoringFolder}`);
}
}
Expand All @@ -137,7 +137,7 @@ function FileOperations() {

let forbiddenCharacters = new RegExp(/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g);
if (forbiddenCharacters.test(anchorId)) {
console.log(`Found forbidden characters in anchorId ${anchorId}`);
logger.error(`Found forbidden characters in anchorId ${anchorId}`);
return callback(new Error(`anchorId ${anchorId} contains forbidden characters`));
}
return callback(undefined);
Expand Down
27 changes: 13 additions & 14 deletions components/anchoring/strategies/oba/index.js
Original file line number Diff line number Diff line change
@@ -1,27 +1,26 @@
const {getEthereumSyncServiceSingleton} = require("./ethereumSyncService");
const LOG_IDENTIFIER = "[OBA]";

function OBA(server, domainConfig, anchorId, anchorValue, ...args) {
let {FS, ETH} = require("../index");
const fsHandler = new FS(server, domainConfig, anchorId, anchorValue, ...args);
const ethHandler = new ETH(server, domainConfig, anchorId, anchorValue, ...args);
const ethSyncService = getEthereumSyncServiceSingleton(server);
const logger = $$.getLogger("OBA", "apihub/anchoring");

this.createAnchor = function (callback) {
console.log("Create anchor", anchorId, anchorValue);
fsHandler.createAnchor((err, res) => {
if (err) {
return callback(err);
}
console.log(`${LOG_IDENTIFIER} optimistic create anchor ended with success.`);
logger.info(`optimistic create anchor ended with success.`);

ethSyncService.storeAnchor("createAnchor", anchorId, anchorValue, domainConfig,(err) => {
if (err) {
console.log(`${LOG_IDENTIFIER} failed to store anchor ${fsHandler.commandData.anchorId} in db.`);
logger.error(`Failed to store anchor ${fsHandler.commandData.anchorId} in db.`);
return;
}

console.log(`${LOG_IDENTIFIER} anchor ${fsHandler.commandData.anchorId} stored in db successfully.`);
logger.info(`Anchor ${fsHandler.commandData.anchorId} stored in db successfully.`);
return callback(undefined, res);
})
});
Expand All @@ -32,25 +31,25 @@ function OBA(server, domainConfig, anchorId, anchorValue, ...args) {
if (err) {
return callback(err);
}
console.log(`${LOG_IDENTIFIER} optimistic append anchor ended with success.`);
logger.info(`Optimistic append anchor ended with success.`);
ethSyncService.storeAnchor("appendAnchor", anchorId, anchorValue, domainConfig, (err) => {
if (err) {
console.log(`${LOG_IDENTIFIER} failed to store anchor ${fsHandler.commandData.anchorId} in db.`);
logger.error(`failed to store anchor ${fsHandler.commandData.anchorId} in db.`);
return;
}

console.log(`${LOG_IDENTIFIER} anchor ${fsHandler.commandData.anchorId} stored in db successfully.`);
logger.info(`Anchor ${fsHandler.commandData.anchorId} stored in db successfully.`);
return callback(undefined, res);

})
});
}

function readAllVersionsFromBlockchain(callback) {
console.log(`${LOG_IDENTIFIER} preparing to read info about anchorId ${fsHandler.commandData.anchorId} from the blockchain...`);
logger.info(`Preparing to read info about anchorId ${fsHandler.commandData.anchorId} from the blockchain...`);
ethHandler.getAllVersions((err, anchorVersions) => {
if (err) {
console.log(`${LOG_IDENTIFIER} anchorId ${fsHandler.commandData.anchorId} syncing blockchain failed. ${err}`);
logger.error(`AnchorId ${fsHandler.commandData.anchorId} syncing blockchain failed. ${err}`);
return callback(err);
}

Expand All @@ -63,20 +62,20 @@ function OBA(server, domainConfig, anchorId, anchorValue, ...args) {
}

if (history === "") {
console.log(`${LOG_IDENTIFIER} anchorId ${fsHandler.commandData.anchorId} synced but no history found.`);
logger.info(`AnchorId ${fsHandler.commandData.anchorId} synced but no history found.`);
//if we don't retrieve info from blockchain we exit
return callback(undefined, anchorVersions);
}

console.log(`${LOG_IDENTIFIER} found info about anchorId ${fsHandler.commandData.anchorId} in blockchain.`);
logger.info(`Found info about anchorId ${fsHandler.commandData.anchorId} in blockchain.`);

//storing locally the history of the anchorId read from the blockchain
fsHandler.fps.createAnchor(anchorId, history, (err) => {
if (err) {
console.log(`${LOG_IDENTIFIER} failed to store info about anchorId ${fsHandler.commandData.anchorId} on local because of ${err}`);
logger.error(`Failed to store info about anchorId ${fsHandler.commandData.anchorId} on local because of ${err}`);
return callback(err);
}
console.log(`${LOG_IDENTIFIER} anchorId ${fsHandler.commandData.anchorId} fully synced.`);
logger.info(`AnchorId ${fsHandler.commandData.anchorId} fully synced.`);
//even if we read all the versions of anchorId we return only the last one
return callback(undefined, anchorVersions);
});
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -26,7 +26,6 @@ assert.callback("Acquire and release lock", (callback) => {
await $$.promisify(newFsLock.acquireLock)();
callback();
} catch (e) {
console.log(e);
assert.true(typeof e === "undefined");
}
})
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,6 @@ assert.callback("Acquire lock after previous expired", (callback) => {
assert.true(typeof err === "undefined");
setTimeout(()=>{
newFsLock.acquireLock((err)=>{
console.log(err);
assert.true(typeof err === "undefined");
callback();
})
Expand Down
14 changes: 9 additions & 5 deletions components/bdns/index.js
Original file line number Diff line number Diff line change
@@ -1,4 +1,6 @@
function BDNS(server) {
const logger = $$.getLogger("BDNS", "apihub/bdns");

const DOMAIN_TEMPLATE = {
"replicas": [],
"brickStorages": [
Expand Down Expand Up @@ -45,12 +47,12 @@ function BDNS(server) {
Object.assign(newRegistry, bdnsExtensions);
bdnsCache = JSON.stringify(newRegistry);
} catch (e) {
console.log(`Failed to get bdns hosts from url`, e);
logger.error(`Failed to get bdns hosts from url`, e);
}
}

try {
console.log("Testing to see if admin component is active and can be used to expand BDNS configuration.");
logger.info("Testing to see if admin component is active and can be used to expand BDNS configuration.");
let adminService = require("./../admin").getAdminService();
let getDomains = $$.promisify(adminService.getDomains);
let domains = await getDomains();
Expand All @@ -66,9 +68,9 @@ function BDNS(server) {
Object.assign(newRegistry, bdnsExtensions);
bdnsCache = JSON.stringify(newRegistry);
}
console.log("BDNS configuration was updated accordingly to information retrieved from admin service");
logger.info("BDNS configuration was updated accordingly to information retrieved from admin service");
} catch (err) {
console.info("Admin service not available, skipping the process of loading dynamic configured domains. This is not a problem, it's a configuration.");
logger.info("Admin service not available, skipping the process of loading dynamic configured domains. This is not a problem, it's a configuration.");
}
}

Expand All @@ -77,6 +79,7 @@ function BDNS(server) {
await initialize();
} catch (e) {
response.statusCode = 500;
logger.error('Failed to initialize BDNS', e);
return response.end('Failed to initialize BDNS');
}

Expand All @@ -85,8 +88,9 @@ function BDNS(server) {
response.statusCode = 200;
response.end(bdnsCache);
} else {
console.log("Bdns config not available at this moment. A 404 response will be sent.");
logger.info("Bdns config not available at this moment. A 404 response will be sent.");
response.statusCode = 404;
logger.error('BDNS hosts not found');
return response.end('BDNS hosts not found');
}
}
Expand Down
5 changes: 2 additions & 3 deletions components/bricking/utils.js
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
const { clone } = require("../../utils");
const { getLocalBdnsEntryListExcludingSelfAsync, getHeadersWithExcludedProvidersIncludingSelf } = require("../../utils/request-utils");
const config = require("../../config");

const logger = $$.getLogger("bricking", "apihub/bricking")
function convertReadableStreamToBuffer(readStream, callback) {
let buffers = [];

Expand All @@ -13,7 +12,7 @@ function convertReadableStreamToBuffer(readStream, callback) {
}

async function getBricksDomainConfig(domain) {
console.log("Looking for domain", domain);
logger.info("Looking for domain", domain);
const config = require("../../config");
let domainConfiguration = await config.getSafeDomainConfig(domain);

Expand Down
1 change: 0 additions & 1 deletion components/bricksFabric/controllers.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,6 @@ function createHandler(flow, server) {

return function storeTransaction (request, response, next) {

console.log('store anchored called');
//strategy is already booted up
flow.storeData(request.body, server, (err, result) => {
if (err) {
Expand Down
3 changes: 2 additions & 1 deletion components/bricksFabric/index.js
Original file line number Diff line number Diff line change
Expand Up @@ -10,12 +10,13 @@ function AutoSavePendingTransactions (flow, timeout, server) {


function BricksFabric(server) {
const logger = $$.getLogger("BricksFabric", "apihub/bricksFabric");

require('./strategies/BrickStorage.js');

const bricksFabricStrategy = require('./utils').getBricksFabricStrategy();
if (!bricksFabricStrategy) {
console.log("Unable to initialized 'bricksFabrick' component. Strategy not found!");
logger.error("Unable to initialized 'bricksFabrick' component. Strategy not found!");
return;
}
const rootFolder = require('./utils').getRootFolder();
Expand Down
17 changes: 8 additions & 9 deletions components/bricksFabric/strategies/BrickStorage.js
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,8 @@ const BRICKSFABRIC_ERROR_CODE = 'bricks fabric error';


function BrickStorage() {
const logger = $$.getLogger("BrickStorage", "apihub/bricksFabric");

this.init = function (brickFabricRootFolder,noOfTransactionsPerBlock) {
this.rootFolder = brickFabricRootFolder;
this.transactionsPerBlock = noOfTransactionsPerBlock;
Expand Down Expand Up @@ -70,7 +72,7 @@ function BrickStorage() {
try {
server.makeLocalRequest(blockMethod, blockPath, data, blockHeaders, (err, result) => {
if (err) {
console.log(err);
logger.error(err);
__pushBuffer();
this.isCommitingBlock = false;
callback(err, undefined);
Expand All @@ -82,8 +84,6 @@ function BrickStorage() {
this.pendingTransactions.splice(0, this.pendingTransactions.length);
__pushBuffer();
this.isCommitingBlock = false;
//console.log(result);
console.log('block finished');

callback(undefined, result);
}
Expand All @@ -92,13 +92,12 @@ function BrickStorage() {
});
} catch (err)
{
console.log("bricks fabric", err);
logger.error("bricks fabric", err);
}
}
function __pushBuffer(){
if (this.pendingBuffer.length > 0)
{
console.log("push buffer to pending block", this.pendingBuffer);
for (let i = 0; i < this.pendingBuffer.length; i++) {
this.pendingTransactions.push(this.pendingBuffer[i]);
}
Expand All @@ -108,19 +107,19 @@ function BrickStorage() {
this.storeData = function(anchorData, server, callback) {
if (this.isCommitingBlock === true)
{
console.log("transaction cached");
logger.info("transaction cached");
this.pendingBuffer.push(anchorData);
callback(undefined,"Transaction was added to the block.");
return;
}
console.log("transaction pushed to pending block");
logger.info("transaction pushed to pending block");
this.pendingTransactions.push(anchorData);
if (this.pendingTransactions.length >= this.transactionsPerBlock)
{
// console.log("commit block callback");
// logger.info("commit block callback");
this.completeBlock(server, callback);
}else {
//console.log("pending callback");
//logger.info("pending callback");
callback(undefined,"Transaction was added to the block.");
}
}
Expand Down
Loading

0 comments on commit fa95e5b

Please # to comment.