Skip to content

Commit

Permalink
feat: enable setting logging level in the application
Browse files Browse the repository at this point in the history
  • Loading branch information
greatertomi committed Jan 30, 2025
1 parent cfd6b7b commit 3a9fd12
Show file tree
Hide file tree
Showing 9 changed files with 126 additions and 15 deletions.
Original file line number Diff line number Diff line change
@@ -1,7 +1,14 @@
import React from 'react';
import { ContentLayout } from '@components/Layout';
import { useTranslation } from 'react-i18next';
import { SettingsWallet, SettingsSecurity, SettingsHelp, SettingsLegal, SettingsPreferences } from '..';
import {
SettingsWallet,
SettingsSecurity,
SettingsHelp,
SettingsLegal,
SettingsPreferences,
SettingsLogging
} from '..';
import { SettingsRemoveWallet } from '@src/views/browser-view/features/settings/components/SettingsRemoveWallet';

export interface SettingsProps {
Expand All @@ -24,6 +31,7 @@ export const Settings = ({ defaultPassphraseVisible, defaultMnemonic }: Settings
/>
<SettingsHelp popupView />
<SettingsLegal />
<SettingsLogging />
<SettingsRemoveWallet popupView />
</div>
</ContentLayout>
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -123,6 +123,14 @@ 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);
webStorage.onChanged.addListener((changes) => {
const oldLogLevelValue = changes.BACKGROUND_STORAGE?.oldValue?.logLevel;
const newLogLevelValue = changes.BACKGROUND_STORAGE?.newValue?.logLevel;
if (oldLogLevelValue !== newLogLevelValue) {
logger.setLogLevel(newLogLevelValue);
}
});

let providers = await getProviders(chainName);

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 { FeatureFlagPayloads, GroupedFeatureFlags } from '@lib/scripts/types/feature-flags';
import { LogLevelString } from '@lace/common';

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

export type BackgroundStorageKeys = keyof BackgroundStorage;
Expand Down
Original file line number Diff line number Diff line change
@@ -1,5 +1,13 @@
import React from 'react';
import { SettingsWallet, SettingsSecurity, SettingsLegal, SettingsAbout, SettingsHelp, SettingsPreferences } from './';
import {
SettingsWallet,
SettingsSecurity,
SettingsLegal,
SettingsAbout,
SettingsHelp,
SettingsPreferences,
SettingsLogging
} from './';
import { PageTitle } from '@components/Layout';
import { useTranslation } from 'react-i18next';
import { Layout, SectionLayout } from '@src/views/browser-view/components/Layout';
Expand Down Expand Up @@ -39,6 +47,7 @@ export const SettingsLayout = ({
<SettingsSecurity defaultPassphraseVisible={defaultPassphraseVisible} defaultMnemonic={defaultMnemonic} />
<SettingsHelp />
<SettingsLegal />
<SettingsLogging />
<SettingsRemoveWallet />
</SectionLayout>
</Layout>
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,52 @@
import React, { ReactElement, useEffect, useState } from 'react';
import styles from '@views/browser/features/settings/components/SettingsLayout.module.scss';
import { SettingsCard, SettingsLink } from '@views/browser/features/settings';
import { Typography } from 'antd';
import { Switch } from '@lace/common';
import { getBackgroundStorage, setBackgroundStorage } from '@lib/scripts/background/storage';
import { useTranslation } from 'react-i18next';

const { Title } = Typography;

export const SettingsLogging = (): ReactElement => {
const { t } = useTranslation();
const [isLoggingEnabled, setIsLoggingEnabled] = useState(false);

useEffect(() => {
(async () => {
const backgroundStorage = await getBackgroundStorage();
setIsLoggingEnabled(backgroundStorage.logLevel === 'debug');
})();
}, []);

const handleLoggingOnChange = async () => {
// todo: change this to 'info'
await setBackgroundStorage({ logLevel: isLoggingEnabled ? 'warn' : 'debug' });
setIsLoggingEnabled(!isLoggingEnabled);
};

return (
<>
<SettingsCard>
<Title level={5} className={styles.heading5} data-testid={'debugger-heading'}>
{t('browserView.settings.debugging.title')}
</Title>
<SettingsLink
onClick={handleLoggingOnChange}
description={t('browserView.settings.debugging.description')}
addon={
<Switch
testId="settings-logging-switch"
checked={isLoggingEnabled}
onChange={() => setIsLoggingEnabled(!isLoggingEnabled)}
className={styles.analyticsSwitch}
/>
}
data-testid="settings-logging-level-section"
>
{t('browserView.settings.debugging.title')}
</SettingsLink>
</SettingsCard>
</>
);
};
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@ export * from './SettingsLink';
export * from './SettingsWallet';
export * from './SettingsSecurity';
export * from './SettingsLegal';
export * from './SettingsLogging';
export * from './SettingsHelp';
export * from './GeneralSettingsDrawer';
export * from './PassphraseSettingsDrawer';
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
51 changes: 41 additions & 10 deletions packages/common/src/stringifyLogger.ts
Original file line number Diff line number Diff line change
@@ -1,38 +1,69 @@
/* 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';

export class StringifyLogger implements Logger {
enum LogLevel {
error = 0,
warn = 1,
info = 2,
debug = 3,
trace = 4
}

export type LogLevelString = keyof typeof LogLevel;

class StringifyLogger implements Logger {
private 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;
}

setLogLevel(logLevel: LogLevelString) {
this.logLevel = LogLevel[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));
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));
}

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

export const logger = new StringifyLogger();
Original file line number Diff line number Diff line change
Expand Up @@ -363,6 +363,8 @@
"browserView.settings.wallet.walletSync.ctaLabel": "Sync",
"browserView.settings.wallet.walletSync.description": "Sync new addresses of your HD wallet. This may be needed if you're using other HD wallets at the same time as Lace",
"browserView.settings.wallet.walletSync.title": "HD wallet sync",
"browserView.settings.debugging.title": "Debugging",
"browserView.settings.debugging.description": "Enable debugging logs in the console",
"browserView.sideMenu.dapps.header": "Open Dapps",
"browserView.sideMenu.links.activity": "Activity",
"browserView.sideMenu.links.addNewWallet": "Add new wallet",
Expand Down

0 comments on commit 3a9fd12

Please sign in to comment.