Skip to content

Commit

Permalink
Merge pull request #481 from balancer/add-logger
Browse files Browse the repository at this point in the history
Add logger to suppress production logs
  • Loading branch information
johngrantuk authored Jul 6, 2023
2 parents 7e86898 + 184b22d commit 913c1d1
Show file tree
Hide file tree
Showing 23 changed files with 104 additions and 102 deletions.
4 changes: 3 additions & 1 deletion balancer-js/src/lib/utils/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Address, PoolType } from '@/types';
import { getAddress } from '@ethersproject/address';
import { Log, TransactionReceipt } from '@ethersproject/providers';
import { Interface, LogDescription } from '@ethersproject/abi';
import { Logger } from '@/lib/utils/logger';

export * from './aaveHelpers';
export * from './assetHelpers';
Expand Down Expand Up @@ -134,7 +135,8 @@ export const findEventInReceiptLogs = ({
try {
return contractInterface.parseLog(log);
} catch (error) {
console.warn(error);
const logger = Logger.getInstance();
logger.warn(error as string);
return null;
}
})
Expand Down
38 changes: 38 additions & 0 deletions balancer-js/src/lib/utils/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
export class Logger {
private enableLogging: boolean;

private static instance: Logger;

private constructor() {
this.enableLogging = true; // Logging is initially enabled
}

static getInstance(): Logger {
if (!Logger.instance) {
Logger.instance = new Logger();
}
return Logger.instance;
}

setLoggingEnabled(enabled: boolean): void {
this.enableLogging = enabled;
}

info(message: string): void {
if (this.enableLogging) {
console.log(`[INFO] ${message}`);
}
}

warn(message: string): void {
if (this.enableLogging) {
console.warn(`[WARN] ${message}`);
}
}

error(message: string): void {
if (this.enableLogging) {
console.error(`[ERROR] ${message}`);
}
}
}
12 changes: 7 additions & 5 deletions balancer-js/src/modules/data/pool/fallback.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import {
PoolsFallbackRepositoryOptions,
PoolsRepositoryFetchOptions,
} from './types';
import { Logger } from '@/lib/utils/logger';

