From cd54893fef012f7a1447c2f00ee039b1eb20c73e Mon Sep 17 00:00:00 2001 From: Isla Koenigsknecht Date: Wed, 15 May 2024 11:12:57 -0400 Subject: [PATCH] Remove all references to the old logger --- .../src/nest/websocketOverTor/listener.ts | 16 ++--- packages/common/src/invitationCode.ts | 22 +++---- packages/common/src/logger.ts | 8 +-- packages/e2e-tests/src/logger.ts | 4 +- packages/e2e-tests/src/selectors.ts | 53 +++++++-------- .../src/tests/backwardsCompatibility.test.ts | 17 +++-- .../src/tests/invitationLink.test.ts | 49 +++++++------- .../src/tests/joiningWithQSS.test.ts | 9 ++- .../src/tests/multipleClients.test.ts | 64 +++++++++---------- .../e2e-tests/src/tests/oneClient.test.ts | 11 ++-- .../e2e-tests/src/tests/userProfile.test.ts | 18 +++--- packages/e2e-tests/src/utils.ts | 61 +++++++++--------- packages/identity/src/createUserCert.ts | 5 +- packages/identity/src/logger.ts | 4 +- packages/integration-tests/src/bot/bot.ts | 32 +++++----- .../src/integrationTests/appActions.ts | 12 ++-- .../src/integrationTests/assertions.ts | 26 ++++---- .../src/integrationTests/sendFiles.test.ts | 6 +- packages/integration-tests/src/logger.ts | 4 +- .../src/testUtils/actions.ts | 16 ++--- .../src/testUtils/assertions.ts | 18 +++--- packages/integration-tests/src/utils.ts | 12 ++-- packages/logger/src/index.ts | 24 +------ 23 files changed, 244 insertions(+), 247 deletions(-) diff --git a/packages/backend/src/nest/websocketOverTor/listener.ts b/packages/backend/src/nest/websocketOverTor/listener.ts index 54c63e6ca1..114058847b 100644 --- a/packages/backend/src/nest/websocketOverTor/listener.ts +++ b/packages/backend/src/nest/websocketOverTor/listener.ts @@ -1,6 +1,6 @@ // import os from 'os' // import { createServer } from 'it-ws/server' -// import logger from '../../logger' +// import { createLogger } from '../../logger' // import { socketToMaConn } from './socket-to-conn.js' // import { EventEmitter, CustomEvent } from './events' // import type { Listener, ListenerEvents, CreateListenerOptions } from '@libp2p/interface-transport' @@ -10,7 +10,7 @@ // import type { Connection } from '@libp2p/interface-connection' // import type { Multiaddr } from '@multiformats/multiaddr' -// const log = logger('libp2p:websockets:listener') +// const logger = createLogger('libp2p:websockets:listener') // // @ts-ignore // class WebSocketListener extends EventEmitter implements Listener { @@ -33,7 +33,7 @@ // ...init, // onConnection: (stream: DuplexWebSocket) => { // const maConn = socketToMaConn(stream, this.toMultiaddr(stream.remoteAddress ?? '', stream.remotePort ?? 0)) -// log('new inbound connection %s', maConn.remoteAddr) +// logger.info('new inbound connection %s', maConn.remoteAddr) // this.connections.add(stream) @@ -44,7 +44,7 @@ // try { // void init.upgrader.upgradeInbound(maConn) // .then((conn) => { -// log('inbound connection %s upgraded', maConn.remoteAddr) +// logger.info('inbound connection %s upgraded', maConn.remoteAddr) // if (init?.handler != null) { // init?.handler(conn) @@ -55,16 +55,16 @@ // })) // }) // .catch(async err => { -// log.error('inbound connection failed to upgrade', err) +// logger.error('inbound connection failed to upgrade', err) // await maConn.close().catch(err => { -// log.error('inbound connection failed to close after upgrade failed', err) +// logger.error('inbound connection failed to close after upgrade failed', err) // }) // }) // } catch (err) { -// log.error('inbound connection failed to upgrade', err) +// logger.error('inbound connection failed to upgrade', err) // maConn.close().catch(err => { -// log.error('inbound connection failed to close after upgrade failed', err) +// logger.error('inbound connection failed to close after upgrade failed', err) // }) // } // } diff --git a/packages/common/src/invitationCode.ts b/packages/common/src/invitationCode.ts index 8be7478615..8d26195cfc 100644 --- a/packages/common/src/invitationCode.ts +++ b/packages/common/src/invitationCode.ts @@ -2,8 +2,8 @@ import { InvitationData, InvitationDataV1, InvitationDataV2, InvitationDataVersi import { QUIET_JOIN_PAGE } from './const' import { createLibp2pAddress, isPSKcodeValid } from './libp2p' // import { CID } from 'multiformats/cid' // Fixme: dependency issue -import Logger from './logger' -const logger = Logger('invite') +import { createLogger } from './logger' +const logger = createLogger('invite') // V1 invitation code format (p2p without relay) export const PSK_PARAM_KEY = 'k' @@ -108,7 +108,7 @@ const parseDeepUrl = ({ url, expectedProtocol = `${DEEP_URL_SCHEME}:` }: ParseDe if (!data) throw new Error(`Could not parse invitation code from deep url '${url}'`) - logger(`Invitation data '${data}' parsed`) + logger.info(`Invitation data '${data}' parsed`) return data } @@ -138,18 +138,18 @@ export const p2pAddressesToPairs = (addresses: string[]): InvitationPair[] => { try { peerId = peerAddress.split('/p2p/')[1] } catch (e) { - console.info(`Could not add peer address '${peerAddress}' to invitation url. Reason: ${e.message}`) + logger.error(`Could not add peer address '${peerAddress}' to invitation url.`, e) continue } try { onionAddress = peerAddress.split('/tcp/')[0].split('/dns4/')[1] } catch (e) { - console.info(`Could not add peer address '${peerAddress}' to invitation url. Reason: ${e.message}`) + logger.error(`Could not add peer address '${peerAddress}' to invitation url.`, e) continue } if (!peerId || !onionAddress) { - console.error(`No peerId or address in ${peerAddress}`) + logger.error(`No peerId or address in ${peerAddress}`) continue } const rawAddress = onionAddress.endsWith('.onion') ? onionAddress.split('.')[0] : onionAddress @@ -210,10 +210,10 @@ export const argvInvitationCode = (argv: string[]): InvitationData | null => { let invitationData: InvitationData | null = null for (const arg of argv) { if (!arg.startsWith(DEEP_URL_SCHEME_WITH_SEPARATOR)) { - console.log('Not a deep url, not parsing', arg) + logger.warn('Not a deep url, not parsing', arg) continue } - logger('Parsing deep url', arg) + logger.info('Parsing deep url', arg) invitationData = parseInvitationCodeDeepUrl(arg) switch (invitationData.version) { case InvitationDataVersion.v1: @@ -230,11 +230,11 @@ export const argvInvitationCode = (argv: string[]): InvitationData | null => { const peerDataValid = ({ peerId, onionAddress }: { peerId: string; onionAddress: string }): boolean => { if (!peerId.match(PEER_ID_REGEX)) { // TODO: test it more properly e.g with PeerId.createFromB58String(peerId.trim()) - logger(`PeerId ${peerId} is not valid`) + logger.warn(`PeerId ${peerId} is not valid`) return false } if (!onionAddress.trim().match(ONION_ADDRESS_REGEX)) { - logger(`Onion address ${onionAddress} is not valid`) + logger.warn(`Onion address ${onionAddress} is not valid`) return false } return true @@ -258,7 +258,7 @@ const validateUrlParams = (params: URLSearchParams, requiredParams: string[]) => } const isParamValid = (param: string, value: string) => { - logger(`Validating param ${param} with value ${value}`) + logger.info(`Validating param ${param} with value ${value}`) switch (param) { case CID_PARAM_KEY: // try { diff --git a/packages/common/src/logger.ts b/packages/common/src/logger.ts index 31360daef5..25868475f3 100644 --- a/packages/common/src/logger.ts +++ b/packages/common/src/logger.ts @@ -1,7 +1,3 @@ -import { logger } from '@quiet/logger' +import { createQuietLogger } from '@quiet/logger' -const createLogger = (name: string) => { - return logger('utils')(name) -} - -export default createLogger +export const createLogger = createQuietLogger('utils') diff --git a/packages/e2e-tests/src/logger.ts b/packages/e2e-tests/src/logger.ts index 322753c0a9..d66e1b6ef3 100644 --- a/packages/e2e-tests/src/logger.ts +++ b/packages/e2e-tests/src/logger.ts @@ -1,3 +1,3 @@ -import logger from '@quiet/logger' +import { createQuietLogger } from '@quiet/logger' -export default logger('e2e') +export const createLogger = createQuietLogger('e2e') diff --git a/packages/e2e-tests/src/selectors.ts b/packages/e2e-tests/src/selectors.ts index c80f8c3b26..24b473721e 100644 --- a/packages/e2e-tests/src/selectors.ts +++ b/packages/e2e-tests/src/selectors.ts @@ -2,6 +2,9 @@ import { By, Key, type ThenableWebDriver, type WebElement, until } from 'seleniu import { BuildSetup, sleep, type BuildSetupInit } from './utils' import path from 'path' import { BACK_ARROW_DATA_TESTID } from './enums' +import { createLogger } from './logger' + +const logger = createLogger('selectors') export class App { thenableWebDriver?: ThenableWebDriver @@ -24,7 +27,7 @@ export class App { } async open() { - console.log('opening the app', this.buildSetup.dataDir) + logger.info('opening the app', this.buildSetup.dataDir) this.buildSetup.resetDriver() await this.buildSetup.createChromeDriver() this.isOpened = true @@ -36,7 +39,7 @@ export class App { async close(options?: { forceSaveState?: boolean }) { if (!this.isOpened) return - console.log('Closing the app', this.buildSetup.dataDir) + logger.info('Closing the app', this.buildSetup.dataDir) if (options?.forceSaveState) { await this.saveState() // Selenium creates community and closes app so fast that redux state may not be saved properly await this.waitForSavedState() @@ -48,11 +51,11 @@ export class App { await new Promise(resolve => setTimeout(() => resolve(), 2000)) } this.isOpened = false - console.log('App closed', this.buildSetup.dataDir) + logger.info('App closed', this.buildSetup.dataDir) } async cleanup(force: boolean = false) { - console.log(`Performing app cleanup`, this.buildSetup.dataDir) + logger.info(`Performing app cleanup`, this.buildSetup.dataDir) if (this.isOpened) { throw new Error(`App with dataDir ${this.buildSetup.dataDir} is still open, close before cleaning up!`) } @@ -171,7 +174,7 @@ export class UserProfileContextMenu { 500 ) - console.log('clicking back button') + logger.info('clicking back button') // await this.driver.executeScript('arguments[0].click();', button) await button.click() } @@ -338,12 +341,12 @@ export class Channel { } async waitForUserMessage(username: string, messageContent: string) { - console.log(`Waiting for user "${username}" message "${messageContent}"`) + logger.info(`Waiting for user "${username}" message "${messageContent}"`) return this.driver.wait(async () => { const messages = await this.getUserMessages(username) const hasMessage = messages.find(async msg => { const messageText = await msg.getText() - console.log(`got message "${messageText}"`) + logger.info(`got message "${messageText}"`) return messageText.includes(messageContent) }) return hasMessage @@ -393,7 +396,7 @@ export class Channel { } async waitForLabel(username: string, label: string) { - console.log(`Waiting for user's "${username}" label "${label}" label`) + logger.info(`Waiting for user's "${username}" label "${label}" label`) await this.driver.wait(async () => { const labels = await this.driver.findElements(By.xpath(`//*[contains(@data-testid, "userLabel-${username}")]`)) const properLabels = labels.filter(async labelElement => { @@ -405,7 +408,7 @@ export class Channel { } async waitForLabelsNotPresent(username: string) { - console.log(`Waiting for user's "${username}" label to not be present`) + logger.info(`Waiting for user's "${username}" label to not be present`) await this.driver.wait(async () => { const labels = await this.driver.findElements(By.xpath(`//*[contains(@data-testid, "userLabel-${username}")]`)) return labels.length === 0 @@ -441,7 +444,7 @@ export class Sidebar { } async waitForChannelsNum(num: number) { - console.log(`Waiting for ${num} channels`) + logger.info(`Waiting for ${num} channels`) return this.driver.wait(async () => { const channels = await this.getChannelList() return channels.length === num @@ -483,7 +486,7 @@ export class UpdateModal { } get element() { - console.log('Waiting for update modal root element') + logger.info('Waiting for update modal root element') return this.driver.wait( until.elementLocated(By.xpath("//h3[text()='Software update']/ancestor::div[contains(@class,'MuiModal-root')]")) ) @@ -491,24 +494,24 @@ export class UpdateModal { async close() { const updateModalRootElement = await this.element - console.log('Found update modal root element') + logger.info('Found update modal root element') const closeButton = await updateModalRootElement.findElement( By.xpath("//*[self::div[@data-testid='ModalActions']]/button") ) try { - console.log('Before clicking update modal close button') + logger.info('Before clicking update modal close button') await closeButton.click() return } catch (e) { - console.error('Error while clicking close button on update modal', e.message) + logger.error('Error while clicking close button on update modal', e) } try { const log = await this.driver.executeScript('arguments[0].click();', closeButton) - console.log('executeScript', log) + logger.info('executeScript', log) } catch (e) { - console.log('Probably clicked hidden close button on update modal') + logger.warn('Probably clicked hidden close button on update modal') } } } @@ -574,7 +577,7 @@ export class DebugModeModal { private readonly driver: ThenableWebDriver constructor(driver: ThenableWebDriver) { this.driver = driver - console.log('Debug modal') + logger.info('Debug modal') } get element() { @@ -589,25 +592,25 @@ export class DebugModeModal { if (!process.env.TEST_MODE) return let button try { - console.log('Closing debug modal') + logger.info('Closing debug modal') await this.element.isDisplayed() - console.log('Debug modal title is displayed') + logger.info('Debug modal title is displayed') button = await this.button - console.log('Debug modal button is displayed') + logger.info('Debug modal button is displayed') } catch (e) { - console.log('Debug modal might have been covered by "join community" modal', e.message) + logger.error('Debug modal might have been covered by "join community" modal', e) return } await button.isDisplayed() - console.log('Button is displayed') + logger.info('Button is displayed') await button.click() - console.log('Button click') + logger.info('Button click') try { const log = await this.driver.executeScript('arguments[0].click();', button) - console.log('executeScript', log) + logger.info('executeScript', log) } catch (e) { - console.log('Probably clicked hidden close button on debug modal') + logger.warn('Probably clicked hidden close button on debug modal') } await new Promise(resolve => setTimeout(() => resolve(), 2000)) } diff --git a/packages/e2e-tests/src/tests/backwardsCompatibility.test.ts b/packages/e2e-tests/src/tests/backwardsCompatibility.test.ts index e238cbb81a..d49c5e3741 100644 --- a/packages/e2e-tests/src/tests/backwardsCompatibility.test.ts +++ b/packages/e2e-tests/src/tests/backwardsCompatibility.test.ts @@ -9,6 +9,9 @@ import { Sidebar, } from '../selectors' import { BACKWARD_COMPATIBILITY_BASE_VERSION, BuildSetup, copyInstallerFile, downloadInstaller } from '../utils' +import { createLogger } from '../logger' + +const logger = createLogger('backwardsCompatibility') jest.setTimeout(1200000) describe('Backwards Compatibility', () => { @@ -55,10 +58,10 @@ describe('Backwards Compatibility', () => { ownerAppOldVersion .closeUpdateModalIfPresent() .then(async () => { - console.log('Closed update modal') + logger.info('Closed update modal') }) .catch(err => { - console.log('Could not close update modal', err) + logger.error('Could not close update modal', err) }) }) @@ -142,21 +145,21 @@ describe('Backwards Compatibility', () => { // ________________________________ it('Owner opens the app in new version', async () => { - console.log('New version', 1) + logger.info('New version', 1) ownerAppNewVersion = new App({ dataDir }) await ownerAppNewVersion.open() }) if (isAlpha) { it('Owner closes debug modal if opened', async () => { - console.log('New version', 2) + logger.info('New version', 2) const debugModal = new DebugModeModal(ownerAppNewVersion.driver) await debugModal.close() }) } it('Owener sees general channel', async () => { - console.log('New version', 3) + logger.info('New version', 3) generalChannel = new Channel(ownerAppNewVersion.driver, 'general') const isGeneralChannel = await generalChannel.element.isDisplayed() const generalChannelText = await generalChannel.element.getText() @@ -165,7 +168,7 @@ describe('Backwards Compatibility', () => { }) it('Confirm that the opened app is the latest version', async () => { - console.log('New version', 4) + logger.info('New version', 4) await new Promise(resolve => setTimeout(() => resolve(), 10000)) const settingsModal = await new Sidebar(ownerAppNewVersion.driver).openSettings() const isSettingsModal = await settingsModal.element.isDisplayed() @@ -177,7 +180,7 @@ describe('Backwards Compatibility', () => { }) it('Check number of messages on second channel', async () => { - console.log('New version', 5) + logger.info('New version', 5) await new Promise(resolve => setTimeout(() => resolve(), 2000)) sidebar = new Sidebar(ownerAppNewVersion.driver) await sidebar.switchChannel(newChannelName) diff --git a/packages/e2e-tests/src/tests/invitationLink.test.ts b/packages/e2e-tests/src/tests/invitationLink.test.ts index 321bc77489..fdb5816ccb 100644 --- a/packages/e2e-tests/src/tests/invitationLink.test.ts +++ b/packages/e2e-tests/src/tests/invitationLink.test.ts @@ -11,6 +11,9 @@ import { import { composeInvitationDeepUrl, parseInvitationCode, userJoinedMessage } from '@quiet/common' import { execSync } from 'child_process' import { type SupportedPlatformDesktop } from '@quiet/types' +import { createLogger } from '../logger' + +const logger = createLogger('invitationLink') jest.setTimeout(1900000) it.todo('New user joins using invitation link while having app closed') @@ -44,12 +47,12 @@ describe('New user joins using invitation link while having app opened', () => { describe('Stages:', () => { it('Owner opens the app', async () => { - console.log('Invitation Link', 1) + logger.info('Invitation Link', 1) await ownerApp.open() }) it('JoinCommunityModal - owner switches to create community', async () => { - console.log('Invitation Link', 4) + logger.info('Invitation Link', 4) const joinModal = new JoinCommunityModal(ownerApp.driver) const isJoinModal = await joinModal.element.isDisplayed() expect(isJoinModal).toBeTruthy() @@ -57,7 +60,7 @@ describe('New user joins using invitation link while having app opened', () => { }) it('CreateCommunityModal - owner creates his community', async () => { - console.log('Invitation Link', 5) + logger.info('Invitation Link', 5) const createModal = new CreateCommunityModal(ownerApp.driver) const isCreateModal = await createModal.element.isDisplayed() expect(isCreateModal).toBeTruthy() @@ -66,7 +69,7 @@ describe('New user joins using invitation link while having app opened', () => { }) it('RegisterUsernameModal - owner has registered', async () => { - console.log('Invitation Link', 6) + logger.info('Invitation Link', 6) const registerModal = new RegisterUsernameModal(ownerApp.driver) const isRegisterModal = await registerModal.element.isDisplayed() expect(isRegisterModal).toBeTruthy() @@ -75,7 +78,7 @@ describe('New user joins using invitation link while having app opened', () => { }) it('Owner sees general channel', async () => { - console.log('Invitation Link', 8) + logger.info('Invitation Link', 8) const generalChannel = new Channel(ownerApp.driver, 'general') const isGeneralChannel = await generalChannel.element.isDisplayed() const generalChannelText = await generalChannel.element.getText() @@ -84,7 +87,7 @@ describe('New user joins using invitation link while having app opened', () => { }) it('Owner opens the settings tab and gets an invitation code', async () => { - console.log('Invitation Link', 9) + logger.info('Invitation Link', 9) const settingsModal = await new Sidebar(ownerApp.driver).openSettings() const isSettingsModal = await settingsModal.element.isDisplayed() expect(isSettingsModal).toBeTruthy() @@ -92,7 +95,7 @@ describe('New user joins using invitation link while having app opened', () => { await new Promise(resolve => setTimeout(() => resolve(), 1000)) const invitationCodeElement = await settingsModal.invitationCode() invitationCode = await invitationCodeElement.getText() - console.log('Received invitation link:', invitationCode) + logger.info('Received invitation link:', invitationCode) await settingsModal.close() }) @@ -100,20 +103,20 @@ describe('New user joins using invitation link while having app opened', () => { // MacOS tries to open link in first app (owner's app) so the workaround is to temporarly close owner // while clicking on the invitation link to have just one instance of app opened it('Owner closes the app', async () => { - console.log('Invitation Link', 10) + logger.info('Invitation Link', 10) await ownerApp.close({ forceSaveState: true }) }) } it('Guest opens the app', async () => { - console.log('Invitation Link', 11) - console.log('Guest opens app') + logger.info('Invitation Link', 11) + logger.info('Guest opens app') await guestApp.open() }) it.skip('Guest clicks invitation link with invalid invitation code', async () => { // Fix when modals ordering is fixed (joining modal hides warning modal) - console.log('opening invalid code') + logger.info('opening invalid code') execSync( `xdg-open ${composeInvitationDeepUrl({ pairs: [{ peerId: 'invalid', onionAddress: 'alsoInvalid' }], @@ -133,7 +136,7 @@ describe('New user joins using invitation link while having app opened', () => { }) it('Guest clicks invitation link with valid code', async () => { - console.log('Invitation Link', 14) + logger.info('Invitation Link', 14) // Extract code from copied invitation url const url = new URL(invitationCode) @@ -147,22 +150,22 @@ describe('New user joins using invitation link while having app opened', () => { expect(() => parseInvitationCode(copiedCode)).not.toThrow() const data = parseInvitationCode(copiedCode) const commandFull = `${command[process.platform as SupportedPlatformDesktop]} ${process.platform === 'win32' ? '""' : ''} "${composeInvitationDeepUrl(data)}"` - console.log(`Calling ${commandFull}`) + logger.info(`Calling ${commandFull}`) execSync(commandFull) - console.log('Guest opened invitation link') + logger.info('Guest opened invitation link') }) it('Guest is redirected to UsernameModal', async () => { - console.log('Invitation Link', 15) - console.log('Guest sees username modal') + logger.info('Invitation Link', 15) + logger.info('Guest sees username modal') const registerModal = new RegisterUsernameModal(guestApp.driver) const isRegisterModalDisplayed = await registerModal.element.isDisplayed() expect(isRegisterModalDisplayed).toBeTruthy() }) it('Guest submits username', async () => { - console.log('Invitation Link', 16) - console.log('Guest submits username') + logger.info('Invitation Link', 16) + logger.info('Guest submits username') const registerModal = new RegisterUsernameModal(guestApp.driver) await registerModal.typeUsername(joiningUserUsername) await registerModal.submit() @@ -171,8 +174,8 @@ describe('New user joins using invitation link while having app opened', () => { if (process.platform === 'darwin') { // Open the owner's app again so guest would be able to register it('Owner opens the app again', async () => { - console.log('Invitation Link', 17) - console.log('Owner opens the app again') + logger.info('Invitation Link', 17) + logger.info('Owner opens the app again') await ownerApp.open() const debugModal = new DebugModeModal(ownerApp.driver) await debugModal.close() @@ -180,15 +183,15 @@ describe('New user joins using invitation link while having app opened', () => { } it('Guest joined a community and sees general channel', async () => { - console.log('Invitation Link', 20) - console.log('guest sees general channel') + logger.info('Invitation Link', 20) + logger.info('guest sees general channel') const generalChannel = new Channel(guestApp.driver, 'general') await generalChannel.element.isDisplayed() }) it('Owner sees that guest joined community', async () => { - console.log('Invitation Link', 21) + logger.info('Invitation Link', 21) const generalChannel = new Channel(ownerApp.driver, 'general') await generalChannel.element.isDisplayed() diff --git a/packages/e2e-tests/src/tests/joiningWithQSS.test.ts b/packages/e2e-tests/src/tests/joiningWithQSS.test.ts index 97a1ef20a5..cee44b2128 100644 --- a/packages/e2e-tests/src/tests/joiningWithQSS.test.ts +++ b/packages/e2e-tests/src/tests/joiningWithQSS.test.ts @@ -5,6 +5,9 @@ import { UserTestData } from '../types' import { sleep } from '../utils' import fs from 'fs' import path from 'path' +import { createLogger } from '../logger' + +const logger = createLogger('joiningWithQSS') jest.setTimeout(1200000) // 20 minutes @@ -78,7 +81,7 @@ describe('User joining with storage server', () => { await sleep(2000) invitationLinkV1 = await invitationCodeElement.getText() await sleep(2000) - console.log({ invitationLinkV1 }) + logger.info({ invitationLinkV1 }) expect(invitationLinkV1).not.toBeUndefined() await settingsModal.close() }) @@ -99,7 +102,7 @@ describe('User joining with storage server', () => { } invitationLinkV2 = decodeURIComponent(composeInvitationShareUrl(data)) - console.log({ invitationLinkV2 }) + logger.info({ invitationLinkV2 }) const serverData = { id: 'id', rootCa: 'rootCa', @@ -121,7 +124,7 @@ describe('User joining with storage server', () => { const joinCommunityModal = new JoinCommunityModal(users.user1.app.driver) const isJoinCommunityModal = await joinCommunityModal.element.isDisplayed() expect(isJoinCommunityModal).toBeTruthy() - console.log({ invitationCode: invitationLinkV2 }) + logger.info({ invitationCode: invitationLinkV2 }) await joinCommunityModal.typeCommunityCode(invitationLinkV2) await joinCommunityModal.submit() }) diff --git a/packages/e2e-tests/src/tests/multipleClients.test.ts b/packages/e2e-tests/src/tests/multipleClients.test.ts index 042aa3dd52..b41c2c9681 100644 --- a/packages/e2e-tests/src/tests/multipleClients.test.ts +++ b/packages/e2e-tests/src/tests/multipleClients.test.ts @@ -8,9 +8,9 @@ import { RegisterUsernameModal, Sidebar, } from '../selectors' -import logger from '../logger' +import { createLogger } from '../logger' import { UserTestData } from '../types' -const log = logger('ManyClients') +const logger = createLogger('multipleClients') jest.setTimeout(1200000) // 20 minutes describe('Multiple Clients', () => { @@ -134,29 +134,29 @@ describe('Multiple Clients', () => { await sleep(2000) invitationCode = await invitationCodeElement.getText() await sleep(2000) - console.log({ invitationCode }) + logger.info({ invitationCode }) expect(invitationCode).not.toBeUndefined() - log('Received invitation code:', invitationCode) + logger.info('Received invitation code:', invitationCode) await settingsModal.close() }) it('First user opens the app', async () => { - console.log('Second client') + logger.info('Second client') await users.user1.app.open() }) it('First user submits invitation code received from owner', async () => { - console.log('new user - 3') + logger.info('new user - 3') const joinCommunityModal = new JoinCommunityModal(users.user1.app.driver) const isJoinCommunityModal = await joinCommunityModal.element.isDisplayed() expect(isJoinCommunityModal).toBeTruthy() - console.log({ invitationCode }) + logger.info({ invitationCode }) await joinCommunityModal.typeCommunityInviteLink(invitationCode) await joinCommunityModal.submit() }) it('First user submits valid username', async () => { - console.log('new user - 5') + logger.info('new user - 5') const registerModal = new RegisterUsernameModal(users.user1.app.driver) const isRegisterModal = await registerModal.element.isDisplayed() expect(isRegisterModal).toBeTruthy() @@ -167,13 +167,13 @@ describe('Multiple Clients', () => { }) it('First user joins successfully sees general channel and sends a message', async () => { - console.log('new user - 7') + logger.info('new user - 7') generalChannelUser1 = new Channel(users.user1.app.driver, 'general') await generalChannelUser1.element.isDisplayed() const isMessageInput2 = await generalChannelUser1.messageInput.isDisplayed() expect(isMessageInput2).toBeTruthy() console.timeEnd(`[${users.user1.app.name}] '${users.user1.username}' joining community time`) - console.log('FETCHING CHANNEL MESSAGES!') + logger.info('FETCHING CHANNEL MESSAGES!') await new Promise(resolve => setTimeout(() => { resolve() @@ -184,7 +184,7 @@ describe('Multiple Clients', () => { it("First user's sent message is visible in a channel", async () => { const messages2 = await generalChannelUser1.getUserMessages(users.user1.username) const messages1 = await generalChannelUser1.getUserMessages(users.owner.username) - console.log({ messages1, messages2 }) + logger.info({ messages1, messages2 }) const text2 = await messages2[1].getText() expect(text2).toEqual(users.user1.messages[0]) }) @@ -199,7 +199,7 @@ describe('Multiple Clients', () => { await sleep(2000) invitationCode = await invitationCodeElement.getText() await sleep(2000) - console.log(`${invitationCode} copied from non owner`) + logger.info(`${invitationCode} copied from non owner`) expect(invitationCode).not.toBeUndefined() await settingsModal.close() }) @@ -209,7 +209,7 @@ describe('Multiple Clients', () => { }) it('Second user opens the app', async () => { - console.log('Third client') + logger.info('Third client') await users.user3.app.open() const debugModal = new DebugModeModal(users.user3.app.driver) await debugModal.close() @@ -219,13 +219,13 @@ describe('Multiple Clients', () => { const joinCommunityModal = new JoinCommunityModal(users.user3.app.driver) const isJoinCommunityModal = await joinCommunityModal.element.isDisplayed() expect(isJoinCommunityModal).toBeTruthy() - console.log({ invitationCode }) + logger.info({ invitationCode }) await joinCommunityModal.typeCommunityInviteLink(invitationCode) await joinCommunityModal.submit() }) it('Second user submits non-valid, duplicated username', async () => { - console.log('duplicated user - 1') + logger.info('duplicated user - 1') const registerModal = new RegisterUsernameModal(users.user3.app.driver) const isRegisterModal = await registerModal.element.isDisplayed() expect(isRegisterModal).toBeTruthy() @@ -236,7 +236,7 @@ describe('Multiple Clients', () => { }) it('Second user submits valid username', async () => { - console.log('duplicated user - 2') + logger.info('duplicated user - 2') const registerModal = new RegisterUsernameModal(users.user3.app.driver) const isRegisterModal = await registerModal.elementUsernameTaken.isDisplayed() expect(isRegisterModal).toBeTruthy() @@ -247,7 +247,7 @@ describe('Multiple Clients', () => { }) it('Second user sees general channel', async () => { - console.log('new user - 7') + logger.info('new user - 7') generalChannelUser3 = new Channel(users.user3.app.driver, 'general') await generalChannelUser3.element.isDisplayed() const isMessageInput = await generalChannelUser3.messageInput.isDisplayed() @@ -256,7 +256,7 @@ describe('Multiple Clients', () => { }) it('Second user can send a message, they see their message tagged as "unregistered"', async () => { - console.log('Second guest FETCHING CHANNEL MESSAGES!') + logger.info('Second guest FETCHING CHANNEL MESSAGES!') await new Promise(resolve => setTimeout(() => { resolve() @@ -350,13 +350,13 @@ describe('Multiple Clients', () => { // End of tests for Windows if (process.platform !== 'win32') { it('User 1 closes app', async () => { - console.log('User 1 closes app') + logger.info('User 1 closes app') await users.user1.app?.close() }) // Delete third channel while guest is absent it('Channel deletion - Owner deletes third channel', async () => { - console.log('TEST 2.5') + logger.info('TEST 2.5') await new Promise(resolve => setTimeout(() => resolve(), 10000)) const isThirdChannel = await thirdChannelOwner.messageInput.isDisplayed() expect(isThirdChannel).toBeTruthy() @@ -368,7 +368,7 @@ describe('Multiple Clients', () => { // Delete general channel while guest is absent it('Channel deletion - Owner recreates general channel', async () => { - console.log('TEST 3') + logger.info('TEST 3') await new Promise(resolve => setTimeout(() => resolve(), 10000)) const isGeneralChannel = await generalChannelOwner.messageInput.isDisplayed() expect(isGeneralChannel).toBeTruthy() @@ -379,14 +379,14 @@ describe('Multiple Clients', () => { }) it('User 1 re-opens app', async () => { - console.log('User 1 re-opens app') + logger.info('User 1 re-opens app') await users.user1.app?.open() await new Promise(resolve => setTimeout(() => resolve(), 30000)) }) // Check correct channels replication it('Channel deletion - User sees information about recreation general channel and see correct amount of messages (#2334)', async () => { - console.log('TESTING - ISSUE 2334') + logger.info('TESTING - ISSUE 2334') generalChannelUser1 = new Channel(users.user1.app.driver, 'general') await generalChannelUser1.element.isDisplayed() console.timeEnd(`[${users.user1.app.name}] '${users.user2.username}' joining community time`) @@ -411,7 +411,7 @@ describe('Multiple Clients', () => { }) it('Leave community', async () => { - console.log('TEST 2') + logger.info('TEST 2') const settingsModal = await new Sidebar(users.user1.app.driver).openSettings() const isSettingsModal = await settingsModal.element.isDisplayed() expect(isSettingsModal).toBeTruthy() @@ -420,7 +420,7 @@ describe('Multiple Clients', () => { }) it('Leave community - Guest re-join to community successfully', async () => { - console.log('TEST 4') + logger.info('TEST 4') const debugModal = new DebugModeModal(users.user1.app.driver) await debugModal.close() const joinCommunityModal = new JoinCommunityModal(users.user1.app.driver) @@ -430,7 +430,7 @@ describe('Multiple Clients', () => { await joinCommunityModal.submit() }) it('Leave community - Guest registers new username', async () => { - console.log('TEST 5') + logger.info('TEST 5') const registerModal2 = new RegisterUsernameModal(users.user1.app.driver) const isRegisterModal2 = await registerModal2.element.isDisplayed() expect(isRegisterModal2).toBeTruthy() @@ -441,7 +441,7 @@ describe('Multiple Clients', () => { // Check correct channels replication it('Channel deletion - User sees information about recreation general channel and see correct amount of messages', async () => { - console.log('TEST 6') + logger.info('TEST 6') generalChannelUser1 = new Channel(users.user1.app.driver, 'general') await generalChannelUser1.element.isDisplayed() console.timeEnd(`[${users.user1.app.name}] '${users.user2.username}' joining community time`) @@ -462,7 +462,7 @@ describe('Multiple Clients', () => { }) it('Leave community - Guest sends a message after rejoining community as a new user', async () => { - console.log('TEST 7') + logger.info('TEST 7') generalChannelUser1 = new Channel(users.user1.app.driver, 'general') await generalChannelUser1.element.isDisplayed() const isMessageInput2 = await generalChannelUser1.messageInput.isDisplayed() @@ -475,7 +475,7 @@ describe('Multiple Clients', () => { await generalChannelUser1.sendMessage(users.user2.messages[0]) }) it('Leave community - Sent message is visible in a channel', async () => { - console.log('TEST 8') + logger.info('TEST 8') await generalChannelUser1.waitForUserMessage(users.user2.username, users.user2.messages[0]) }) it('Owner closes app', async () => { @@ -484,7 +484,7 @@ describe('Multiple Clients', () => { }) it('Guest closes app', async () => { - console.log('TEST 9') + logger.info('TEST 9') await users.user1.app?.close() }) @@ -494,14 +494,14 @@ describe('Multiple Clients', () => { }) it('Guest closes app - Owner sends another message after guest left the app', async () => { - console.log('TEST 10') + logger.info('TEST 10') generalChannelOwner = new Channel(users.owner.app.driver, 'general') const isMessageInput = await generalChannelOwner.messageInput.isDisplayed() expect(isMessageInput).toBeTruthy() await generalChannelOwner.sendMessage(users.owner.messages[2]) }) it('Guest closes app - Check if message is visible for owner', async () => { - console.log('TEST 11') + logger.info('TEST 11') await generalChannelOwner.waitForUserMessage(users.owner.username, users.owner.messages[2]) }) } diff --git a/packages/e2e-tests/src/tests/oneClient.test.ts b/packages/e2e-tests/src/tests/oneClient.test.ts index 1dab965c39..564bb105b5 100644 --- a/packages/e2e-tests/src/tests/oneClient.test.ts +++ b/packages/e2e-tests/src/tests/oneClient.test.ts @@ -9,6 +9,9 @@ import { import getPort from 'get-port' import { fork } from 'child_process' import path from 'path' +import { createLogger } from '../logger' + +const logger = createLogger('oneClient') jest.setTimeout(450000) describe('One Client', () => { @@ -60,11 +63,11 @@ describe('One Client', () => { const isRegisterModal = await registerModal.element.isDisplayed() expect(isRegisterModal).toBeTruthy() - console.log('Registration - vefore typeUsername') + logger.info('Registration - vefore typeUsername') await registerModal.typeUsername('testuser') - console.log('Registration - before submit') + logger.info('Registration - before submit') await registerModal.submit() - console.log('Registration - after submit') + logger.info('Registration - after submit') }) it.skip('User waits for the modal JoiningLoadingPanel to disappear', async () => { @@ -97,7 +100,7 @@ describe('One Client', () => { 'desktop', ] const backendBundlePath = path.normalize(require.resolve('backend-bundle')) - console.log('Spawning backend', backendBundlePath, 'with argvs:', forkArgvs) + logger.info('Spawning backend', backendBundlePath, 'with argvs:', forkArgvs) fork(backendBundlePath, forkArgvs) await app.close({ forceSaveState: true }) }) diff --git a/packages/e2e-tests/src/tests/userProfile.test.ts b/packages/e2e-tests/src/tests/userProfile.test.ts index eeaa00cb9c..04f1cec641 100644 --- a/packages/e2e-tests/src/tests/userProfile.test.ts +++ b/packages/e2e-tests/src/tests/userProfile.test.ts @@ -9,13 +9,13 @@ import { Sidebar, UserProfileContextMenu, } from '../selectors' -import logger from '../logger' +import { createLogger } from '../logger' import { EXPECTED_IMG_SRC_GIF, EXPECTED_IMG_SRC_JPEG, EXPECTED_IMG_SRC_PNG } from '../profilePhoto.const' import { sleep } from '../utils' import { BACK_ARROW_DATA_TESTID } from '../enums' import { UserTestData } from '../types' -const log = logger('userProfile') +const logger = createLogger('userProfile') jest.setTimeout(900000) @@ -96,7 +96,7 @@ describe('User Profile Feature', () => { it('Owner updates their profile photo with JPEG', async () => { try { - console.log('JPEG') + logger.info('JPEG') const menu = new UserProfileContextMenu(users.owner.app.driver) await menu.openMenu() await menu.openEditProfileMenu() @@ -108,14 +108,14 @@ describe('User Profile Feature', () => { await menu.back(BACK_ARROW_DATA_TESTID.EDIT_PROFILE) await menu.back(BACK_ARROW_DATA_TESTID.PROFILE) } catch (e) { - console.error('Failed to set JPEG profile photo', e) + logger.error('Failed to set JPEG profile photo', e) throw e } }) it('Owner updates their profile photo with GIF', async () => { try { - console.log('GIF') + logger.info('GIF') const menu = new UserProfileContextMenu(users.owner.app.driver) await menu.openMenu() await menu.openEditProfileMenu() @@ -127,14 +127,14 @@ describe('User Profile Feature', () => { await menu.back(BACK_ARROW_DATA_TESTID.EDIT_PROFILE) await menu.back(BACK_ARROW_DATA_TESTID.PROFILE) } catch (e) { - console.error('Failed to set GIF profile photo', e) + logger.error('Failed to set GIF profile photo', e) throw e } }) it('Owner updates their profile photo with PNG', async () => { try { - console.log('PNG') + logger.info('PNG') const menu = new UserProfileContextMenu(users.owner.app.driver) await menu.openMenu() await menu.openEditProfileMenu() @@ -146,7 +146,7 @@ describe('User Profile Feature', () => { await menu.back(BACK_ARROW_DATA_TESTID.EDIT_PROFILE) await menu.back(BACK_ARROW_DATA_TESTID.PROFILE) } catch (e) { - console.error('Failed to set PNG profile photo', e) + logger.error('Failed to set PNG profile photo', e) throw e } }) @@ -163,7 +163,7 @@ describe('User Profile Feature', () => { invitationCode = await invitationCodeElement.getText() await sleep(2000) expect(invitationCode).not.toBeUndefined() - log('Received invitation code:', invitationCode) + logger.info('Received invitation code:', invitationCode) await settingsModal.close() }) diff --git a/packages/e2e-tests/src/utils.ts b/packages/e2e-tests/src/utils.ts index c167c02a3c..35462fc17f 100644 --- a/packages/e2e-tests/src/utils.ts +++ b/packages/e2e-tests/src/utils.ts @@ -6,6 +6,9 @@ import path from 'path' import fs from 'fs' import { DESKTOP_DATA_DIR, getAppDataPath } from '@quiet/common' import { config } from 'dotenv' +import { createLogger } from './logger' + +const logger = createLogger('utils') export const BACKWARD_COMPATIBILITY_BASE_VERSION = '2.0.1' // Pre-latest production version const appImagesPath = `${__dirname}/../Quiet` @@ -49,14 +52,14 @@ export class BuildSetup { // Note: .env file is being used locally right now, mainly by script e2e:linux:build static getEnvFileName() { const { parsed, error } = config() - console.log('Dotenv config', { parsed, error }) + logger.info('Dotenv config', { parsed, error }) return process.env.FILE_NAME } private getBinaryLocation() { switch (process.platform) { case 'linux': - console.log('filename', this.fileName) + logger.info('filename', this.fileName) return `${__dirname}/../Quiet/${this.fileName ? this.fileName : BuildSetup.getEnvFileName()}` case 'win32': return `${process.env.LOCALAPPDATA}\\Programs\\@quietdesktop\\Quiet.exe` @@ -70,7 +73,7 @@ export class BuildSetup { private getMacBinaryDir(): string { let basePath = '/Applications' if (process.env.IS_LOCAL === 'true') { - console.warn('RUNNING ON LOCAL BINARY') + logger.warn('RUNNING ON LOCAL BINARY') const distDirByArch = process.arch === 'arm64' ? 'mac-arm64' : 'mac' basePath = `${__dirname}/../../desktop/dist/${distDirByArch}` } @@ -113,7 +116,7 @@ export class BuildSetup { DATA_DIR: this.dataDir, } if (process.platform === 'win32') { - console.log('!WINDOWS!') + logger.info('!WINDOWS!') this.child = spawn(`cd node_modules/.bin & chromedriver.cmd --port=${this.port} --verbose`, [], { shell: true, env: Object.assign(process.env, env), @@ -133,29 +136,29 @@ export class BuildSetup { ) this.child.on('error', () => { - console.error('ERROR') + logger.error('ERROR') this.killNine() }) this.child.on('exit', () => { - console.log('EXIT') + logger.info('EXIT') this.killNine() }) this.child.on('close', () => { - console.log('CLOSE') + logger.info('CLOSE') this.killNine() }) this.child.on('message', data => { - console.log('message', data) + logger.info('message', data) }) this.child.on('error', data => { - console.error('error', data) + logger.error('error', data) }) this.child.stdout.on('data', data => { - console.log(`stdout:\n${data}`) + logger.info(`stdout:\n${data}`) }) this.child.stderr.on('data', data => { @@ -165,11 +168,11 @@ export class BuildSetup { for (const l of trashLogs) { if (dataString.includes(l)) return } - console.log(`[${this.dataDir}]: ${dataString}`) + logger.info(`[${this.dataDir}]: ${dataString}`) }) this.child.stdin.on('data', data => { - console.log(`stdin: ${data}`) + logger.info(`stdin: ${data}`) }) } @@ -178,14 +181,14 @@ export class BuildSetup { return await new Promise(resolve => { exec(cmd, (error, stdout, stderr) => { if (error) { - console.warn(error) + logger.warn(error) } resolve(stdout || stderr) }) }) } const torPid = await execAsync('lsof -t -c tor') - console.log({ torPid }) + logger.info({ torPid }) return torPid } @@ -204,7 +207,7 @@ export class BuildSetup { .forBrowser(Browser.CHROME) .build() } catch (e) { - console.log(e) + logger.info(e) } } @@ -220,7 +223,7 @@ export class BuildSetup { } public async killChromeDriver() { - console.log(`Killing driver (DATA_DIR=${this.dataDir})`) + logger.info(`Killing driver (DATA_DIR=${this.dataDir})`) this.child?.kill() await new Promise(resolve => setTimeout(() => { @@ -230,20 +233,20 @@ export class BuildSetup { } public async closeDriver() { - console.log(`Closing driver (DATA_DIR=${this.dataDir})`) + logger.info(`Closing driver (DATA_DIR=${this.dataDir})`) await this.driver?.close() } public clearDataDir(force: boolean = false) { if (process.env.IS_CI === 'true' && !force) { - console.warn('Not deleting data directory because we are running in CI') + logger.warn('Not deleting data directory because we are running in CI') return } - console.log(`Deleting data directory at ${this.dataDirPath}`) + logger.info(`Deleting data directory at ${this.dataDirPath}`) try { fs.rmdirSync(this.dataDirPath, { recursive: true }) } catch (e) { - console.error(`Could not delete ${this.dataDirPath}. Reason: ${e.message}`) + logger.error(`Could not delete ${this.dataDirPath}. Reason: ${e.message}`) } } @@ -264,13 +267,13 @@ export class BuildSetup { const command = byPlatform[process.platform as SupportedPlatformDesktop] const appBackendProcess = execSync(command).toString('utf8').trim() - console.log('Backend process info', appBackendProcess) + logger.info('Backend process info', appBackendProcess) let args = appBackendProcess.split(' ') if (process.platform === 'win32') { args = args.filter(item => item.trim() !== '') args = args.map(item => item.trim()) } - console.log('Args:', args) + logger.info('Args:', args) if (args.length >= 5) { if (process.platform === 'win32') { dataDirPath = args[5] @@ -280,7 +283,7 @@ export class BuildSetup { resourcesPath = args[8] } } - console.log('Extracted dataDirPath:', dataDirPath, 'resourcesPath:', resourcesPath) + logger.info('Extracted dataDirPath:', dataDirPath, 'resourcesPath:', resourcesPath) return { dataDirPath, resourcesPath, @@ -298,17 +301,17 @@ export const downloadInstaller = (version = BACKWARD_COMPATIBILITY_BASE_VERSION) const appImage = quietAppImage(version) const appImageTargetPath = path.join(appImagesPath, appImage) if (fs.existsSync(appImageTargetPath)) { - console.log(`${appImage} already exists. Skipping download.`) + logger.info(`${appImage} already exists. Skipping download.`) return appImage } const downloadUrl = `https://github.com/TryQuiet/quiet/releases/download/%40quiet%2Fdesktop%40${version}/${appImage}` - console.log(`Downloading Quiet version: ${version} from ${downloadUrl}`) + logger.info(`Downloading Quiet version: ${version} from ${downloadUrl}`) // With newer curl: execSync(`curl -LO --output-dir ${appImagesPath} ${downloadUrl}`) execSync(`curl -LO ${downloadUrl}`) const appImageDownloadPath = path.join(process.cwd(), appImage) - console.log(`Downloaded to ${appImageDownloadPath}`) + logger.info(`Downloaded to ${appImageDownloadPath}`) fs.renameSync(appImageDownloadPath, appImageTargetPath) - console.log('Moved to', appImageTargetPath) + logger.info('Moved to', appImageTargetPath) // Make it executable fs.chmodSync(appImageTargetPath, 0o755) return appImage @@ -322,12 +325,12 @@ export const copyInstallerFile = (file: string) => { const copiedFileName = `${parsedBase.name}-copy${parsedBase.ext}` const copiedFilePath = path.join(appImagesPath, copiedFileName) if (fs.existsSync(copiedFilePath)) { - console.log(`${copiedFileName} already exists. Skipping copy.`) + logger.info(`${copiedFileName} already exists. Skipping copy.`) return copiedFileName } fs.copyFileSync(base, copiedFilePath) - console.log(`Copied ${base} to ${copiedFilePath}`) + logger.info(`Copied ${base} to ${copiedFilePath}`) return copiedFileName } diff --git a/packages/identity/src/createUserCert.ts b/packages/identity/src/createUserCert.ts index c8cb455bcf..103c436936 100644 --- a/packages/identity/src/createUserCert.ts +++ b/packages/identity/src/createUserCert.ts @@ -12,6 +12,9 @@ import { GeneralNames, type Attribute, } from 'pkijs' +import { createLogger } from './logger' + +const logger = createLogger('createUserCert') export interface UserCert { // Todo: move types to separate file @@ -92,7 +95,7 @@ async function generateUserCertificate({ ], }) } catch (err) { - console.error(err) + logger.error(err) throw new Error('Cannot get certificate request extension') } diff --git a/packages/identity/src/logger.ts b/packages/identity/src/logger.ts index 88ad4293d1..32132aeb95 100644 --- a/packages/identity/src/logger.ts +++ b/packages/identity/src/logger.ts @@ -1,3 +1,3 @@ -import logger from '@quiet/logger' +import { createQuietLogger } from '@quiet/logger' -export default logger('identity') +export const createLogger = createQuietLogger('identity') diff --git a/packages/integration-tests/src/bot/bot.ts b/packages/integration-tests/src/bot/bot.ts index e2a4cb3c6e..015933ed67 100644 --- a/packages/integration-tests/src/bot/bot.ts +++ b/packages/integration-tests/src/bot/bot.ts @@ -8,8 +8,8 @@ import { registerUsername, switchChannel, sendMessage } from '../testUtils/actio import { waitForExpect } from '../testUtils/waitForExpect' import { assertReceivedChannel } from '../testUtils/assertions' import { CryptoEngine, setEngine } from 'pkijs' -import logger from '../logger' -const log = logger('bot') +import { createLogger } from '../logger' +const logger = createLogger('bot') // eslint-disable-next-line const { Crypto } = require('@peculiar/webcrypto') @@ -67,11 +67,11 @@ let typingLatency: number if (intensity) { typingLatency = 60_000 / intensity // Typing latency per message (in milliseconds) - log(`Typing latency is ${typingLatency}`) + logger.info(`Typing latency is ${typingLatency}`) } const createBots = async () => { - log(`Creating ${activeUsers} bots`) + logger.info(`Creating ${activeUsers} bots`) for (let i = 0; i < activeUsers; i++) { const username = `bot_${(Math.random() + 1).toString(36).substring(5)}` apps.set(username, await createApp()) @@ -79,7 +79,7 @@ const createBots = async () => { } const createSilentBots = async () => { - log(`Creating ${silentUsers} silent bots`) + logger.info(`Creating ${silentUsers} silent bots`) for (let i = 0; i < silentUsers; i++) { const username = `silent_bot_${(Math.random() + 1).toString(36).substring(5)}` apps.set(username, await createApp()) @@ -95,7 +95,7 @@ const registerBots = async () => { registrarPort: null, store, } - log(`Registering ${username}`) + logger.info(`Registering ${username}`) await registerUsername(payload) const communityId = store.getState().Communities.communities.ids[0] @@ -123,7 +123,7 @@ const sendMessages = async () => { }) if (_activeUsers.size > 0) { - log(`Start sending ${endless ? 'endless' : messages} messages`) + logger.info(`Start sending ${endless ? 'endless' : messages} messages`) const messagesPerUser = Math.floor(messages / _activeUsers.size) @@ -141,7 +141,7 @@ const sendMessages = async () => { if (messagesLeft <= 0) { await sendMessageWithLatency(currentUsername, apps.get(currentUsername).store, 'Bye!') messagesToSend.delete(currentUsername) - log(`User ${currentUsername} is finished with sending messages`) + logger.info(`User ${currentUsername} is finished with sending messages`) continue } @@ -154,13 +154,13 @@ const sendMessages = async () => { } } - log('Bot starts waiting 10_000ms for remaining promises to resolve') + logger.info('Bot starts waiting 10_000ms for remaining promises to resolve') await sleep(10_000) } const sendMessageWithLatency = async (username: string, store: TestStore, message: string) => { const latency = typingLatency || getRandomInt(300, 550) - log(`${username} is waiting ${latency}ms to send a message`) + logger.info(`${username} is waiting ${latency}ms to send a message`) await sleep(latency) await sendMessage({ message, @@ -171,22 +171,22 @@ const sendMessageWithLatency = async (username: string, store: TestStore, messag const closeAll = async (force = false) => { if (!force && standby) { - log(`Waiting ${standby}ms before peers goes offline`) + logger.info(`Waiting ${standby}ms before peers goes offline`) await sleep(standby) } for (const [username, app] of apps) { - log(`Closing services for ${username}`) + logger.info(`Closing services for ${username}`) await app.manager.closeAllServices() } } const run = async () => { process.on('unhandledRejection', async error => { - console.error(error) + logger.error(error) await closeAll(true) }) process.on('SIGINT', async () => { - log('\nGracefully shutting down from SIGINT (Ctrl-C)') + logger.info('\nGracefully shutting down from SIGINT (Ctrl-C)') await closeAll(true) }) await createBots() @@ -198,6 +198,6 @@ const run = async () => { run() .then(() => { - console.log('FINISHED') + logger.info('FINISHED') }) - .catch(e => console.error(e)) + .catch(e => logger.error(e)) diff --git a/packages/integration-tests/src/integrationTests/appActions.ts b/packages/integration-tests/src/integrationTests/appActions.ts index 1404683cb1..0dcfa56a87 100644 --- a/packages/integration-tests/src/integrationTests/appActions.ts +++ b/packages/integration-tests/src/integrationTests/appActions.ts @@ -17,9 +17,9 @@ import { import { MAIN_CHANNEL } from '../testUtils/constants' import { AsyncReturnType } from '../types/AsyncReturnType.interface' import { createApp } from '../utils' -import logger from '../logger' +import { createLogger } from '../logger' -const log = logger('actions') +const logger = createLogger('actions') const App: AsyncReturnType = null type Store = typeof App.store @@ -110,14 +110,14 @@ export async function createCommunity({ userName, store }: CreateCommunity) { await waitForExpect(() => { expect(store.getState().Communities.communities.entities[communityId].onionAddress).toBeTruthy() }, timeout) - log(store.getState().Communities.communities.entities[communityId].onionAddress) + logger.info(store.getState().Communities.communities.entities[communityId].onionAddress) await waitForExpect(() => { expect(store.getState().Users.certificates.ids).toHaveLength(1) }, timeout) await waitForExpect(() => { expect(store.getState().Network.initializedCommunities[communityId]).toBeTruthy() }, timeout) - log('initializedCommunity', store.getState().Network.initializedCommunities[communityId]) + logger.info('initializedCommunity', store.getState().Network.initializedCommunities[communityId]) } export async function registerUsername(payload: Register) { @@ -202,7 +202,7 @@ export async function joinCommunity(payload: JoinCommunity) { export async function sendMessage(payload: SendMessage): Promise { const { message, channelName, store } = payload - log(message, 'sendMessage') + logger.info(message, 'sendMessage') const communityId = store.getState().Communities.communities.ids[0] if (channelName) { @@ -233,7 +233,7 @@ export async function sendMessage(payload: SendMessage): Promise export async function sendImage(payload: SendImage) { const { file, store } = payload - log(JSON.stringify(payload), 'sendImage') + logger.info(JSON.stringify(payload), 'sendImage') store.dispatch(files.actions.uploadFile(file)) diff --git a/packages/integration-tests/src/integrationTests/assertions.ts b/packages/integration-tests/src/integrationTests/assertions.ts index bd36828759..5f70d9d899 100644 --- a/packages/integration-tests/src/integrationTests/assertions.ts +++ b/packages/integration-tests/src/integrationTests/assertions.ts @@ -2,9 +2,9 @@ import { ErrorPayload, publicChannels, TestStore, messages, MessageType } from ' import waitForExpect from 'wait-for-expect' import { MAIN_CHANNEL } from '../testUtils/constants' import { sleep } from '../utils' -import logger from '../logger' +import { createLogger } from '../logger' -const log = logger('assertions') +const logger = createLogger('assertions') export async function assertReceivedCertificates( userName: string, @@ -12,13 +12,13 @@ export async function assertReceivedCertificates( maxTime = 60000, store: TestStore ) { - log(`User ${userName} starts waiting ${maxTime}ms for certificates`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for certificates`) await waitForExpect(() => { expect(store.getState().Users.certificates.ids).toHaveLength(expectedCount) }, maxTime) - log(`User ${userName} received ${store.getState().Users.certificates.ids.length} certificates`) + logger.info(`User ${userName} received ${store.getState().Users.certificates.ids.length} certificates`) } export async function assertReceivedChannelsAndSubscribe( @@ -27,7 +27,7 @@ export async function assertReceivedChannelsAndSubscribe( maxTime = 60000, store: TestStore ) { - log(`User ${userName} starts waiting ${maxTime}ms for channels`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for channels`) await waitForExpect(() => { expect(store.getState().PublicChannels.channels.ids).toHaveLength(expectedCount) @@ -39,7 +39,7 @@ export async function assertReceivedChannelsAndSubscribe( }) ) - log(`User ${userName} received ${store.getState().PublicChannels.channels.ids.length} channels`) + logger.info(`User ${userName} received ${store.getState().PublicChannels.channels.ids.length} channels`) } export async function assertReceivedMessages( @@ -48,14 +48,14 @@ export async function assertReceivedMessages( maxTime = 60000, store: TestStore ) { - log(`User ${userName} starts waiting ${maxTime}ms for messages`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for messages`) await waitForExpect(() => { expect(store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.ids).toHaveLength( expectedCount ) }, maxTime) - log( + logger.info( `User ${userName} received ${ store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.ids.length } messages` @@ -68,7 +68,7 @@ export const assertReceivedMessagesAreValid = async ( maxTime = 60000, store: TestStore ) => { - log(`User ${userName} checks is messages are valid`) + logger.info(`User ${userName} checks is messages are valid`) const receivedMessages = Object.values( store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.entities @@ -89,7 +89,7 @@ export const assertReceivedMessagesAreValid = async ( } export async function assertReceivedImages(userName: string, expectedCount: number, maxTime = 60000, store: TestStore) { - log(`User ${userName} starts waiting ${maxTime}ms for image`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for image`) await waitForExpect(() => { expect( Object.values( @@ -97,7 +97,7 @@ export async function assertReceivedImages(userName: string, expectedCount: numb ).filter(message => message.type === MessageType.Image) ).toHaveLength(expectedCount) }, maxTime) - log( + logger.info( `User ${userName} received ${ Object.values( store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.entities @@ -112,7 +112,7 @@ export async function assertDownloadedImage( maxTime = 60000, store: TestStore ) { - log(`User ${userName} starts waiting ${maxTime}ms for downloading ${expectedImage}`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for downloading ${expectedImage}`) await waitForExpect(() => { const message = Object.values( store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.entities @@ -123,7 +123,7 @@ export async function assertDownloadedImage( expect(filename).toBe(expectedImage) }, maxTime) - log(`User ${userName} downloaded ${expectedImage}`) + logger.info(`User ${userName} downloaded ${expectedImage}`) } export const assertInitializedExistingCommunitiesAndRegistrars = async (store: TestStore) => { diff --git a/packages/integration-tests/src/integrationTests/sendFiles.test.ts b/packages/integration-tests/src/integrationTests/sendFiles.test.ts index fdbf8ee482..086979fea5 100644 --- a/packages/integration-tests/src/integrationTests/sendFiles.test.ts +++ b/packages/integration-tests/src/integrationTests/sendFiles.test.ts @@ -9,9 +9,9 @@ import { createCommunity, joinCommunity, getCommunityOwnerData, sendImage, SendI import { createApp, storePersistor } from '../utils' import { AsyncReturnType } from '../types/AsyncReturnType.interface' import { FileContent } from '@quiet/state-manager' -import logger from '../logger' +import { createLogger } from '../logger' -const log = logger('files') +const logger = createLogger('files') const crypto = new Crypto() @@ -65,7 +65,7 @@ describe('send message - users are online', () => { }) test('user sends image to general channel', async () => { - log(`Image ${JSON.stringify(image)}`) + logger.info(`Image ${JSON.stringify(image)}`) const payload: SendImage = { file: image, store: owner.store, diff --git a/packages/integration-tests/src/logger.ts b/packages/integration-tests/src/logger.ts index b5364bbecf..95bf498c30 100644 --- a/packages/integration-tests/src/logger.ts +++ b/packages/integration-tests/src/logger.ts @@ -1,3 +1,3 @@ -import logger from '@quiet/logger' +import { createQuietLogger } from '@quiet/logger' -export default logger('state-manager:test') +export const createLogger = createQuietLogger('state-manager:test') diff --git a/packages/integration-tests/src/testUtils/actions.ts b/packages/integration-tests/src/testUtils/actions.ts index 5a621c0c02..49ba9450cf 100644 --- a/packages/integration-tests/src/testUtils/actions.ts +++ b/packages/integration-tests/src/testUtils/actions.ts @@ -10,9 +10,9 @@ import { } from '@quiet/state-manager' import assert from 'assert' import { Register, SendImage, SendMessage } from '../integrationTests/appActions' -import logger from '../logger' +import { createLogger } from '../logger' import { waitForExpect } from './waitForExpect' -const log = logger('actions') +const logger = createLogger('actions') const timeout = 120_000 @@ -22,7 +22,7 @@ export async function registerUsername(payload: Register) { const createNetworkPayload: CreateNetworkPayload = { ownership: CommunityOwnership.User, } - log(`User ${userName} starts creating network`) + logger.info(`User ${userName} starts creating network`) store.dispatch(communities.actions.createNetwork(createNetworkPayload)) await waitForExpect(() => { @@ -41,7 +41,7 @@ export async function registerUsername(payload: Register) { assert.equal(store.getState().Identity.identities.entities[communityId].peerId.id.length, 46) }, timeout) - log(`User ${userName} starts registering username`) + logger.info(`User ${userName} starts registering username`) store.dispatch(identity.actions.registerUsername({ nickname: userName })) } @@ -81,14 +81,14 @@ export const createCommunity = async ({ username, communityName, store }): Promi await waitForExpect(() => { assert.ok(store.getState().Communities.communities.entities[communityId].onionAddress) }, timeout) - log(store.getState().Communities.communities.entities[communityId].onionAddress) + logger.info(store.getState().Communities.communities.entities[communityId].onionAddress) await waitForExpect(() => { assert.strictEqual(store.getState().Users.certificates.ids.length, 1) }, timeout) await waitForExpect(() => { assert.ok(store.getState().Connection.initializedCommunities[communityId]) }, timeout) - log('initializedCommunity', store.getState().Connection.initializedCommunities[communityId]) + logger.info('initializedCommunity', store.getState().Connection.initializedCommunities[communityId]) return store.getState().Communities.communities.entities[communityId].onionAddress } @@ -96,7 +96,7 @@ export const createCommunity = async ({ username, communityName, store }): Promi export async function sendMessage(payload: SendMessage): Promise { const { message, channelName, store } = payload - log(message, 'sendMessage') + logger.info(message, 'sendMessage') store.dispatch(messages.actions.sendMessage({ message })) @@ -118,7 +118,7 @@ export async function sendMessage(payload: SendMessage): Promise export async function sendImage(payload: SendImage) { const { file, store } = payload - log(file.path, 'sendImage') + logger.info(file.path, 'sendImage') store.dispatch(files.actions.uploadFile(file)) diff --git a/packages/integration-tests/src/testUtils/assertions.ts b/packages/integration-tests/src/testUtils/assertions.ts index 84b97ac394..55b5b96d3d 100644 --- a/packages/integration-tests/src/testUtils/assertions.ts +++ b/packages/integration-tests/src/testUtils/assertions.ts @@ -1,9 +1,9 @@ import { publicChannels, Store } from '@quiet/state-manager' import assert from 'assert' -import logger from '../logger' +import { createLogger } from '../logger' import { MAIN_CHANNEL } from './constants' import { waitForExpect } from './waitForExpect' -const log = logger('utils') +const logger = createLogger('utils') const timeout = 120_000 @@ -25,13 +25,13 @@ export async function assertReceivedChannel( maxTime: number = timeout, store: Store ) { - log(`User ${userName} starts waiting ${maxTime}ms for channels`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for channels`) await waitForExpect(() => { assertNotEmpty(store.getState().PublicChannels) assertContains(channelName, store.getState().PublicChannels.channels.ids) }, maxTime) - log(`User ${userName} replicated '${channelName}'`) + logger.info(`User ${userName} replicated '${channelName}'`) store.dispatch( publicChannels.actions.setCurrentChannel({ @@ -39,7 +39,7 @@ export async function assertReceivedChannel( }) ) - log(`User ${userName} received ${store.getState().PublicChannels.channels.ids.length} channels`) + logger.info(`User ${userName} received ${store.getState().PublicChannels.channels.ids.length} channels`) } export async function assertReceivedMessages( @@ -48,7 +48,7 @@ export async function assertReceivedMessages( maxTime: number = timeout, store: Store ) { - log(`User ${userName} starts waiting ${maxTime}ms for messages`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for messages`) await waitForExpect(() => { assert.strictEqual( @@ -57,7 +57,7 @@ export async function assertReceivedMessages( ) }, maxTime) - log( + logger.info( `User ${userName} received ${ store.getState().Messages.publicChannelsMessagesBase.entities[MAIN_CHANNEL].messages.ids.length } messages` @@ -97,11 +97,11 @@ export const assertReceivedCertificates = async ( maxTime: number = timeout, store: Store ) => { - log(`User ${userName} starts waiting ${maxTime}ms for certificates`) + logger.info(`User ${userName} starts waiting ${maxTime}ms for certificates`) await waitForExpect(() => { assert.strictEqual(store.getState().Users.certificates.ids.length, expectedCount) }, maxTime) - log(`User ${userName} received ${store.getState().Users.certificates.ids.length} certificates`) + logger.info(`User ${userName} received ${store.getState().Users.certificates.ids.length} certificates`) } diff --git a/packages/integration-tests/src/utils.ts b/packages/integration-tests/src/utils.ts index 5af12e3c6b..4f885497f2 100644 --- a/packages/integration-tests/src/utils.ts +++ b/packages/integration-tests/src/utils.ts @@ -9,10 +9,10 @@ import path from 'path' import assert from 'assert' import getPort from 'get-port' import tmp from 'tmp' -import logger from './logger' +import { createLogger } from './logger' import { Saga, Task } from '@redux-saga/types' -const log = logger('utils') +const logger = createLogger('utils') export const createTmpDir = (prefix: string) => { return tmp.dirSync({ mode: 0o750, prefix, unsafeCleanup: true }) @@ -25,10 +25,10 @@ export const createPath = (dirName: string) => { const connectToDataport = (url: string, name: string): Socket => { const socket = io(url) socket.on('connect', async () => { - log(`websocket connection is ready for app ${name}`) + logger.info(`websocket connection is ready for app ${name}`) }) socket.on('disconnect', () => { - log(`socket disconnected for app ${name}`) + logger.info(`socket disconnected for app ${name}`) socket.close() }) return socket @@ -49,7 +49,7 @@ export const createApp = async ( * configure redux store */ const appName = (Math.random() + 1).toString(36).substring(7) - log(`Creating test app for ${appName}`) + logger.info(`Creating test app for ${appName}`) const dataServerPort1 = await getPort() const { store, runSaga } = prepareStore(mockedState) @@ -96,7 +96,7 @@ export const createAppWithoutTor = async ( * configure redux store */ const appName = (Math.random() + 1).toString(36).substring(7) - log(`Creating test app for ${appName}`) + logger.info(`Creating test app for ${appName}`) const dataServerPort1 = await getPort() const server1 = new backend.DataServer(dataServerPort1) await server1.listen() diff --git a/packages/logger/src/index.ts b/packages/logger/src/index.ts index 04ae43ad38..9a19ca7f6f 100644 --- a/packages/logger/src/index.ts +++ b/packages/logger/src/index.ts @@ -32,21 +32,7 @@ colors.theme({ object_error: colors.red, }) -export type Logger = debug.Debugger & { - error: debug.Debugger -} - -export const consoleLogger = - (packageName: string) => - (module: string): Logger => { - debug('quiet')('Initializing debug logger') - const logger = Object.assign(debug(`${packageName}:${module}`), { - error: debug(`${packageName}:${module}:err`), - }) - return logger - } - -export const nodeConsoleLogger = Console instanceof Function ? new Console(process.stdout, process.stderr) : console +const nodeConsoleLogger = Console instanceof Function ? new Console(process.stdout, process.stderr) : console export class QuietLogger { private isDebug: boolean @@ -115,7 +101,7 @@ export class QuietLogger { } } -export const electronLogger = +const electronLogger = (packageName: string, parallelConsoleLog: boolean = false) => (module: string): QuietLogger => { const name = `${packageName}:${module}` @@ -123,15 +109,9 @@ export const electronLogger = return new QuietLogger(name, parallelConsoleLog) } -export const logger = (packageName: string): ((arg: string) => Logger) => { - return consoleLogger(packageName) -} - export const createQuietLogger = ( packageName: string, parallelConsoleLog: boolean = false ): ((arg: string) => QuietLogger) => { return electronLogger(packageName, parallelConsoleLog) } - -export default logger