Skip to content

Commit

Permalink
Merge pull request #525 from makerdao/logger
Browse files Browse the repository at this point in the history
Update logger implementation
  • Loading branch information
rafinskipg authored Jun 24, 2022
2 parents d7c1a7f + 1b49917 commit e7d78c3
Show file tree
Hide file tree
Showing 29 changed files with 110 additions and 58 deletions.
5 changes: 3 additions & 2 deletions .eslintrc
Original file line number Diff line number Diff line change
Expand Up @@ -44,12 +44,13 @@
"react/react-in-jsx-scope": 0,
"testing-library/await-async-query": "error",
"testing-library/no-await-sync-query": "error",
"testing-library/no-debug": "warn",
"testing-library/no-debug": "off",
"testing-library/no-dom-import": "off",
"jest-dom/prefer-checked": "error",
"jest-dom/prefer-enabled-disabled": "error",
"jest-dom/prefer-required": "error",
"jest-dom/prefer-to-have-attribute": "error"
"jest-dom/prefer-to-have-attribute": "error",
"no-debugger":"off"
},
"settings": {
"react": {
Expand Down
17 changes: 9 additions & 8 deletions lib/cache.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import { DEFAULT_NETWORK, SupportedNetworks } from 'modules/web3/constants/netwo
import { config } from 'lib/config';
import Redis from 'ioredis';
import packageJSON from '../package.json';
import logger from './logger';

const redis = config.REDIS_URL
? new Redis(config.REDIS_URL, {
Expand All @@ -23,7 +24,7 @@ function getFilePath(name: string, network: string): string {
}

export const cacheDel = (path: string): void => {
console.log('Delete cache', path);
logger.debug('Delete cache', path);
fs.unlinkSync(path);
memoryCache[path] = null;
};
Expand All @@ -46,18 +47,18 @@ export const cacheGet = async (
if (isRedisCache && redis) {
// Get redis data if it exists
const cachedData = await redis.get(path);
console.log(`Redis cache get for ${path}`);
logger.debug(`Redis cache get for ${path}`);
return cachedData;
} else {
// If fs does not exist as a module, return null (TODO: This shouldn't happen, consider removing this check)
if (Object.keys(fs).length === 0) return null;
const memCached = memoryCache[path];

if (memCached) {
console.log(`mem cache hit: ${path}`);
logger.debug(`mem cache hit: ${path}`);

if (memCached.expiry && memCached.expiry < Date.now()) {
console.log('mem cache expired');
logger.debug('mem cache expired');
cacheDel(path);
return null;
}
Expand All @@ -75,12 +76,12 @@ export const cacheGet = async (
return null;
}

console.log(`fs cache hit: ${path}`);
logger.debug(`fs cache hit: ${path}`);
return fs.readFileSync(path).toString();
}
}
} catch (e) {
console.error(`Error getting cached data, ${name} - ${network}`, e.message);
logger.error(`CacheGet: Error getting cached data, ${name} - ${network}`, e.message);
return null;
}
};
Expand All @@ -103,7 +104,7 @@ export const cacheSet = (
try {
if (isRedisCache && redis) {
// If redis cache is enabled, store in redis, with a TTL in seconds
console.log(`Redis cache set for ${path}`);
logger.debug(`Redis cache set for ${path}`);

redis.set(path, data, 'EX', expiryMs / 1000);
} else {
Expand All @@ -118,6 +119,6 @@ export const cacheSet = (
};
}
} catch (e) {
console.error(`Error storing data in cache, ${name} - ${network}`, e.message);
logger.error(`CacheSet: Error storing data in cache, ${name} - ${network}`, e.message);
}
};
12 changes: 12 additions & 0 deletions lib/logger.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
function logger(level: string, method: string) {
return function (...args) {
console[method](`- ${level.toUpperCase()}: `, ...args);
};
}

export default {
info: logger('info', 'info'),
debug: logger('debug', 'log'),
warn: logger('warn', 'warn'),
error: logger('error', 'error')
};
5 changes: 2 additions & 3 deletions lib/utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { CurrencyObject } from 'modules/app/types/currency';
import { hexZeroPad, stripZeros } from 'ethers/lib/utils';

import round from 'lodash/round';
import logger from './logger';

export function bigNumberKFormat(num: CurrencyObject): string {
invariant(num && num.symbol && num.toBigNumber, 'bigNumberKFormat must recieve a maker currency object');
Expand Down Expand Up @@ -215,9 +216,7 @@ const windowOpen = (
onClose(shareDialog);
}
} catch (e) {
/* eslint-disable no-console */
console.error(e);
/* eslint-enable no-console */
logger.error('windowOpen:', e);
}
}, 1000);
}
Expand Down
3 changes: 2 additions & 1 deletion modules/app/api/withApiHandler.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import type { NextApiHandler, NextApiRequest, NextApiResponse } from 'next';
import { withSentry } from '@sentry/nextjs';
import logger from 'lib/logger';