/**
* The fallback provider takes multiple PoolRepository's in an array and uses them in order
Expand Down Expand Up @@ -73,17 +74,18 @@ export class PoolsFallbackRepository implements Findable<Pool, PoolAttribute> {
} catch (e: unknown) {
const message = (e as Error).message;
if (message === 'timeout') {
console.warn(
const logger = Logger.getInstance();
logger.warn(
'Provider ' +
this.currentProviderIdx +
' timed out, falling back to next provider'
);
} else {
console.warn(
'Provider ' + this.currentProviderIdx + ' failed with error: ',
message,
', falling back to next provider'
const logger = Logger.getInstance();
logger.warn(
`Provider ${this.currentProviderIdx} failed with error, falling back to next provider.`
);
logger.warn(message);
}
this.currentProviderIdx++;
result = await this.fallbackQuery.call(this, func, args);
Expand Down
4 changes: 3 additions & 1 deletion balancer-js/src/modules/data/token-prices/provider.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { Findable, Price } from '@/types';
import { IAaveRates } from './aave-rates';
import { Logger } from '@/lib/utils/logger';

export class TokenPriceProvider implements Findable<Price> {
constructor(
Expand All @@ -16,7 +17,8 @@ export class TokenPriceProvider implements Findable<Price> {
throw new Error('Price not found');
}
} catch (err) {
console.warn(err);
const logger = Logger.getInstance();
logger.warn(err as string);
price = await this.subgraphRepository.find(address);
}
const rate = (await this.aaveRates.getRate(address)) || 1;
Expand Down
4 changes: 3 additions & 1 deletion balancer-js/src/modules/data/token-yields/repository.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import axios from 'axios';
import { Findable } from '@/types';
import { Logger } from '@/lib/utils/logger';

export class TokenYieldsRepository implements Findable<number> {
private yields?: Promise<{ [address: string]: number }>;
Expand All @@ -18,7 +19,8 @@ export class TokenYieldsRepository implements Findable<number> {
[key: string]: number;
};
} catch (error) {
console.warn('Failed to fetch yield tokens:', error);
const logger = Logger.getInstance();
logger.warn(`Failed to fetch yield tokens: ${error}`);
}

return aprs;
Expand Down
4 changes: 3 additions & 1 deletion balancer-js/src/modules/exits/exits.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ import { StablePoolEncoder } from '@/pool-stable';
import { getPoolAddress } from '@/pool-utils';
import { WeightedPoolEncoder } from '@/pool-weighted';
import { BalancerNetworkConfig, ExitPoolRequest, PoolType } from '@/types';
import { Logger } from '@/lib/utils/logger';

const balancerRelayerInterface = BalancerRelayer__factory.createInterface();

Expand All @@ -53,7 +54,8 @@ export interface ExitInfo {
const DEBUG = false;

function debugLog(log: string) {
if (DEBUG) console.log(log);
const logger = Logger.getInstance();
if (DEBUG) logger.info(log);
}

export class Exit {
Expand Down
4 changes: 3 additions & 1 deletion balancer-js/src/modules/joins/joins.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -31,14 +31,16 @@ import { SwapRequest } from '../vaultModel/poolModel/swap';
import { JoinPoolRequest as JoinPoolModelRequest } from '../vaultModel/poolModel/join';
import { JsonRpcSigner } from '@ethersproject/providers';
import { BalancerRelayer__factory } from '@/contracts/factories/BalancerRelayer__factory';
import { Logger } from '@/lib/utils/logger';

const balancerRelayerInterface = BalancerRelayer__factory.createInterface();

// Quickly switch useful debug logs on/off
const DEBUG = false;

function debugLog(log: string) {
if (DEBUG) console.log(log);
const logger = Logger.getInstance();
if (DEBUG) logger.info(log);
}

export class Join {
Expand Down
7 changes: 5 additions & 2 deletions balancer-js/src/modules/pools/apr/apr.ts
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ import { identity, zipObject, pickBy } from 'lodash';
import { PoolFees } from '../fees/fees';
import { BALANCER_NETWORK_CONFIG } from '@/lib/constants/config';
import { BigNumber } from '@ethersproject/bignumber';
import { Logger } from '@/lib/utils/logger';

export interface AprBreakdown {
swapFees: number;
Expand Down Expand Up @@ -194,7 +195,8 @@ export class PoolApr {
const weight = await getWeight(token);
return Math.round(aprs[idx] * weight);
} catch (e) {
console.log(e);
const logger = Logger.getInstance();
logger.error(e as string);
return 0;
}
})
Expand Down Expand Up @@ -458,7 +460,8 @@ export class PoolApr {
const liquidity = await liquidityService.getLiquidity(pool);
return liquidity;
} catch (err) {
console.warn('Liquidity calculcation failed, falling back to subgraph');
const logger = Logger.getInstance();
logger.warn('Liquidity calculcation failed, falling back to subgraph');
return pool.totalLiquidity;
}
}
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,7 @@
*/
import { BalancerError, BalancerErrorCode } from '@/balancerErrors';
import { Findable, Pool, PoolToken, Price } from '@/types';
import { Logger } from '@/lib/utils/logger';

