1
0
mirror of https://github.com/oceanprotocol-archive/squid-js.git synced 2024-02-02 15:31:51 +01:00

Replace the main Logger for a instantiable class.

This commit is contained in:
Pedro Gutiérrez 2019-03-19 14:27:28 +01:00 committed by Pedro Gutiérrez
parent 5402d421c8
commit ea16729d86
23 changed files with 105 additions and 106 deletions

View File

@ -1,5 +1,5 @@
import Config from "./models/Config"
import Logger, { LogLevel } from "./utils/Logger"
import LoggerInstance, { LogLevel } from "./utils/Logger"
/**
* Stores the configuration of the library.
@ -17,7 +17,7 @@ export default class ConfigProvider {
* @param {Config} Library config.
*/
public static setConfig(config: Config) {
Logger.setLevel(
LoggerInstance.setLevel(
typeof config.verbose !== "number"
? (config.verbose ? LogLevel.Log : LogLevel.None)
: config.verbose as LogLevel,

View File

@ -2,7 +2,7 @@ import { URL } from "whatwg-url"
import { DDO } from "../ddo/DDO"
import Config from "../models/Config"
import DID from "../ocean/DID"
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
import WebServiceConnectorProvider from "../utils/WebServiceConnectorProvider"
import { SearchQuery } from "./query/SearchQuery"
@ -26,15 +26,15 @@ export default class Aquarius {
if (response.ok) {
return response.text()
}
Logger.error("Failed: ", response.status, response.statusText)
LoggerInstance.error("Failed: ", response.status, response.statusText)
return null
})
.then((consumptionUrl: string): string => {
Logger.error("Success accessing consume endpoint: ", consumptionUrl)
LoggerInstance.error("Success accessing consume endpoint: ", consumptionUrl)
return consumptionUrl
})
.catch((error) => {
Logger.error("Error fetching the data asset consumption url: ", error)
LoggerInstance.error("Error fetching the data asset consumption url: ", error)
return null
})
@ -53,7 +53,7 @@ export default class Aquarius {
if (response.ok) {
return response.json() as DDO[]
}
Logger.error("queryMetadata failed:", response.status, response.statusText)
LoggerInstance.error("queryMetadata failed:", response.status, response.statusText)
return [] as DDO[]
})
.then((ddos) => {
@ -62,7 +62,7 @@ export default class Aquarius {
})
})
.catch((error) => {
Logger.error("Error fetching querying metadata: ", error)
LoggerInstance.error("Error fetching querying metadata: ", error)
return [] as DDO[]
})
@ -86,7 +86,7 @@ export default class Aquarius {
if (response.ok) {
return response.json() as DDO[]
}
Logger.log("queryMetadataByText failed:", response.status, response.statusText)
LoggerInstance.log("queryMetadataByText failed:", response.status, response.statusText)
return [] as DDO[]
})
.then((ddos) => {
@ -95,7 +95,7 @@ export default class Aquarius {
})
})
.catch((error) => {
Logger.error("Error fetching querying metadata by text: ", error)
LoggerInstance.error("Error fetching querying metadata by text: ", error)
return [] as DDO[]
})
@ -115,14 +115,14 @@ export default class Aquarius {
if (response.ok) {
return response.json()
}
Logger.error("storeDDO failed:", response.status, response.statusText, ddo)
LoggerInstance.error("storeDDO failed:", response.status, response.statusText, ddo)
return null as DDO
})
.then((response: DDO) => {
return new DDO(response) as DDO
})
.catch((error) => {
Logger.error("Error fetching querying metadata: ", error)
LoggerInstance.error("Error fetching querying metadata: ", error)
return null as DDO
})
@ -142,14 +142,14 @@ export default class Aquarius {
if (response.ok) {
return response.json()
}
Logger.log("retrieveDDO failed:", response.status, response.statusText, did)
LoggerInstance.log("retrieveDDO failed:", response.status, response.statusText, did)
return null as DDO
})
.then((response: DDO) => {
return new DDO(response) as DDO
})
.catch((error) => {
Logger.error("Error fetching querying metadata: ", error)
LoggerInstance.error("Error fetching querying metadata: ", error)
return null as DDO
})