export default function withApiHandler(handler: NextApiHandler, { allowPost = false } = {}): NextApiHandler {
return withSentry(async (req: NextApiRequest, res: NextApiResponse) => {
Expand All @@ -24,7 +25,7 @@ export default function withApiHandler(handler: NextApiHandler, { allowPost = fa
const result = await handler(req, res);
return result;
} catch (error) {
console.log('server error', error);
logger.error(`API: ${req.method} ${req.url}`, error.message);
return res.status(500).json({
error: {
code: 'unexpected_error',
Expand Down
3 changes: 2 additions & 1 deletion modules/app/components/Icon/index.tsx
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from 'lib/logger';
import React from 'react';

const icons = {
Expand Down Expand Up @@ -144,7 +145,7 @@ export default function Icon({
sx?: any;
}): React.ReactElement | null {
if (!icons[name]) {
console.error(`No icon found with name ${name}`);
logger.error(`Icon: No icon found with name ${name}`);
return null;
}

Expand Down
5 changes: 4 additions & 1 deletion modules/comments/api/getCommentsByAddress.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { markdownToHtml } from 'lib/markdown';
import { networkNameToChainId } from 'modules/web3/helpers/chain';
import { getRPCFromChainID } from 'modules/web3/helpers/getRPC';
import { ethers } from 'ethers';
import logger from 'lib/logger';
export async function getCommentsByAddress(
address: string,
network: SupportedNetworks
Expand Down Expand Up @@ -39,7 +40,9 @@ export async function getCommentsByAddress(
transaction = await provider
.getTransaction(comment.txHash as string)
.catch(e =>
console.error(`There was a problem fetching transaction for comment ID: ${_id}. Error: ${e}`)
logger.error(
`GetCommentsByAddress: ${address}, There was a problem fetching transaction for comment ID: ${_id}. Error: ${e}`
)
);
}

Expand Down
6 changes: 4 additions & 2 deletions modules/comments/api/insertPollingComments.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from 'lib/logger';
import connectToDatabase from 'modules/db/helpers/connectToDatabase';
import invariant from 'tiny-invariant';
import { PollComment } from '../types/comments';
Expand All @@ -22,9 +23,10 @@ export async function insertPollComments(comments: PollComment[]): Promise<PollC
};
})
);
logger.debug(`insertPollComments Inserted ${comments.length} comments.`);
} catch (e) {
console.error(
`A MongoBulkWriteException occurred, but there are ${e.result.result.nInserted} successfully processed documents.`
logger.error(
`insertPollComments: A MongoBulkWriteException occurred, but there are ${e.result.result.nInserted} successfully processed documents.`
);
}

Expand Down
3 changes: 2 additions & 1 deletion modules/delegates/api/fetchDelegatedTo.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { utils } from 'ethers';
import logger from 'lib/logger';
import { gqlRequest } from 'modules/gql/gqlRequest';
import { mkrDelegatedTo } from 'modules/gql/queries/mkrDelegatedTo';
import { SupportedNetworks } from 'modules/web3/constants/networks';
Expand Down Expand Up @@ -42,7 +43,7 @@ export async function fetchDelegatedTo(
utils.parseEther(prev.lockAmount).gt(utils.parseEther(next.lockAmount)) ? -1 : 1
);
} catch (e) {
console.error('Error fetching MKR delegated to address', e.message);
logger.error('fetchDelegatedTo: Error fetching MKR delegated to address', e.message);
return [];
}
}
3 changes: 2 additions & 1 deletion modules/delegates/api/fetchDelegationEventsByAddresses.ts
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import logger from 'lib/logger';
import { gqlRequest } from 'modules/gql/gqlRequest';
import { mkrLockedDelegateArrayTotals } from 'modules/gql/queries/mkrLockedDelegateArray';
import { SupportedNetworks } from 'modules/web3/constants/networks';
Expand All @@ -23,7 +24,7 @@ export async function fetchDelegationEventsByAddresses(

return addressData;
} catch (e) {
console.error('Error fetching delegation events', e.message);
logger.error('fetchDelegationEventsByAddresses: Error fetching delegation events', e.message);
return [];
}
}
13 changes: 10 additions & 3 deletions modules/delegates/api/fetchGithubDelegates.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,7 @@ import { DelegateRepoInformation } from 'modules/delegates/types';
import { getDelegatesRepositoryInformation } from './getDelegatesRepositoryInfo';
import { ethers } from 'ethers';
import { allGithubDelegates } from 'modules/gql/queries/allGithubDelegates';
import logger from 'lib/logger';

// Parses the information on a delegate folder in github and extracts a DelegateRepoInformation parsed object
async function extractGithubInformation(
Expand Down Expand Up @@ -65,7 +66,7 @@ async function extractGithubInformation(
cuMember
};
} catch (e) {
console.error('Error parsing folder from github delegate', e.message);
logger.error('extractGithubInformation: Error parsing folder from github delegate', e.message);
return undefined;
}
}
Expand Down Expand Up @@ -166,7 +167,7 @@ export async function fetchGithubDelegates(
data
};
} catch (e) {
console.error('Error fetching Github delegates ', e.message, 'Network', network);
logger.error('fetchGithubDelegates: Error fetching Github delegates ', e.message, 'Network', network);
return { error: true };
}
}
Expand Down Expand Up @@ -211,7 +212,13 @@ export async function fetchGithubDelegate(
data: userInfo
};
} catch (e) {
console.error('Error fetching Github delegate ', address, e.message, 'Network: ', network);
logger.error(
'fetchGithubDelegate: Error fetching Github delegate ',
address,
e.message,
'Network: ',
network
);
return { error: true };
}
}
3 changes: 2 additions & 1 deletion modules/executive/api/analyzeSpell.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import { getSpellScheduledDate } from 'modules/web3/api/getSpellScheduledDate';
import { SupportedNetworks } from 'modules/web3/constants/networks';
import { SpellData } from '../types';
import { getSpellContract } from 'modules/web3/helpers/getSpellContract';
import logger from 'lib/logger';