type Asset = {
priceDelta: number;
Expand Down Expand Up @@ -213,13 +214,15 @@ export class ImpermanentLossService {
const price = await this.tokenHistoricalPrices
.findBy(address, timestamp)
.catch((reason) => {
console.warn(
const logger = Logger.getInstance();
logger.warn(
`[ImpermanentLossService][getEntryPrices]Error: ${reason.message}`
);
return undefined;
});
if (!price?.usd) {
console.warn(
const logger = Logger.getInstance();
logger.warn(
`[ImpermanentLossService][getEntryPrices]Error: ${BalancerError.getMessage(
BalancerErrorCode.MISSING_PRICE_RATE
)}`
Expand Down
4 changes: 3 additions & 1 deletion balancer-js/src/modules/pools/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,7 @@ import type {
AprBreakdown,
PoolAttribute,
} from '@/types';
import { Logger } from '@/lib/utils/logger';

import {
ExitExactBPTInAttributes,
Expand Down Expand Up @@ -211,7 +212,8 @@ export class Pools implements Findable<PoolWithMethods> {
};
} catch (error) {
if ((error as BalancerError).code != 'UNSUPPORTED_POOL_TYPE') {
console.warn(error);
const logger = Logger.getInstance();
logger.warn(error as string);
}

methods = {
Expand Down
Original file line number Diff line number Diff line change
@@ -1,41 +1,15 @@
import {
ExitConcern,
ExitExactBPTInAttributes,
ExitExactBPTInParameters,
ExitExactTokensOutAttributes,
ExitExactTokensOutParameters,
} from '@/modules/pools/pool-types/concerns/types';

export class FXExitConcern implements ExitConcern {
buildExitExactTokensOut({
exiter,
pool,
tokensOut,
amountsOut,
slippage,
wrappedNativeAsset,
}: ExitExactTokensOutParameters): ExitExactTokensOutAttributes {
console.log(
exiter,
pool,
tokensOut,
amountsOut,
slippage,
wrappedNativeAsset
);
throw new Error('Not implemented');
buildExitExactTokensOut(): ExitExactTokensOutAttributes {
throw new Error('FXExitConcern Not implemented');
}

buildRecoveryExit({
exiter,
pool,
bptIn,
slippage,
}: Pick<
ExitExactBPTInParameters,
'exiter' | 'pool' | 'bptIn' | 'slippage'
>): ExitExactBPTInAttributes {
console.log(exiter, pool, bptIn, slippage);
throw new Error('Not implemented');
buildRecoveryExit(): ExitExactBPTInAttributes {
throw new Error('FXExitConcern Not implemented');
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,10 @@
import {
JoinConcern,
JoinPoolAttributes,
JoinPoolParameters,
} from '@/modules/pools/pool-types/concerns/types';

export class FXJoinConcern implements JoinConcern {
buildJoin({
joiner,
pool,
tokensIn,
amountsIn,
slippage,
wrappedNativeAsset,
}: JoinPoolParameters): JoinPoolAttributes {
console.log(
joiner,
pool,
tokensIn,
amountsIn,
slippage,
wrappedNativeAsset
);
throw new Error('Not implemented');
buildJoin(): JoinPoolAttributes {
throw new Error('FXJoinConcern Not implemented');
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { SpotPriceConcern } from '@/modules/pools/pool-types/concerns/types';
import { Pool } from '@/types';

export class FXSpotPriceConcern implements SpotPriceConcern {
calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {
console.log(tokenIn, tokenOut, pool);
throw new Error('Not implemented');
calcPoolSpotPrice(): string {
throw new Error('FXSpotPriceConcern Not implemented');
}
}
Original file line number Diff line number Diff line change
@@ -1,26 +1,10 @@
import {
JoinConcern,
JoinPoolAttributes,
JoinPoolParameters,
} from '@/modules/pools/pool-types/concerns/types';

export class GyroJoinConcern implements JoinConcern {
buildJoin({
joiner,
pool,
tokensIn,
amountsIn,
slippage,
wrappedNativeAsset,
}: JoinPoolParameters): JoinPoolAttributes {
console.log(
joiner,
pool,
tokensIn,
amountsIn,
slippage,
wrappedNativeAsset
);
throw new Error('Not implemented');
buildJoin(): JoinPoolAttributes {
throw new Error('GyroJoinConcern Not implemented');
}
}
Original file line number Diff line number Diff line change
@@ -1,9 +1,7 @@
import { SpotPriceConcern } from '@/modules/pools/pool-types/concerns/types';
import { Pool } from '@/types';

export class GyroSpotPriceConcern implements SpotPriceConcern {
calcPoolSpotPrice(tokenIn: string, tokenOut: string, pool: Pool): string {
console.log(tokenIn, tokenOut, pool);
throw new Error('Not implemented');
calcPoolSpotPrice(): string {
throw new Error('GyroSpotPriceConcern Not implemented');
}
}
3 changes: 3 additions & 0 deletions balancer-js/src/modules/sdk.module.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ import { Data } from './data';
import { VaultModel } from './vaultModel/vaultModel.module';
import { JsonRpcProvider } from '@ethersproject/providers';
import { Migrations } from './liquidity-managment/migrations';
import { Logger } from '@/lib/utils/logger';

export interface BalancerSDKRoot {
config: BalancerSdkConfig;
Expand Down Expand Up @@ -44,6 +45,8 @@ export class BalancerSDK implements BalancerSDKRoot {
public sor = new Sor(config),
public subgraph = new Subgraph(config)
) {
const logger = Logger.getInstance();
logger.setLoggingEnabled(!!config.enableLogging);
this.networkConfig = getNetworkConfig(config);
this.provider = sor.provider as JsonRpcProvider;

Expand Down
Loading

0 comments on commit 913c1d1

Please sign in to comment.