View File

@ -2,7 +2,7 @@ import save = require("save-file")
import { File } from "../ddo/MetaData"
import Config from "../models/Config"
import Account from "../ocean/Account"
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
import WebServiceConnectorProvider from "../utils/WebServiceConnectorProvider"
const apiPath = "/api/v1/brizo/services"
@ -55,7 +55,7 @@ export default class Brizo {
decodeURI(JSON.stringify(args)),
)
} catch (e) {
Logger.error(e)
LoggerInstance.error(e)
throw new Error("HTTP request failed")
}
}
@ -81,8 +81,8 @@ export default class Brizo {
destination,
)
} catch (e) {
Logger.error("Error consuming assets")
Logger.error(e)
LoggerInstance.error("Error consuming assets")
LoggerInstance.error(e)
throw new Error("Error consuming assets")
}
})

View File

@ -1,5 +1,5 @@
import Web3Provider from "../keeper/Web3Provider"
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
import * as signatureHelpers from "../utils/SignatureHelpers"
import { Authentication } from "./Authentication"
import { Proof } from "./Proof"
@ -130,7 +130,7 @@ export class DDO {
public addChecksum(): void {
const metadataService = this.findServiceByType("Metadata")
if (metadataService.metadata.base.checksum) {
Logger.log("Checksum already exists")
LoggerInstance.log("Checksum already exists")
return
}
metadataService.metadata.base.checksum = this.getChecksum()

View File

@ -1,5 +1,5 @@
import { Contract } from "web3-eth-contract"
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
import Keeper from "./Keeper"
import Web3Provider from "./Web3Provider"
@ -10,7 +10,7 @@ export default class ContractHandler {
try {
return ContractHandler.contracts.get(what) || await ContractHandler.load(what, where)
} catch (err) {
Logger.error("Failed to load", what, "from", where, err)
LoggerInstance.error("Failed to load", what, "from", where, err)
throw err
}
}
@ -27,7 +27,7 @@ export default class ContractHandler {
private static async load(what: string, where: string): Promise<Contract> {
const web3 = Web3Provider.getWeb3()
Logger.debug("Loading", what, "from", where)
LoggerInstance.debug("Loading", what, "from", where)
const artifact = require(`@oceanprotocol/keeper-contracts/artifacts/${what}.${where}.json`)
// Logger.log('Loaded artifact', artifact)
const code = await web3.eth.getCode(artifact.address)
@ -37,7 +37,7 @@ export default class ContractHandler {
}
const contract = new web3.eth.Contract(artifact.abi, artifact.address)
Logger.debug("Getting instance of", what, "from", where, "at address", artifact.address)
LoggerInstance.debug("Getting instance of", what, "from", where, "at address", artifact.address)
ContractHandler.contracts.set(what, contract)
return ContractHandler.contracts.get(what)
}

View File

@ -1,4 +1,4 @@
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
import GenericContract from "./contracts/GenericContract"
import EventListener from "./EventListener"
import Web3Provider from "./Web3Provider"
@ -55,7 +55,7 @@ export default class Event {
callback(events)
}
} catch (err) {
Logger.log(err)
LoggerInstance.log(err)
}
}
}

View File

