Skip to content

Commit

Permalink
feat: centralize log level selection
Browse files Browse the repository at this point in the history
  • Loading branch information
greatertomi committed Jan 29, 2025
1 parent 87b1005 commit ced48b3
Show file tree
Hide file tree
Showing 10 changed files with 69 additions and 17 deletions.
2 changes: 2 additions & 0 deletions apps/browser-extension-wallet/.env.defaults
Original file line number Diff line number Diff line change
Expand Up @@ -10,6 +10,8 @@ ADA_PRICE_POLLING_IN_SEC=60
TOKEN_PRICE_POLLING_IN_SEC=300
SAVED_PRICE_DURATION_IN_MINUTES=720
WALLET_POLLING_INTERVAL_IN_SEC=45
# options for log level: trace, debug, info, warn, error, fatal
DEFAULT_LOG_LEVEL=info

# Feature Flags
USE_PASSWORD_VERIFICATION=false
Expand Down
2 changes: 2 additions & 0 deletions apps/browser-extension-wallet/.env.developerpreview
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ AVAILABLE_CHAINS=Sanchonet
ADA_PRICE_POLLING_IN_SEC=60
TOKEN_PRICE_POLLING_IN_SEC=300
SAVED_PRICE_DURATION_IN_MINUTES=720
# options for log level: trace, debug, info, warn, error, fatal
DEFAULT_LOG_LEVEL=info

# Feature Flags
USE_PASSWORD_VERIFICATION=false
Expand Down
2 changes: 2 additions & 0 deletions apps/browser-extension-wallet/.env.example
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,8 @@ ADA_PRICE_POLLING_IN_SEC=60
TOKEN_PRICE_POLLING_IN_SEC=300
SAVED_PRICE_DURATION_IN_MINUTES=720
WALLET_POLLING_INTERVAL_IN_SEC=45
# options for log level: trace, debug, info, warn, error, fatal
DEFAULT_LOG_LEVEL=info

# Feature Flags
USE_PASSWORD_VERIFICATION=false
Expand Down
5 changes: 4 additions & 1 deletion apps/browser-extension-wallet/src/config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { BlockfrostClientConfig } from '@cardano-sdk/cardano-services-client';
import { Milliseconds } from '@cardano-sdk/core';
import { Wallet } from '@lace/cardano';
import { EnvironmentTypes } from '@stores';
import { LogLevelString } from '@lace/common';

type ByNetwork<T> = {
[key in Wallet.ChainName]: T;
Expand Down Expand Up @@ -34,6 +35,7 @@ export type Config = {
DEFAULT_SUBMIT_API: string;
GOV_TOOLS_URLS: Record<EnvironmentTypes, string>;
SESSION_TIMEOUT: Milliseconds;
DEFAULT_LOG_LEVEL: LogLevelString;
};

// eslint-disable-next-line complexity
Expand Down Expand Up @@ -150,6 +152,7 @@ export const config = (): Config => {
!Number.isNaN(Number.parseInt(process.env.SESSION_TIMEOUT))
? Number.parseInt(process.env.SESSION_TIMEOUT)
: 1000 * 60 * 5
)
),
DEFAULT_LOG_LEVEL: process.env.DEFAULT_LOG_LEVEL as LogLevelString
};
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ import { getBaseUrlForChain, getMagicForChain } from '@src/utils/chain';
import { BackgroundService, UserIdService as UserIdServiceInterface } from '../types';
import { getBackgroundStorage } from '@lib/scripts/background/storage';
import { ExperimentName } from '@providers/ExperimentsProvider/types';
import { logger } from '@lace/common';
import { LogLevelString, StringifyLogger } from '@lace/common';
import { config } from '@src/config';
import Bottleneck from 'bottleneck';
import { RateLimiter } from '@cardano-sdk/cardano-services-client';
Expand Down Expand Up @@ -40,10 +40,14 @@ export const rateLimiter: RateLimiter = new Bottleneck({
reservoirIncreaseMaximum: BLOCKFROST_RATE_LIMIT_CONFIG.size
});