export const getExecutiveMKRSupport = async (
address: string,
Expand All @@ -16,7 +17,7 @@ export const getExecutiveMKRSupport = async (
const approvals = await getChiefApprovals(address, network);
return approvals.toString();
} catch (e) {
console.error(`Error fetching approvals for ${address} on ${network}`, e);
logger.error(`getExecutiveMKRSupport: Error fetching approvals for ${address} on ${network}`, e);
return new Promise<string>(res => res('0'));
}
};
Expand Down
3 changes: 2 additions & 1 deletion modules/executive/api/fetchExecutives.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { EXEC_PROPOSAL_INDEX } from '../executive.constants';
import { analyzeSpell, getExecutiveMKRSupport } from './analyzeSpell';
import { ZERO_ADDRESS } from 'modules/web3/constants/addresses';
import { BigNumber } from 'ethers';
import logger from 'lib/logger';

export async function getGithubExecutives(network: SupportedNetworks): Promise<CMSProposal[]> {
const cacheKey = 'github-proposals';
Expand Down Expand Up @@ -36,7 +37,7 @@ export async function getGithubExecutives(network: SupportedNetworks): Promise<C

return parseExecutive(proposalDoc, proposalIndex, proposalLink, network);
} catch (e) {
console.log(e);
logger.error(`getGithubExecutives: network ${network}`, e);
// Catch error and return null if failed fetching one proposal
return null;
}
Expand Down
3 changes: 2 additions & 1 deletion modules/executive/api/fetchSimulationSpellDiff.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
import { fetchJson } from 'lib/fetchJson';
import logger from 'lib/logger';
import {
SIGNATURE_CAST,
SIMULATE_TX_ENDPOINT,
Expand Down Expand Up @@ -48,7 +49,7 @@ export async function fetchSimulationSpellDiffs(

return validated;
} catch (e) {
console.error('Error fetching simulated spell diffs:', e.message);
logger.error('fetchSimulationSpellDiffs: Error fetching simulated spell diffs:', e.message);
return [];
}
}
10 changes: 7 additions & 3 deletions modules/executive/api/parseExecutive.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { CMSProposal } from 'modules/executive/types';
import { ethers } from 'ethers';
import { slugify } from 'lib/utils';
import { SupportedNetworks } from 'modules/web3/constants/networks';
import logger from 'lib/logger';