@ -1,6 +1,6 @@
import { Contract } from "web3-eth-contract"
import { TransactionReceipt } from "web3-core"
import Logger from "../../utils/Logger"
import LoggerInstance from "../../utils/Logger"
import ContractHandler from "../ContractHandler"
import Web3Provider from "../Web3Provider"
@ -75,12 +75,12 @@ export default abstract class ContractBase {
value: args[i],
}
})
Logger.error("-".repeat(40))
Logger.error(`Sending transaction "${name}" on contract "${this.contractName}" failed.`)
Logger.error(`Error: ${err.message}`)
Logger.error(`From: ${from}`)
Logger.error(`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`)
Logger.error("-".repeat(40))
LoggerInstance.error("-".repeat(40))
LoggerInstance.error(`Sending transaction "${name}" on contract "${this.contractName}" failed.`)
LoggerInstance.error(`Error: ${err.message}`)
LoggerInstance.error(`From: ${from}`)
LoggerInstance.error(`Parameters: ${JSON.stringify(mappedArgs, null, 2)}`)
LoggerInstance.error("-".repeat(40))
throw err
}
}
@ -94,7 +94,7 @@ export default abstract class ContractBase {
const method = this.contract.methods[name](...args)
return method.call(from ? {from} : null)
} catch (err) {
Logger.error(`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`, err)
LoggerInstance.error(`Calling method "${name}" on contract "${this.contractName}" failed. Args: ${args}`, err)
throw err
}
}

View File

@ -1,4 +1,4 @@
import Logger from "../../../utils/Logger"
import LoggerInstance from "../../../utils/Logger"
import ContractBase from "../ContractBase"
import { zeroX } from "../../../utils"

View File

@ -1,4 +1,4 @@
import Logger from "../../../utils/Logger"
import LoggerInstance from "../../../utils/Logger"
import ContractBase from "../ContractBase"
import { ConditionState } from "../conditions/Condition.abstract"
import { zeroX } from "../../../utils"

View File