export const getProviders = async (chainName: Wallet.ChainName): Promise<Wallet.WalletProvidersDependencies> => {
export const getProviders = async (
chainName: Wallet.ChainName,
logLevel: LogLevelString
): Promise<Wallet.WalletProvidersDependencies> => {
const baseCardanoServicesUrl = getBaseUrlForChain(chainName);
const magic = getMagicForChain(chainName);
const { customSubmitTxUrl, featureFlags } = await getBackgroundStorage();
const logger = new StringifyLogger(logLevel);

const isExperimentEnabled = (experimentName: ExperimentName) => !!(featureFlags?.[magic]?.[experimentName] ?? false);

Expand Down
Original file line number Diff line number Diff line change
@@ -1,9 +1,11 @@
import { createBackgroundMessenger } from '@cardano-sdk/web-extension';
import { logger } from '@lace/common';
import { LogLevelString, StringifyLogger } from '@lace/common';
import { TRACK_POPUP_CHANNEL } from '@src/utils/constants';
import { distinctUntilChanged, map, share } from 'rxjs';
import { runtime } from 'webextension-polyfill';

const logger = new StringifyLogger(process.env.DEFAULT_LOG_LEVEL as LogLevelString);

const channel = createBackgroundMessenger({ logger, runtime }).getChannel(TRACK_POPUP_CHANNEL);
export const isLacePopupOpen$ = channel.ports$.pipe(
map((ports) => ports.size > 0),
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -39,7 +39,6 @@ import axiosFetchAdapter from '@shiroyasha9/axios-fetch-adapter';
import { SharedWalletScriptKind } from '@lace/core';
import { getBaseUrlForChain, getMagicForChain } from '@utils/chain';
import { cacheNamiMetadataSubscription } from './cache-nami-metadata';
import { logger } from '@lace/common';
import { getBackgroundStorage } from '@lib/scripts/background/storage';
import { ExperimentName } from '@providers/ExperimentsProvider/types';
import { requestMessage$ } from './services/utilityServices';
Expand All @@ -48,9 +47,12 @@ import { ExtensionDocumentStore } from './storage/extension-document-store';
import { ExtensionBlobKeyValueStore } from './storage/extension-blob-key-value-store';
import { ExtensionBlobCollectionStore } from './storage/extension-blob-collection-store';
import { migrateCollectionStore, migrateWalletStores, shouldAttemptWalletStoresMigration } from './storage/migrations';
import { StringifyLogger, LogLevelString } from '@lace/common';
import { isLacePopupOpen$, createUserSessionTracker, isLaceTabActive$ } from './session';
import { TrackerSubject } from '@cardano-sdk/util-rxjs';

const logger = new StringifyLogger(process.env.DEFAULT_LOG_LEVEL as LogLevelString);

export const dAppConnectorActivity$ = new Subject<void>();
const pollController$ = new TrackerSubject(
createUserSessionTracker(isLacePopupOpen$, isLaceTabActive$, dAppConnectorActivity$, SESSION_TIMEOUT).pipe(
Expand Down Expand Up @@ -123,7 +125,9 @@ const walletFactory: WalletFactory<Wallet.WalletMetadata, Wallet.AccountMetadata
// eslint-disable-next-line complexity, max-statements
create: async ({ chainId, accountIndex }, wallet, { stores, witnesser }) => {
const chainName: Wallet.ChainName = networkMagicToChainName(chainId.networkMagic);
let providers = await getProviders(chainName);
const backgroundStorage = await getBackgroundStorage();
const logLevel = backgroundStorage?.logLevel || (process.env.DEFAULT_LOG_LEVEL as LogLevelString);
let providers = await getProviders(chainName, logLevel);

const baseUrl = getBaseUrlForChain(chainName);

Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { AuthorizedDappStorage } from '@src/types/dappConnector';
import type { Message } from './background-service';
import { ADAPrices } from './prices';
import { ExperimentName } from '@providers/ExperimentsProvider/types';
import { LogLevelString } from '@lace/common';

export interface PendingMigrationState {
from: string;
Expand Down Expand Up @@ -37,6 +38,7 @@ export interface BackgroundStorage {
};
dappInjectCompatibilityMode?: boolean;
optedInBeta?: boolean;
logLevel?: LogLevelString;
}

export type BackgroundStorageKeys = keyof BackgroundStorage;
Expand Down
4 changes: 1 addition & 3 deletions packages/cardano/src/wallet/lib/providers.ts
Original file line number Diff line number Diff line change
Expand Up @@ -97,11 +97,9 @@ let wsProvider: CardanoWsClient;
export const createProviders = ({
axiosAdapter,
env: { baseCardanoServicesUrl: baseUrl, customSubmitTxUrl, blockfrostConfig },
logger,
logger = console,
experiments: { useWebSocket }
}: ProvidersConfig): WalletProvidersDependencies => {
if (!logger) logger = console;

const httpProviderConfig: CreateHttpProviderConfig<Provider> = { baseUrl, logger, adapter: axiosAdapter };

const blockfrostClient = new BlockfrostClient(blockfrostConfig, {
Expand Down
49 changes: 41 additions & 8 deletions packages/common/src/stringifyLogger.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,71 @@
/* eslint-disable no-console */
/* eslint-disable no-console, no-magic-numbers */
/* eslint-disable @typescript-eslint/no-explicit-any */
import { Logger } from 'ts-log';
import { toSerializableObject } from '@cardano-sdk/util';

enum LogLevel {
fatal = 0,
error = 1,
warn = 2,
info = 3,
debug = 4,
trace = 5
}

export type LogLevelString = keyof typeof LogLevel;

export class StringifyLogger implements Logger {
private readonly logLevel: LogLevel;

constructor(logLevel: LogLevelString = 'info') {
if (!(logLevel in LogLevel)) {
throw new Error(`Invalid log level: ${logLevel}`);
}
this.logLevel = LogLevel[logLevel];
}

private convertParams(params: any[]) {
return params.map((param) =>
param && typeof param === 'object' ? JSON.stringify(toSerializableObject(param)) : param
);
}

private shouldLog(level: LogLevel) {
return level <= this.logLevel;
}

trace(...params: any[]): void {
console.trace(...this.convertParams(params));
if (this.shouldLog(LogLevel.trace)) {
console.trace(...this.convertParams(params));
}
}

debug(...params: any[]): void {
console.debug(...this.convertParams(params));
if (this.shouldLog(LogLevel.debug)) {
console.debug(...this.convertParams(params));
}
}

info(...params: any[]): void {
console.log(...this.convertParams(params));
console.log('info', this.shouldLog(LogLevel.info), this.logLevel);
if (this.shouldLog(LogLevel.info)) {
console.info(...this.convertParams(params));
}
}

warn(...params: any[]): void {
console.warn(...this.convertParams(params));
if (this.shouldLog(LogLevel.warn)) {
console.warn(...this.convertParams(params));
}
}

error(...params: any[]): void {
console.error(...this.convertParams(params));
if (this.shouldLog(LogLevel.error)) {
console.error(...this.convertParams(params));
}
}

fatal(...params: any[]): void {
console.error(...this.convertParams(params));
}
}

export const logger = new StringifyLogger();

0 comments on commit ced48b3

Please sign in to comment.