export function parseExecutive(
proposalDoc: string,
Expand All @@ -16,21 +17,24 @@ export function parseExecutive(
} = matter(proposalDoc);
// Remove empty docs
if (!(content && title && summary && address && date)) {
console.log('executive missing required field, skipping executive: ', title);
logger.warn(
`parseExecutive: ${proposalLink} executive missing required field, skipping executive: `,
title
);
return null;
}

//remove if address is not a valid address
try {
ethers.utils.getAddress(address);
} catch (_) {
console.log('invalid address: ', address, ' skipping executive: ', title);
logger.warn(`parseExecutive: ${proposalLink} invalid address: ${address} skipping executive: ${title}`);
return null;
}

//remove if date is invalid
if (!(date instanceof Date) || isNaN(date.getTime())) {
console.log('invalid date: ', date, ' skipping executive: ', title);
logger.warn(`parseExecutive: ${proposalLink} invalid date: ${date} skipping executive: ${title}`);
return null;
}

Expand Down
4 changes: 2 additions & 2 deletions modules/executive/components/VoteModal/DefaultView.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -26,6 +26,7 @@ import { sign } from 'modules/web3/helpers/sign';
import { ExecutiveCommentsRequestBody } from 'modules/comments/types/comments';
import { ExternalLink } from 'modules/app/components/ExternalLink';
import { getEtherscanLink } from 'modules/web3/helpers/getEtherscanLink';
import logger from 'lib/logger';

export default function DefaultVoteModalView({
proposal,
Expand Down Expand Up @@ -146,10 +147,9 @@ export default function DefaultVoteModalView({
body: JSON.stringify(requestBody)
})
.then(() => {
// console.log('comment successfully added');
mutateComments();
})
.catch(() => console.error('failed to add comment'));
.catch(() => logger.error('POST executive comments: failed to add comment'));
}
onTransactionPending();
},
Expand Down
7 changes: 6 additions & 1 deletion modules/home/api/fetchAllLocksSummed.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
import BigNumber from 'bignumber.js';
import { format } from 'date-fns';
import logger from 'lib/logger';
import { gqlRequest } from 'modules/gql/gqlRequest';
import { allLocksSummed } from 'modules/gql/queries/allLocksSummed';
import { SupportedNetworks } from 'modules/web3/constants/networks';
Expand Down Expand Up @@ -30,7 +31,11 @@ export default async function fetchAllLocksSummed(

return locks;
} catch (e) {
console.error('Error fetching all lock events', e);
logger.error(
'fetchAllLocksSummed: Error fetching all lock events',
`Start: ${unixtimeStart}, End: ${unixtimeEnd}, Network: ${network}`,
e
);
}
return [];
}
3 changes: 2 additions & 1 deletion modules/mkr/components/MKRInput.tsx
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ import { BigNumber } from 'ethers';
import { formatValue } from 'lib/string';
import { BigNumber as BigNumberJs } from 'bignumber.js';
import { parseUnits } from 'ethers/lib/utils';
import logger from 'lib/logger';

export type MKRInputProps = {
placeholder?: string;
Expand Down Expand Up @@ -50,7 +51,7 @@ export function MKRInput({

onChange(parseUnits(newValueStr));
} catch (e) {
console.log(e);
logger.error(`MKRInput, invalid value: ${newValueStr}`, e);
setErrorInvalidFormat(true);
return;
}
Expand Down
Loading

0 comments on commit e7d78c3

Please sign in to comment.