@ -1,4 +1,4 @@
import Logger from "../../../utils/Logger"
import LoggerInstance from "../../../utils/Logger"
import ContractBase from "../ContractBase"
import { zeroX } from "../../../utils"
@ -31,7 +31,7 @@ export class TemplateStoreManager extends ContractBase {
public async proposeTemplate(address: string, from?: string, ignoreExists?: boolean) {
const template = await this.getTemplate(address)
if (template.blockNumberUpdated !== 0) {
Logger.warn(`Template "${address}" already exist.`)
LoggerInstance.warn(`Template "${address}" already exist.`)
if (!ignoreExists) {
throw new Error("Template already exist.")
}
@ -43,7 +43,7 @@ export class TemplateStoreManager extends ContractBase {
public async approveTemplate(address: string, from?: string, ignoreApproved?: boolean) {
const template = await this.getTemplate(address)
if (template.state !== TemplateState.Proposed) {
Logger.warn(`Template "${address}" is not in "proposed" state.`)
LoggerInstance.warn(`Template "${address}" is not in "proposed" state.`)
if (!ignoreApproved) {
throw new Error(`Template not in "proposed" state.`)
}

View File

@ -4,7 +4,7 @@ import { Condition, ConditionState, conditionStateNames } from "../conditions/Co
import Keeper from "../../Keeper"
import { DDO } from "../../../ddo/DDO"
import { ServiceAgreementTemplate } from "../../../ddo/ServiceAgreementTemplate"
import { zeroX, Logger } from "../../../utils"
import { zeroX, LoggerInstance } from "../../../utils"
import EventListener from "../../../keeper/EventListener"
import Event from "../../../keeper/Event"
@ -124,7 +124,7 @@ export abstract class AgreementTemplate extends ContractBase {
const {conditionIds} = await agreementStore.getAgreement(agreementId)
if (!conditionIds.length) {
Logger.error(`Agreement not creeated yet: "${agreementId}"`)
LoggerInstance.error(`Agreement not creeated yet: "${agreementId}"`)
return false
}
@ -167,25 +167,25 @@ export abstract class AgreementTemplate extends ContractBase {
public async printAgreementStatus(agreementId: string) {
const status = await this.getAgreementStatus(agreementId)
Logger.bypass("-".repeat(80))
Logger.bypass("Template:", this.contractName)
Logger.bypass("Agreement ID:", agreementId)
Logger.bypass("-".repeat(40))
LoggerInstance.bypass("-".repeat(80))
LoggerInstance.bypass("Template:", this.contractName)
LoggerInstance.bypass("Agreement ID:", agreementId)
LoggerInstance.bypass("-".repeat(40))
if (!status) {
Logger.bypass("Agreement not created yet!")
LoggerInstance.bypass("Agreement not created yet!")
}
Object.values(status || [])
.forEach(({condition, contractName, state, blocked, blockedBy}, i) => {
if (i) {
Logger.bypass("-".repeat(20))
LoggerInstance.bypass("-".repeat(20))
}
Logger.bypass(`${condition} (${contractName})`)
Logger.bypass(" Status:", state, `(${conditionStateNames[state]})`)
LoggerInstance.bypass(`${condition} (${contractName})`)
LoggerInstance.bypass(" Status:", state, `(${conditionStateNames[state]})`)
if (blocked) {
Logger.bypass(" Blocked by:", blockedBy)
LoggerInstance.bypass(" Blocked by:", blockedBy)
}
})
Logger.bypass("-".repeat(80))
LoggerInstance.bypass("-".repeat(80))
}
/**

View File

@ -3,7 +3,7 @@ import * as EthJsUtils from "ethereumjs-util"
import Keeper from "../keeper/Keeper"
import Web3Provider from "../keeper/Web3Provider"
import Balance from "../models/Balance"
import Logger from "../utils/Logger"
import LoggerInstance from "../utils/Logger"
/**
* Account information.
@ -84,7 +84,7 @@ export default class Account {
.dispenser
.requestTokens(amount, this.id)
} catch (e) {
Logger.error(e)
LoggerInstance.error(e)
throw new Error("Error requesting tokens")
}

View File

@ -16,7 +16,7 @@ import { Service } from "../ddo/Service"
import ContractEvent from "../keeper/Event"
import Config from "../models/Config"
import SecretStoreProvider from "../secretstore/SecretStoreProvider"
import { Logger, LogLevel } from "../utils/Logger"
import { LoggerInstance, LogLevel } from "../utils/Logger"
import Account from "./Account"
import DID from "./DID"
import ServiceAgreement from "./ServiceAgreements/ServiceAgreement"

View File

@ -8,7 +8,7 @@ import { ServiceAgreementTemplateCondition } from "../ddo/ServiceAgreementTempla
import { Service, ServiceAuthorization } from "../ddo/Service"
import Keeper from "../keeper/Keeper"
import SecretStoreProvider from "../secretstore/SecretStoreProvider"
import { Logger, fillConditionsWithDDO } from "../utils"
import { LoggerInstance, fillConditionsWithDDO } from "../utils"
import Account from "./Account"
import DID from "./DID"
import { OceanAgreements } from "./OceanAgreements"
@ -192,13 +192,13 @@ export class OceanAssets {
secretStoreUri: secretStoreUrl,
}
Logger.log("Decrypting files")
LoggerInstance.log("Decrypting files")
const decryptedFiles = await SecretStoreProvider
.getSecretStore(secretStoreConfig)
.decryptDocument(DID.parse(did).getId(), files)
Logger.log("Files decrypted")
LoggerInstance.log("Files decrypted")
Logger.log("Consuming files")
LoggerInstance.log("Consuming files")
resultPath = resultPath ? `${resultPath}/datafile.${ddo.shortId()}.${agreementId}/` : undefined
await brizo.consumeService(
@ -208,7 +208,7 @@ export class OceanAssets {
decryptedFiles,
resultPath,
)
Logger.log("Files consumed")
LoggerInstance.log("Files consumed")
if (resultPath) {
return resultPath
@ -232,9 +232,9 @@ export class OceanAssets {
const oceanAgreements = await OceanAgreements.getInstance()
Logger.log("Asking for agreement signature")
LoggerInstance.log("Asking for agreement signature")
const {agreementId, signature} = await oceanAgreements.prepare(did, serviceDefinitionId, consumer)
Logger.log(`Agreement ${agreementId} signed`)
LoggerInstance.log(`Agreement ${agreementId} signed`)
const ddo = await this.resolve(did)
@ -247,20 +247,20 @@ export class OceanAssets {
template
.getAgreementCreatedEvent(agreementId)
.listenOnce(async (...args) => {
Logger.log("Agreement initialized")
LoggerInstance.log("Agreement initialized")
const {metadata} = ddo.findServiceByType("Metadata")
Logger.log("Locking payment")
LoggerInstance.log("Locking payment")
const paid = await oceanAgreements.conditions.lockReward(agreementId, metadata.base.price, consumer)
if (paid) {
Logger.log("Payment was OK")
LoggerInstance.log("Payment was OK")
} else {
Logger.error("Payment was KO")
Logger.error("Agreement ID: ", agreementId)
Logger.error("DID: ", ddo.id)
LoggerInstance.error("Payment was KO")
LoggerInstance.error("Agreement ID: ", agreementId)
LoggerInstance.error("DID: ", ddo.id)
reject("Error on payment")
}
})
@ -268,12 +268,12 @@ export class OceanAssets {
accessCondition
.getConditionFulfilledEvent(agreementId)
.listenOnce(async (...args) => {
Logger.log("Access granted")
LoggerInstance.log("Access granted")
resolve()
})
})
Logger.log("Sending agreement request")
LoggerInstance.log("Sending agreement request")
await oceanAgreements.send(did, agreementId, serviceDefinitionId, signature, consumer)
await paymentFlow

View File

@ -3,7 +3,7 @@ import { DDO } from "../../ddo/DDO"
import { ServiceAccess } from "../../ddo/Service"
import Web3Provider from "../../keeper/Web3Provider"
import ValuePair from "../../models/ValuePair"
import Logger from "../../utils/Logger"
import LoggerInstance from "../../utils/Logger"
import Account from "../Account"
import { signText, zeroX } from "../../utils"
@ -35,7 +35,7 @@ export default class ServiceAgreement {
consumer,
)
Logger.log("SA hash signature:", serviceAgreementHashSignature)
LoggerInstance.log("SA hash signature:", serviceAgreementHashSignature)
return serviceAgreementHashSignature
}

View File

@ -2,7 +2,7 @@ import Config from "./models/Config"
import Account from "./ocean/Account"
import DID from "./ocean/DID"
import { Ocean } from "./ocean/Ocean"
import Logger from "./utils/Logger"
import LoggerInstance from "./utils/Logger"
import WebServiceConnectorProvider from "./utils/WebServiceConnectorProvider"
import Keeper from "./keeper/Keeper"
import EventListener from "./keeper/EventListener"
@ -26,7 +26,7 @@ export {
DID,
EventListener,
Keeper,
Logger,
LoggerInstance,
WebServiceConnectorProvider,
conditions,

View File

@ -1,4 +1,4 @@
import { Logger } from "./Logger"
import { LoggerInstance } from "./Logger"
// Ox transformer
export const zeroX = (input: string) => zeroXTransformer(input, true)
@ -22,13 +22,13 @@ export const didZeroX = (input: string) => zeroX(didTransformer(input, false))
// Shared functions
function inputMatch(input: string, regexp: RegExp, conversorName: string): {valid: boolean, output: string} {
if (typeof input !== "string") {
Logger.debug("Not input string:")
Logger.debug(input)
LoggerInstance.debug("Not input string:")
LoggerInstance.debug(input)
throw new Error(`[${conversorName}] Expected string, input type: ${typeof input}`)
}
const match = input.match(regexp)
if (!match) {
Logger.warn(`[${conversorName}] Input transformation failed.`)
LoggerInstance.warn(`[${conversorName}] Input transformation failed.`)
return {valid: false, output: input}
}
return {valid: true, output: match[1]}

View File

@ -8,36 +8,39 @@ export enum LogLevel {
export class Logger {
public static setLevel(level: LogLevel) {
this.logLevel = level
constructor(private logLevel: LogLevel = LogLevel.Verbose) { }
public setLevel(logLevel: LogLevel) {
this.warn("Logger.setLevel is deprecated")
this.logLevel = logLevel
}
public static bypass(...args: any[]) {
Logger.dispatch("log", -Infinity as any, ...args)
public bypass(...args: any[]) {
this.dispatch("log", -Infinity as any, ...args)
}
public static debug(...args: any[]) {
Logger.dispatch("debug", LogLevel.Verbose, ...args)
public debug(...args: any[]) {
this.dispatch("debug", LogLevel.Verbose, ...args)
}
public static log(...args: any[]) {
Logger.dispatch("log", LogLevel.Log, ...args)
public log(...args: any[]) {
this.dispatch("log", LogLevel.Log, ...args)
}
public static warn(...args: any[]) {
Logger.dispatch("warn", LogLevel.Warn, ...args)
public warn(...args: any[]) {
this.dispatch("warn", LogLevel.Warn, ...args)
}
public static error(...args: any[]) {
Logger.dispatch("error", LogLevel.Error, ...args)
public error(...args: any[]) {
this.dispatch("error", LogLevel.Error, ...args)
}
private static logLevel: LogLevel = LogLevel.Verbose
private static dispatch(verb: string, level: LogLevel, ...args: any[]) {
private dispatch(verb: string, level: LogLevel, ...args: any[]) {
if (this.logLevel >= level) {
console[verb](...args)
}
}
}
export default Logger
export const LoggerInstance = new Logger()
export default LoggerInstance

View File

@ -1,5 +1,5 @@
import Web3Provider from "../keeper/Web3Provider"
import Logger from "./Logger"
import LoggerInstance from "./Logger"
export async function signText(text: string, publicKey: string, password?: string): Promise<string> {
const web3 = Web3Provider.getWeb3()
@ -7,13 +7,13 @@ export async function signText(text: string, publicKey: string, password?: strin
try {
return await web3.eth.personal.sign(text, publicKey, password)
} catch (e) {
Logger.error("Error on personal sign.")
Logger.error(e)
LoggerInstance.error("Error on personal sign.")
LoggerInstance.error(e)
try {
return await web3.eth.sign(text, publicKey, password)
} catch (e2) {
Logger.error("Error on sign.")
Logger.error(e2)
LoggerInstance.error("Error on sign.")
LoggerInstance.error(e2)
throw new Error("Error executing personal sign")
}
}

View File

@ -1,5 +1,5 @@
import fetch, { BodyInit, RequestInit, Response } from "node-fetch"
import Logger from "./Logger"
import LoggerInstance from "./Logger"
/**
* Provides a common interface to web services.
@ -38,8 +38,8 @@ export default class WebServiceConnector {
private async fetch(url: string, opts: RequestInit): Promise<Response> {
const result = await fetch(url, opts)
if (!result.ok) {
Logger.error(`Error requesting [${opts.method}] ${url}`)
Logger.error(`Response message: \n${await result.text()}`)
LoggerInstance.error(`Error requesting [${opts.method}] ${url}`)
LoggerInstance.error(`Response message: \n${await result.text()}`)
throw result
}
return result

View File

@ -1,4 +1,4 @@
export { Logger, LogLevel } from "./Logger"
export * from "./Logger"
export * from "./SignatureHelpers"
export * from "./ConversionTypeHelpers"
export * from "./GeneratorHelpers"

View File

@ -8,10 +8,5 @@ describe("Squid", () => {
it("should expose Ocean", async () => {
assert(squid.Ocean)
})
it("should expose Logger", async () => {
assert(squid.Logger)
})
})
})

View File

@ -9,6 +9,7 @@
],
"declaration": true,
"module": "commonjs",
"target": "es5",
"noImplicitAny": false,
"removeComments": true,
"experimentalDecorators": true,