From 3a8db0795a490e6e0dfdd39f3216d1cd3ab5f3ef Mon Sep 17 00:00:00 2001 From: lukasIO Date: Tue, 21 Apr 2026 15:51:22 +0200 Subject: [PATCH] chore: replace explicit logContext passing with bound version, add info logs --- src/api/SignalClient.ts | 50 +++--- src/room/RTCEngine.ts | 93 +++++------ src/room/Room.ts | 88 ++++------ src/room/participant/LocalParticipant.ts | 197 ++++++----------------- src/room/participant/Participant.ts | 5 +- 5 files changed, 146 insertions(+), 287 deletions(-) diff --git a/src/api/SignalClient.ts b/src/api/SignalClient.ts index b8768fd71e..a4b15e16c9 100644 --- a/src/api/SignalClient.ts +++ b/src/api/SignalClient.ts @@ -247,8 +247,8 @@ export class SignalClient { private useV0SignalPath = false; constructor(useJSON: boolean = false, loggerOptions: LoggerOptions = {}) { - this.log = getLogger(loggerOptions.loggerName ?? LoggerNames.Signal); this.loggerContextCb = loggerOptions.loggerContextCb; + this.log = getLogger(loggerOptions.loggerName ?? LoggerNames.Signal, () => this.logContext); this.useJSON = useJSON; this.requestQueue = new AsyncQueue(); this.queuedRequests = []; @@ -284,10 +284,7 @@ export class SignalClient { reason?: ReconnectReason, ): Promise { if (!this.options) { - this.log.warn( - 'attempted to reconnect without signal options being set, ignoring', - this.logContext, - ); + this.log.warn('attempted to reconnect without signal options being set, ignoring'); return; } this.state = SignalConnectionState.RECONNECTING; @@ -377,10 +374,9 @@ export class SignalClient { if (redactedUrl.searchParams.has('access_token')) { redactedUrl.searchParams.set('access_token', ''); } - this.log.debug(`connecting to ${redactedUrl}`, { + this.log.info(`signal connecting to ${redactedUrl}`, { reconnect: opts.reconnect, reconnectReason: opts.reconnectReason, - ...this.logContext, }); if (this.ws) { await this.close(false); @@ -399,7 +395,6 @@ export class SignalClient { } if (closeInfo.closeCode !== 1000) { this.log.warn(`websocket closed`, { - ...this.logContext, reason: closeInfo.reason, code: closeInfo.closeCode, wasClean: closeInfo.closeCode === 1000, @@ -466,7 +461,6 @@ export class SignalClient { if (this.pingTimeoutDuration && this.pingTimeoutDuration > 0) { this.log.debug('ping config', { - ...this.logContext, timeout: this.pingTimeoutDuration, interval: this.pingIntervalDuration, }); @@ -555,7 +549,7 @@ export class SignalClient { await Promise.race([closePromise, sleep(MAX_WS_CLOSE_TIME)]); } } catch (e) { - this.log.debug('websocket error while closing', { ...this.logContext, error: e }); + this.log.debug('websocket error while closing', { error: e }); } finally { if (updateState) { this.state = SignalConnectionState.DISCONNECTED; @@ -566,7 +560,7 @@ export class SignalClient { // initial offer after joining sendOffer(offer: RTCSessionDescriptionInit, offerId: number) { - this.log.debug('sending offer', { ...this.logContext, offerSdp: offer.sdp }); + this.log.debug('sending offer', { offerSdp: offer.sdp }); this.sendRequest({ case: 'offer', value: toProtoSessionDescription(offer, offerId), @@ -575,7 +569,7 @@ export class SignalClient { // answer a server-initiated offer sendAnswer(answer: RTCSessionDescriptionInit, offerId: number) { - this.log.debug('sending answer', { ...this.logContext, answerSdp: answer.sdp }); + this.log.debug('sending answer', { answerSdp: answer.sdp }); return this.sendRequest({ case: 'answer', value: toProtoSessionDescription(answer, offerId), @@ -583,7 +577,7 @@ export class SignalClient { } sendIceCandidate(candidate: RTCIceCandidateInit, target: SignalTarget) { - this.log.debug('sending ice candidate', { ...this.logContext, candidate }); + this.log.debug('sending ice candidate', { candidate }); return this.sendRequest({ case: 'trickle', value: new TrickleRequest({ @@ -768,10 +762,7 @@ export class SignalClient { return; } if (!this.streamWriter) { - this.log.error( - `cannot send signal request before connected, type: ${message?.case}`, - this.logContext, - ); + this.log.error(`cannot send signal request before connected, type: ${message?.case}`); return; } const req = new SignalRequest({ message }); @@ -783,14 +774,14 @@ export class SignalClient { await this.streamWriter.write(req.toBinary()); } } catch (e) { - this.log.error('error sending signal message', { ...this.logContext, error: e }); + this.log.error('error sending signal message', { error: e }); } } private handleSignalResponse(res: SignalResponse) { const msg = res.message; if (msg == undefined) { - this.log.debug('received unsupported message', this.logContext); + this.log.debug('received unsupported message'); return; } @@ -899,7 +890,7 @@ export class SignalClient { this.onDataTrackSubscriberHandles(msg.value); } } else { - this.log.debug('unsupported message', { ...this.logContext, msgCase: msg.case }); + this.log.debug('unsupported message', { msgCase: msg.case }); } if (!pingHandled) { @@ -920,14 +911,14 @@ export class SignalClient { if (this.state === SignalConnectionState.DISCONNECTED) return; const onCloseCallback = this.onClose; await this.close(undefined, reason); - this.log.debug(`websocket connection closed: ${reason}`, { ...this.logContext, reason }); + this.log.info(`websocket connection closed: ${reason}`, { reason }); if (onCloseCallback) { onCloseCallback(reason); } } private handleWSError(error: unknown) { - this.log.error('websocket error', { ...this.logContext, error }); + this.log.error('websocket error', { error }); } /** @@ -937,7 +928,7 @@ export class SignalClient { private resetPingTimeout() { this.clearPingTimeout(); if (!this.pingTimeoutDuration) { - this.log.warn('ping timeout duration not set', this.logContext); + this.log.warn('ping timeout duration not set'); return; } this.pingTimeout = CriticalTimers.setTimeout(() => { @@ -945,7 +936,6 @@ export class SignalClient { `ping timeout triggered. last pong received at: ${new Date( Date.now() - this.pingTimeoutDuration! * 1000, ).toUTCString()}`, - this.logContext, ); this.handleOnClose('ping timeout'); }, this.pingTimeoutDuration * 1000); @@ -964,17 +954,17 @@ export class SignalClient { this.clearPingInterval(); this.resetPingTimeout(); if (!this.pingIntervalDuration) { - this.log.warn('ping interval duration not set', this.logContext); + this.log.warn('ping interval duration not set'); return; } - this.log.debug('start ping interval', this.logContext); + this.log.debug('start ping interval'); this.pingInterval = CriticalTimers.setInterval(() => { this.sendPing(); }, this.pingIntervalDuration * 1000); } private clearPingInterval() { - this.log.debug('clearing ping interval', this.logContext); + this.log.debug('clearing ping interval'); this.clearPingTimeout(); if (this.pingInterval) { CriticalTimers.clearInterval(this.pingInterval); @@ -994,6 +984,7 @@ export class SignalClient { firstMessage?: SignalResponse, ) { this.state = SignalConnectionState.CONNECTED; + this.log.info('signal connected'); clearTimeout(timeoutHandle); this.startPingInterval(); this.startReadingLoop(connection.readable.getReader(), firstMessage); @@ -1031,10 +1022,7 @@ export class SignalClient { }; } else { // in reconnecting, any message received means signal reconnected and we still need to process it - this.log.debug( - 'declaring signal reconnected without reconnect response received', - this.logContext, - ); + this.log.debug('declaring signal reconnected without reconnect response received'); return { isValid: true, response: undefined, diff --git a/src/room/RTCEngine.ts b/src/room/RTCEngine.ts index 992f02a9c5..c428844cb5 100644 --- a/src/room/RTCEngine.ts +++ b/src/room/RTCEngine.ts @@ -227,6 +227,8 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit private log = log; + private reconnectLog = log; + private loggerOptions: LoggerOptions; private publisherConnectionPromise: Promise | undefined; @@ -254,7 +256,8 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit constructor(private options: InternalRoomOptions) { super(); - this.log = getLogger(options.loggerName ?? LoggerNames.Engine); + this.log = getLogger(options.loggerName ?? LoggerNames.Engine, () => this.logContext); + this.reconnectLog = getLogger(LoggerNames.Reconnection, () => this.logContext); this.loggerOptions = { loggerName: options.loggerName, loggerContextCb: () => this.logContext, @@ -364,7 +367,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit // create offer if (!this.subscriberPrimary || joinResponse.fastPublish) { this.negotiate().catch((err) => { - log.error(err, this.logContext); + this.log.error(err); }); } } @@ -377,15 +380,10 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (!serverInfo) { serverInfo = { version: joinResponse.serverVersion, region: joinResponse.serverRegion }; } - this.log.debug( + this.log.info( `connected to Livekit Server ${Object.entries(serverInfo) .map(([key, value]) => `${key}: ${value}`) .join(', ')}`, - { - room: joinResponse.room?.name, - roomSid: joinResponse.room?.sid, - identity: joinResponse.participant?.identity, - }, ); return { joinResponse, serverInfo }; @@ -394,7 +392,6 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (e.reason === ConnectionErrorReason.ServerUnreachable) { this.log.warn( `Couldn't connect to server, attempt ${this.joinAttempts} of ${this.maxJoinAttempts}`, - this.logContext, ); if (this.joinAttempts < this.maxJoinAttempts) { return this.join(url, token, opts, abortSignal, useV0Path); @@ -531,7 +528,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.pcManager!.removeTrack(sender); return true; } catch (e: unknown) { - this.log.warn('failed to remove track', { ...this.logContext, error: e }); + this.log.warn('failed to remove track', { error: e }); } return false; } @@ -588,7 +585,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.pcManager.onDataChannel = this.handleDataChannel; this.pcManager.onStateChange = async (connectionState, publisherState, subscriberState) => { - this.log.debug(`primary PC state changed ${connectionState}`, this.logContext); + this.log.debug(`primary PC state changed ${connectionState}`); if (['closed', 'disconnected', 'failed'].includes(publisherState)) { // reset publisher connection promise @@ -642,7 +639,6 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit return; } this.log.debug('received server answer', { - ...this.logContext, RTCSdpType: sd.type, sdp: sd.sdp, midToTrackId, @@ -656,7 +652,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (!this.pcManager) { return; } - this.log.debug('got ICE candidate from peer', { ...this.logContext, candidate, target }); + this.log.debug('got ICE candidate from peer', { candidate, target }); this.pcManager.addIceCandidate(candidate, target); }; @@ -675,15 +671,11 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.client.onLocalTrackPublished = (res: TrackPublishedResponse) => { this.log.debug('received trackPublishedResponse', { - ...this.logContext, cid: res.cid, track: res.track?.sid, }); if (!this.pendingTrackResolvers[res.cid]) { - this.log.error(`missing track resolver for ${res.cid}`, { - ...this.logContext, - cid: res.cid, - }); + this.log.error(`missing track resolver for ${res.cid}`, { cid: res.cid }); return; } const { resolve } = this.pendingTrackResolvers[res.cid]; @@ -742,9 +734,11 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit }; this.client.onLeave = (leave: LeaveRequest) => { - this.log.debug('client leave request', { ...this.logContext, reason: leave?.reason }); + this.log.info(`client leave request received (action=${leave?.action})`, { + reason: leave?.reason, + }); if (leave.regions) { - this.log.debug('updating regions', this.logContext); + this.log.debug('updating regions'); this.emit(EngineEvent.ServerRegionsReported, leave.regions); } switch (leave.action) { @@ -772,7 +766,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit const rtcConfig = { ...this.rtcConfig }; if (this.signalOpts?.e2eeEnabled) { - this.log.debug('E2EE - setting up transports with insertable streams', this.logContext); + this.log.debug('E2EE - setting up transports with insertable streams'); // this makes sure that no data is sent before the transforms are ready // @ts-ignore rtcConfig.encodedInsertableStreams = true; @@ -911,7 +905,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit } else { return; } - this.log.debug(`on data channel ${channel.id}, ${channel.label}`, this.logContext); + this.log.debug(`on data channel ${channel.id}, ${channel.label}`); channel.onmessage = handler; }; @@ -926,7 +920,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit } else if (message.data instanceof Blob) { buffer = await message.data.arrayBuffer(); } else { - this.log.error('unsupported data type', { ...this.logContext, data: message.data }); + this.log.error('unsupported data type', { data: message.data }); return; } const dp = DataPacket.fromBinary(new Uint8Array(buffer)); @@ -945,7 +939,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.emit(EngineEvent.ActiveSpeakersUpdate, dp.value.value.speakers); } else if (dp.value?.case === 'encryptedPacket') { if (!this.e2eeManager) { - this.log.error('Received encrypted packet but E2EE not set up', this.logContext); + this.log.error('Received encrypted packet but E2EE not set up'); return; } const decryptedData = await this.e2eeManager?.handleEncryptedData( @@ -985,7 +979,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit } else if (message.data instanceof Blob) { buffer = await message.data.arrayBuffer(); } else { - this.log.error('unsupported data type', { ...this.logContext, data: message.data }); + this.log.error('unsupported data type', { data: message.data }); return; } @@ -998,12 +992,9 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (event instanceof ErrorEvent && event.error) { const { error } = event.error; - this.log.error(`DataChannel error on ${channelKind}: ${event.message}`, { - ...this.logContext, - error, - }); + this.log.error(`DataChannel error on ${channelKind}: ${event.message}`, { error }); } else { - this.log.error(`Unknown DataChannel error on ${channelKind}`, { ...this.logContext, event }); + this.log.error(`Unknown DataChannel error on ${channelKind}`, { event }); } }; @@ -1021,7 +1012,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit return sender; } if (supportsAddTrack()) { - this.log.warn('using add-track fallback', this.logContext); + this.log.warn('using add-track fallback'); const sender = await this.createRTCRtpSender(track.mediaStreamTrack); return sender; } @@ -1039,7 +1030,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit return this.createSimulcastTransceiverSender(track, simulcastTrack, opts, encodings); } if (supportsAddTrack()) { - this.log.debug('using add-track fallback', this.logContext); + this.log.debug('using add-track fallback'); return this.createRTCRtpSender(track.mediaStreamTrack); } @@ -1118,16 +1109,15 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit return; } - this.log.warn(`${connection} disconnected`, this.logContext); + this.reconnectLog.warn(`${connection} disconnected`); if (this.reconnectAttempts === 0) { // only reset start time on the first try this.reconnectStart = Date.now(); } const disconnect = (duration: number) => { - this.log.warn( + this.reconnectLog.warn( `could not recover connection after ${this.reconnectAttempts} attempts, ${duration}ms. giving up`, - this.logContext, ); this.emit(EngineEvent.Disconnected); this.close(); @@ -1147,7 +1137,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit delay = 0; } - this.log.debug(`reconnecting in ${delay}ms`, this.logContext); + this.reconnectLog.debug(`reconnecting in ${delay}ms`); this.clearReconnectTimeout(); if (this.token) { @@ -1168,7 +1158,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit } // guard for attempting reconnection multiple times while one attempt is still not finished if (this.attemptingReconnect) { - log.warn('already attempting reconnect, returning early', this.logContext); + this.reconnectLog.warn('already attempting reconnect, returning early'); return; } if ( @@ -1193,7 +1183,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.reconnectAttempts += 1; let recoverable = true; if (e instanceof UnexpectedConnectionState) { - this.log.debug('received unrecoverable error', { ...this.logContext, error: e }); + this.reconnectLog.debug('received unrecoverable error', { error: e }); // unrecoverable recoverable = false; } else if (!(e instanceof SignalReconnectError)) { @@ -1204,11 +1194,10 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (recoverable) { this.handleDisconnect('reconnect', ReconnectReason.RR_UNKNOWN); } else { - this.log.info( + this.reconnectLog.info( `could not recover connection after ${this.reconnectAttempts} attempts, ${ Date.now() - this.reconnectStart }ms. giving up`, - this.logContext, ); this.emit(EngineEvent.Disconnected); await this.close(); @@ -1222,7 +1211,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit try { return this.reconnectPolicy.nextRetryDelayInMs(context); } catch (e) { - this.log.warn('encountered error in reconnect policy', { ...this.logContext, error: e }); + this.reconnectLog.warn('encountered error in reconnect policy', { error: e }); } // error in user code with provided reconnect policy, stop reconnecting @@ -1236,7 +1225,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit throw new UnexpectedConnectionState('could not reconnect, url or token not saved'); } - this.log.info(`reconnecting, attempt: ${this.reconnectAttempts}`, this.logContext); + this.reconnectLog.info(`reconnecting, attempt: ${this.reconnectAttempts}`); this.emit(EngineEvent.Restarting); if (!this.client.isDisconnected) { @@ -1248,10 +1237,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit let joinResponse: JoinResponse; try { if (!this.signalOpts) { - this.log.warn( - 'attempted connection restart, without signal options present', - this.logContext, - ); + this.reconnectLog.warn('attempted connection restart, without signal options present'); throw new SignalReconnectError(); } // in case a regionUrl is passed, the region URL takes precedence @@ -1312,7 +1298,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit throw new UnexpectedConnectionState('publisher and subscriber connections unset'); } - this.log.info(`resuming signal connection, attempt ${this.reconnectAttempts}`, this.logContext); + this.reconnectLog.info(`resuming signal connection, attempt ${this.reconnectAttempts}`); this.emit(EngineEvent.Resuming); let res: ReconnectResponse | undefined; try { @@ -1322,7 +1308,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit let message = ''; if (error instanceof Error) { message = error.message; - this.log.error(error.message, { ...this.logContext, error }); + this.reconnectLog.error(error.message, { error }); } if (error instanceof ConnectionError && error.reason === ConnectionErrorReason.NotAllowed) { throw new UnexpectedConnectionState('could not reconnect, token might be expired'); @@ -1341,7 +1327,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit this.latestJoinResponse.serverInfo = res.serverInfo; } } else { - this.log.warn('Did not receive reconnect response', this.logContext); + this.reconnectLog.warn('Did not receive reconnect response'); } if (this.shouldFailNext) { @@ -1384,7 +1370,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit private async waitForPCReconnected() { this.pcState = PCState.Reconnecting; - this.log.debug('waiting for peer connection to reconnect', this.logContext); + this.reconnectLog.debug('waiting for peer connection to reconnect'); try { await sleep(minReconnectWait); // FIXME setTimeout again not ideal for a connection critical path if (!this.pcManager) { @@ -1531,7 +1517,6 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (this.lossyDataDropCount % 100 === 0) { this.log.warn( `dropping lossy data channel messages, total dropped: ${this.lossyDataDropCount}`, - this.logContext, ); } return; @@ -1637,7 +1622,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit if (needNegotiation) { // start negotiation this.negotiate().catch((err) => { - log.error(err, this.logContext); + this.log.error(err); }); } @@ -1714,7 +1699,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit const handleClosed = () => { abortController.abort(); - this.log.debug('engine disconnected while negotiation was ongoing', this.logContext); + this.log.debug('engine disconnected while negotiation was ongoing'); resolve(); return; }; @@ -1795,7 +1780,7 @@ export default class RTCEngine extends (EventEmitter as new () => TypedEventEmit localDataTrackInfos: Array, ) { if (!this.pcManager) { - this.log.warn('sync state cannot be sent without peer connection setup', this.logContext); + this.log.warn('sync state cannot be sent without peer connection setup'); return; } const previousPublisherOffer = this.pcManager.publisher.getLocalDescription(); diff --git a/src/room/Room.ts b/src/room/Room.ts index cf782f5a49..af4e27f0d5 100644 --- a/src/room/Room.ts +++ b/src/room/Room.ts @@ -233,7 +233,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.sidToIdentity = new Map(); this.options = { ...roomOptionDefaults, ...options }; - this.log = getLogger(this.options.loggerName ?? LoggerNames.Room); + this.log = getLogger(this.options.loggerName ?? LoggerNames.Room, () => this.logContext); this.transcriptionReceivedTimes = new Map(); this.options.audioCaptureDefaults = { @@ -329,7 +329,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.switchActiveDevice( 'audiooutput', unwrapConstraint(this.options.audioOutput.deviceId), - ).catch((e) => this.log.warn(`Could not set audio output: ${e.message}`, this.logContext)); + ).catch((e) => this.log.warn(`Could not set audio output: ${e.message}`)); } if (isWeb()) { @@ -467,8 +467,8 @@ class Room extends (EventEmitter as new () => TypedEmitter) return { room: this.name, roomID: this.roomInfo?.sid, - participant: this.localParticipant.identity, - participantID: this.localParticipant.sid, + participant: this.localParticipant?.identity, + participantID: this.localParticipant?.sid, }; } @@ -555,7 +555,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) .on(EngineEvent.Resuming, () => { this.clearConnectionReconcile(); this.isResuming = true; - this.log.info('Resuming signal connection', this.logContext); + this.log.debug('Resuming signal connection'); if (this.setAndEmitConnectionState(ConnectionState.SignalReconnecting)) { this.emit(RoomEvent.SignalReconnecting); } @@ -563,7 +563,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) .on(EngineEvent.Resumed, () => { this.registerConnectionReconcile(); this.isResuming = false; - this.log.info('Resumed signal connection', this.logContext); + this.log.debug('Resumed signal connection'); this.updateSubscriptions(); this.emitBufferedEvents(); if (this.setAndEmitConnectionState(ConnectionState.Connected)) { @@ -613,7 +613,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (!event.info) { this.log.warn( `received PublishDataTrackResponse, but event.info was ${event.info}, so skipping.`, - this.logContext, ); return; } @@ -632,7 +631,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (!event.info) { this.log.warn( `received UnPublishDataTrackResponse, but event.info was ${event.info}, so skipping.`, - this.logContext, ); return; } @@ -732,7 +730,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (this.state !== ConnectionState.Disconnected) { return; } - this.log.debug(`prepareConnection to ${url}`, this.logContext); + this.log.debug(`prepareConnection to ${url}`); try { if (isCloud(new URL(url)) && token) { this.regionUrlProvider = new RegionUrlProvider(url, token); @@ -742,13 +740,13 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (regionUrl && this.state === ConnectionState.Disconnected) { this.regionUrl = regionUrl; await fetch(toHttpUrl(regionUrl), { method: 'HEAD' }); - this.log.debug(`prepared connection to ${regionUrl}`, this.logContext); + this.log.debug(`prepared connection to ${regionUrl}`); } } else { await fetch(toHttpUrl(url), { method: 'HEAD' }); } } catch (e) { - this.log.warn('could not prepare connection', { ...this.logContext, error: e }); + this.log.warn('could not prepare connection', { error: e }); } } @@ -768,7 +766,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (this.state === ConnectionState.Connected) { // when the state is reconnecting or connected, this function returns immediately - this.log.info(`already connected to room ${this.name}`, this.logContext); + this.log.info(`already connected to room ${this.name}`); unlockDisconnect(); return Promise.resolve(); } @@ -798,7 +796,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.regionUrlProvider?.setServerReportedRegions(settings); }) .catch((e) => { - this.log.warn('could not fetch region settings', { ...this.logContext, error: e }); + this.log.warn('could not fetch region settings', { error: e }); }); } @@ -864,7 +862,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (nextUrl && !this.abortController?.signal.aborted) { this.log.info( `Initial connection failed with ConnectionError: ${error.message}. Retrying with another region: ${nextUrl}`, - this.logContext, ); this.recreateEngine(true); await connectFn(resolve, reject, nextUrl); @@ -930,7 +927,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) } if (serverInfo.version === '0.15.1' && this.options.dynacast) { - this.log.debug('disabling dynacast due to server version', this.logContext); + this.log.debug('disabling dynacast due to server version'); // dynacast has a bug in 0.15.1, so we cannot use it then roomOptions.dynacast = false; } @@ -950,7 +947,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.e2eeManager.setSifTrailer(joinResponse.sifTrailer); } catch (e: any) { this.log.error(e instanceof Error ? e.message : 'Could not set SifTrailer', { - ...this.logContext, error: e, }); } @@ -975,7 +971,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) this.isResuming || this.engine?.pendingReconnect ) { - this.log.info('Reconnection attempt replaced by new connection attempt', this.logContext); + this.log.info('Reconnection attempt replaced by new connection attempt'); // make sure we close and recreate the existing engine in order to get rid of any potentially ongoing reconnection attempts this.recreateEngine(true); } else { @@ -1027,7 +1023,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) resultingError.status = err.status; } this.log.debug(`error trying to establish signal connection`, { - ...this.logContext, error: err, }); throw resultingError; @@ -1077,12 +1072,10 @@ class Room extends (EventEmitter as new () => TypedEmitter) const unlock = await this.disconnectLock.lock(); try { if (this.state === ConnectionState.Disconnected) { - this.log.debug('already disconnected', this.logContext); + this.log.debug('already disconnected'); return; } - this.log.info('disconnect from room', { - ...this.logContext, - }); + this.log.info('disconnect from room'); if ( this.state === ConnectionState.Connecting || this.state === ConnectionState.Reconnecting || @@ -1090,7 +1083,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) ) { // try aborting pending connection attempt const msg = 'Abort connection attempt due to user initiated disconnect'; - this.log.warn(msg, this.logContext); + this.log.warn(msg); this.abortController?.abort(msg); // in case the abort controller didn't manage to cancel the connection attempt, reject the connect promise explicitly this.connectFuture?.reject?.(ConnectionError.cancelled('Client initiated disconnect')); @@ -1256,7 +1249,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) } private onPageLeave = async () => { - this.log.info('Page leave detected, disconnecting', this.logContext); + this.log.info('Page leave detected, disconnecting'); await this.disconnect(); }; @@ -1299,7 +1292,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (!document.hidden) { this.log.debug( 'page visible again, triggering startAudio to resume playback and update playback status', - this.logContext, ); this.startAudio(); } @@ -1359,7 +1351,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) } else { this.log.warn( 'Resuming video playback failed, make sure you call `startVideo` directly in a user gesture handler', - this.logContext, ); } }); @@ -1545,11 +1536,11 @@ class Room extends (EventEmitter as new () => TypedEmitter) return; } if (this.state === ConnectionState.Disconnected) { - this.log.warn('skipping incoming track after Room disconnected', this.logContext); + this.log.warn('skipping incoming track after Room disconnected'); return; } if (mediaTrack.readyState === 'ended') { - this.log.info('skipping incoming track as it already ended', this.logContext); + this.log.debug('skipping incoming track as it already ended'); return; } const parts = unpackStreamId(stream.id); @@ -1561,7 +1552,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (streamId && streamId.startsWith('TR')) trackId = streamId; if (participantSid === this.localParticipant.sid) { - this.log.warn('tried to create RemoteParticipant for local participant', this.logContext); + this.log.warn('tried to create RemoteParticipant for local participant'); return; } @@ -1574,7 +1565,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (participantSid.startsWith('PA')) { this.log.error( `Tried to add a track for a participant, that's not present. Sid: ${participantSid}`, - this.logContext, ); } return; @@ -1588,7 +1578,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (!id) { this.log.error( `Tried to add a track whose 'sid' could not be found for a participant, that's not present. Sid: ${participantSid}`, - this.logContext, ); return; } @@ -1598,7 +1587,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (!trackId.startsWith('TR')) { this.log.warn( `Tried to add a track whose 'sid' could not be determined for a participant, that's not present. Sid: ${participantSid}, streamId: ${streamId}, trackId: ${trackId}`, - { ...this.logContext, remoteParticipantID: participantSid, streamId, trackId }, + { remoteParticipantID: participantSid, streamId, trackId }, ); } @@ -1645,7 +1634,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) // the subscription before publishTrack has finished adding the publication. // defer with a timeout until LocalTrackPublished fires for the matching trackSid this.log.debug('deferring LocalTrackSubscribed, publication not yet available', { - ...this.logContext, subscribedSid, }); @@ -1677,7 +1665,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) } else { this.log.warn( 'could not find local track publication for LocalTrackSubscribed event after timeout', - { ...this.logContext, subscribedSid }, + { subscribedSid }, ); } }, TIMEOUT_MS); @@ -1710,7 +1698,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) private handleSignalRestarted = async (joinResponse: JoinResponse) => { this.log.debug(`signal reconnected to server, region ${joinResponse.serverRegion}`, { - ...this.logContext, region: joinResponse.serverRegion, }); this.bufferedEvents = []; @@ -1721,18 +1708,12 @@ class Room extends (EventEmitter as new () => TypedEmitter) // unpublish & republish tracks await this.localParticipant.republishAllTracks(undefined, true); } catch (error) { - this.log.error('error trying to re-publish tracks after reconnection', { - ...this.logContext, - error, - }); + this.log.error('error trying to re-publish tracks after reconnection', { error }); } try { await this.engine.waitForRestarted(); - this.log.debug(`fully reconnected to server`, { - ...this.logContext, - region: joinResponse.serverRegion, - }); + this.log.debug(`fully reconnected to server`, { region: joinResponse.serverRegion }); } catch { // reconnection failed, handleDisconnect is being invoked already, just return here return; @@ -2158,7 +2139,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) }; private handleAudioPlaybackFailed = (e: any) => { - this.log.warn('could not playback audio', { ...this.logContext, error: e }); + this.log.warn('could not playback audio', { error: e }); if (!this.canPlaybackAudio) { return; } @@ -2304,7 +2285,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) try { await Promise.race([this.audioContext.resume(), sleep(200)]); } catch (e: any) { - this.log.warn('Could not resume audio context', { ...this.logContext, error: e }); + this.log.warn('Could not resume audio context', { error: e }); } } @@ -2347,7 +2328,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) if (this.options.audioOutput?.deviceId) { participant .setAudioOutput(this.options.audioOutput) - .catch((e) => this.log.warn(`Could not set audio output: ${e.message}`, this.logContext)); + .catch((e) => this.log.warn(`Could not set audio output: ${e.message}`)); } return participant; } @@ -2506,7 +2487,6 @@ class Room extends (EventEmitter as new () => TypedEmitter) ) { consecutiveFailures++; this.log.warn('detected connection state mismatch', { - ...this.logContext, numFailures: consecutiveFailures, engine: this.engine ? { @@ -2539,6 +2519,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) // unchanged return false; } + this.log.info(`connection state changed: ${this.state} -> ${state}`); this.state = state; this.incomingDataStreamManager.setConnected(state === ConnectionState.Connected); this.emit(RoomEvent.ConnectionStateChanged, this.state); @@ -2633,10 +2614,7 @@ class Room extends (EventEmitter as new () => TypedEmitter) deviceId && deviceId !== this.localParticipant.activeDeviceMap.get(deviceKind) ) { - this.log.debug( - `local track restarted, setting ${deviceKind} ${deviceId} active`, - this.logContext, - ); + this.log.debug(`local track restarted, setting ${deviceKind} ${deviceId} active`); this.localParticipant.activeDeviceMap.set(deviceKind, deviceId); this.emit(RoomEvent.ActiveDeviceChanged, deviceKind, deviceId); } @@ -2815,13 +2793,9 @@ class Room extends (EventEmitter as new () => TypedEmitter) // only extract logContext from arguments in order to avoid logging the whole object tree const minimizedArgs = mapArgs(args).filter((arg: unknown) => arg !== undefined); if (event === RoomEvent.TrackSubscribed || event === RoomEvent.TrackUnsubscribed) { - this.log.trace(`subscribe trace: ${event}`, { - ...this.logContext, - event, - args: minimizedArgs, - }); + this.log.trace(`subscribe trace: ${event}`, { event, args: minimizedArgs }); } - this.log.debug(`room event ${event}`, { ...this.logContext, event, args: minimizedArgs }); + this.log.debug(`room event ${event}`, { event, args: minimizedArgs }); } return super.emit(event, ...args); } diff --git a/src/room/participant/LocalParticipant.ts b/src/room/participant/LocalParticipant.ts index 42c0a45bce..0a86c8eb71 100644 --- a/src/room/participant/LocalParticipant.ts +++ b/src/room/participant/LocalParticipant.ts @@ -290,7 +290,7 @@ export default class LocalParticipant extends Participant { if (this.reconnectFuture) { // @throws-transformer ignore - introduced due to adding Throws into Future, investigate this // further - this.reconnectFuture.promise.catch((e) => this.log.warn(e.message, this.logContext)); + this.reconnectFuture.promise.catch((e) => this.log.warn(e.message)); this.reconnectFuture?.reject?.(new Error('Got disconnected during reconnection attempt')); this.reconnectFuture = undefined; } @@ -548,7 +548,7 @@ export default class LocalParticipant extends Participant { options?: VideoCaptureOptions | AudioCaptureOptions | ScreenShareCaptureOptions, publishOptions?: TrackPublishOptions, ) { - this.log.debug('setTrackEnabled', { ...this.logContext, source, enabled }); + this.log.debug('setTrackEnabled', { source, enabled }); if (this.republishPromise) { await this.republishPromise; } @@ -561,10 +561,7 @@ export default class LocalParticipant extends Participant { if (this.pendingPublishing.has(source)) { const pendingTrack = await this.waitForPendingPublicationOfSource(source); if (!pendingTrack) { - this.log.info('waiting for pending publication promise timed out', { - ...this.logContext, - source, - }); + this.log.info('waiting for pending publication promise timed out', { source }); } await pendingTrack?.unmute(); return pendingTrack; @@ -612,9 +609,7 @@ export default class LocalParticipant extends Participant { isAudioTrack(localTrack) && opts.preConnectBuffer ) { - this.log.info('starting preconnect buffer for microphone', { - ...this.logContext, - }); + this.log.info('starting preconnect buffer for microphone'); localTrack.startPreConnectBuffer(); } } @@ -622,10 +617,7 @@ export default class LocalParticipant extends Participant { try { const publishPromises: Array> = []; for (const localTrack of localTracks) { - this.log.info('publishing track', { - ...this.logContext, - ...getLogContextFromTrack(localTrack), - }); + this.log.info('publishing track', getLogContextFromTrack(localTrack)); publishPromises.push(this.publishTrack(localTrack, publishOptions)); } @@ -648,10 +640,7 @@ export default class LocalParticipant extends Participant { // if there's no track available yet first wait for pending publishing promises of that source to see if it becomes available track = await this.waitForPendingPublicationOfSource(source); if (!track) { - this.log.info('waiting for pending publication promise timed out', { - ...this.logContext, - source, - }); + this.log.info('waiting for pending publication promise timed out', { source }); } } if (track && track.track) { @@ -917,10 +906,7 @@ export default class LocalParticipant extends Participant { }); if (existingPublication) { - this.log.warn('track has already been published, skipping', { - ...this.logContext, - ...getLogContextFromTrack(existingPublication), - }); + this.log.warn('track has already been published, skipping', getLogContextFromTrack(existingPublication)); return existingPublication; } @@ -938,16 +924,13 @@ export default class LocalParticipant extends Participant { // disable dtx for stereo track if not enabled explicitly if (isStereo) { if (opts.dtx === undefined) { - this.log.info( + this.log.debug( `Opus DTX will be disabled for stereo tracks by default. Enable them explicitly to make it work.`, - { - ...this.logContext, - ...getLogContextFromTrack(track), - }, + getLogContextFromTrack(track), ); } if (opts.red === undefined) { - this.log.info( + this.log.debug( `Opus RED will be disabled for stereo tracks by default. Enable them explicitly to make it work.`, ); } @@ -958,9 +941,6 @@ export default class LocalParticipant extends Participant { if (!isE2EESimulcastSupported() && this.roomOptions.e2ee) { this.log.info( `End-to-end encryption is set up, simulcast publishing will be disabled on Safari versions and iOS browsers running iOS < v17.2`, - { - ...this.logContext, - }, ); opts.simulcast = false; } @@ -972,7 +952,6 @@ export default class LocalParticipant extends Participant { try { if (this.engine.client.currentState !== SignalConnectionState.CONNECTED) { this.log.debug('deferring track publication until signal is connected', { - ...this.logContext, track: getLogContextFromTrack(track), }); @@ -1014,7 +993,6 @@ export default class LocalParticipant extends Participant { } catch (e) { if (!hasRetriedAfterNegotiationError && e instanceof NegotiationError) { this.log.warn('negotiation due to track publish failed, retrying after reconnect', { - ...this.logContext, error: e, }); this.pendingPublishPromises.delete(track); @@ -1036,10 +1014,7 @@ export default class LocalParticipant extends Participant { private hasPermissionsToPublish(track: LocalTrack): boolean { if (!this.permissions) { - this.log.warn('no permissions present for publishing track', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.warn('no permissions present for publishing track', getLogContextFromTrack(track)); return false; } const { canPublish, canPublishSources } = this.permissions; @@ -1050,10 +1025,7 @@ export default class LocalParticipant extends Participant { ) { return true; } - this.log.warn('insufficient permissions to publish', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.warn('insufficient permissions to publish', getLogContextFromTrack(track)); return false; } @@ -1065,10 +1037,10 @@ export default class LocalParticipant extends Participant { (publishedTrack) => isLocalTrack(track) && publishedTrack.source === track.source, ); if (existingTrackOfSource && track.source !== Track.Source.Unknown) { - this.log.info(`publishing a second track with the same source: ${track.source}`, { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.info( + `publishing a second track with the same source: ${track.source}`, + getLogContextFromTrack(track), + ); } if (opts.stopMicTrackOnMute && isAudioTrack(track)) { track.stopOnMute = true; @@ -1172,7 +1144,6 @@ export default class LocalParticipant extends Participant { }; // log failure this.log.error('could not determine track dimensions, using defaults', { - ...this.logContext, ...getLogContextFromTrack(track), dims, }); @@ -1194,10 +1165,10 @@ export default class LocalParticipant extends Participant { // that we need if ('contentHint' in track.mediaStreamTrack) { track.mediaStreamTrack.contentHint = 'motion'; - this.log.info('forcing contentHint to motion for screenshare with SVC codecs', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug( + 'forcing contentHint to motion for screenshare with SVC codecs', + getLogContextFromTrack(track), + ); } } // set scalabilityMode to 'L3T3_KEY' by default @@ -1318,13 +1289,12 @@ export default class LocalParticipant extends Participant { try { this.engine.pcManager.publisher.removeTrack(track.sender); } catch (e) { - this.log.error(e, this.logContext); + this.log.error(e); } await this.engine.negotiate().catch((negotiateErr) => { this.log.error( 'failed to negotiate after removing track due to failed add track request', { - ...this.logContext, ...getLogContextFromTrack(track), error: negotiateErr, }, @@ -1351,7 +1321,6 @@ export default class LocalParticipant extends Participant { const updatedCodec = mimeTypeToVideoCodecString(primaryCodecMime); if (updatedCodec !== videoCodec) { this.log.debug('falling back to server selected codec', { - ...this.logContext, ...getLogContextFromTrack(track), codec: updatedCodec, }); @@ -1391,11 +1360,7 @@ export default class LocalParticipant extends Participant { } } - this.log.debug(`publishing ${track.kind} with encodings`, { - ...this.logContext, - encodings, - trackInfo: ti, - }); + this.log.debug(`publishing ${track.kind} with encodings`, { encodings, trackInfo: ti }); if (isLocalVideoTrack(track)) { track.startMonitor(this.engine.client); @@ -1417,13 +1382,10 @@ export default class LocalParticipant extends Participant { this.on(ParticipantEvent.LocalTrackSubscribed, (pub) => { if (pub.trackSid === ti.sid) { if (!track.hasPreConnectBuffer) { - this.log.warn('subscribe event came to late, buffer already closed', this.logContext); + this.log.warn('subscribe event came to late, buffer already closed'); return; } - this.log.debug('finished recording preconnect buffer', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('finished recording preconnect buffer', getLogContextFromTrack(track)); track.stopPreConnectBuffer(); } }); @@ -1431,19 +1393,13 @@ export default class LocalParticipant extends Participant { if (stream) { const bufferStreamPromise = new Promise(async (resolve, reject) => { try { - this.log.debug('waiting for agent', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('waiting for agent', getLogContextFromTrack(track)); const agentActiveTimeout = setTimeout(() => { reject(new Error('agent not active within 10 seconds')); }, 10_000); const agent = await this.waitUntilActiveAgentPresent(); clearTimeout(agentActiveTimeout); - this.log.debug('sending preconnect buffer', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('sending preconnect buffer', getLogContextFromTrack(track)); const writer = await this.streamBytes({ name: 'preconnect-buffer', mimeType, @@ -1466,14 +1422,10 @@ export default class LocalParticipant extends Participant { }); bufferStreamPromise .then(() => { - this.log.debug('preconnect buffer sent successfully', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('preconnect buffer sent successfully', getLogContextFromTrack(track)); }) .catch((e) => { this.log.error('error sending preconnect buffer', { - ...this.logContext, ...getLogContextFromTrack(track), error: e, }); @@ -1527,10 +1479,7 @@ export default class LocalParticipant extends Participant { if (!encodings) { this.log.info( `backup codec has been disabled, ignoring request to add additional codec for track`, - { - ...this.logContext, - ...getLogContextFromTrack(track), - }, + getLogContextFromTrack(track), ); return; } @@ -1571,7 +1520,6 @@ export default class LocalParticipant extends Participant { const ti = rets[0]; this.log.debug(`published ${videoCodec} for track ${track.sid}`, { - ...this.logContext, encodings, trackInfo: ti, }); @@ -1584,10 +1532,7 @@ export default class LocalParticipant extends Participant { if (isLocalTrack(track)) { const publishPromise = this.pendingPublishPromises.get(track); if (publishPromise) { - this.log.info('awaiting publish promise before attempting to unpublish', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('awaiting publish promise before attempting to unpublish', getLogContextFromTrack(track)); await publishPromise; } } @@ -1596,16 +1541,10 @@ export default class LocalParticipant extends Participant { const pubLogContext = publication ? getLogContextFromTrack(publication) : undefined; - this.log.debug('unpublishing track', { - ...this.logContext, - ...pubLogContext, - }); + this.log.info('unpublishing track', pubLogContext); if (!publication || !publication.track) { - this.log.warn('track was not unpublished because no publication was found', { - ...this.logContext, - ...pubLogContext, - }); + this.log.warn('track was not unpublished because no publication was found', pubLogContext); return undefined; } @@ -1648,7 +1587,7 @@ export default class LocalParticipant extends Participant { try { negotiationNeeded = this.engine.removeTrack(trackSender); } catch (e) { - this.log.warn(e, this.logContext); + this.log.warn(e); negotiationNeeded = true; } @@ -1658,7 +1597,7 @@ export default class LocalParticipant extends Participant { try { negotiationNeeded = this.engine.removeTrack(trackInfo.sender); } catch (e) { - this.log.warn(e, this.logContext); + this.log.warn(e); negotiationNeeded = true; } trackInfo.sender = undefined; @@ -1667,11 +1606,7 @@ export default class LocalParticipant extends Participant { track.simulcastCodecs.clear(); } } catch (e) { - this.log.warn('failed to unpublish track', { - ...this.logContext, - ...pubLogContext, - error: e, - }); + this.log.warn('failed to unpublish track', { ...pubLogContext, error: e }); } } @@ -1734,10 +1669,7 @@ export default class LocalParticipant extends Participant { ) { // generally we need to restart the track before publishing, often a full reconnect // is necessary because computer had gone to sleep. - this.log.debug('restarting existing track', { - ...this.logContext, - track: pub.trackSid, - }); + this.log.debug('restarting existing track', { track: pub.trackSid }); await track.restartTrack(); } await this.publishOrRepublishTrack(track, pub.options, true); @@ -2107,7 +2039,6 @@ export default class LocalParticipant extends Participant { const mutedOnServer = pub.isMuted || (pub.track?.isUpstreamPaused ?? false); if (mutedOnServer !== ti.muted) { this.log.debug('updating server mute state after reconcile', { - ...this.logContext, ...getLogContextFromTrack(pub), mutedOnServer, }); @@ -2120,7 +2051,6 @@ export default class LocalParticipant extends Participant { private updateTrackSubscriptionPermissions = () => { this.log.debug('updating track subscription permissions', { - ...this.logContext, allParticipantsAllowed: this.allParticipantsAllowedToSubscribe, participantTrackPermissions: this.participantTrackPermissions, }); @@ -2167,10 +2097,10 @@ export default class LocalParticipant extends Participant { } if (!track.sid) { - this.log.error('could not update mute status for unpublished track', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.error( + 'could not update mute status for unpublished track', + getLogContextFromTrack(track), + ); return; } @@ -2178,18 +2108,12 @@ export default class LocalParticipant extends Participant { }; private onTrackUpstreamPaused = (track: LocalTrack) => { - this.log.debug('upstream paused', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('upstream paused', getLogContextFromTrack(track)); this.onTrackMuted(track, true); }; private onTrackUpstreamResumed = (track: LocalTrack) => { - this.log.debug('upstream resumed', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('upstream resumed', getLogContextFromTrack(track)); this.onTrackMuted(track, track.isMuted); }; @@ -2198,7 +2122,6 @@ export default class LocalParticipant extends Participant { if (!pub) { this.log.warn( `Could not update local audio track settings, missing publication for track ${track.sid}`, - this.logContext, ); return; } @@ -2206,10 +2129,7 @@ export default class LocalParticipant extends Participant { }; private onTrackCpuConstrained = (track: LocalVideoTrack, publication: LocalTrackPublication) => { - this.log.debug('track cpu constrained', { - ...this.logContext, - ...getLogContextFromTrack(publication), - }); + this.log.debug('track cpu constrained', getLogContextFromTrack(publication)); this.emit(ParticipantEvent.LocalTrackCpuConstrained, track, publication); }; @@ -2220,7 +2140,6 @@ export default class LocalParticipant extends Participant { const pub = this.videoTrackPublications.get(update.trackSid); if (!pub) { this.log.warn('received subscribed quality update for unknown track', { - ...this.logContext, trackSid: update.trackSid, }); return; @@ -2231,10 +2150,7 @@ export default class LocalParticipant extends Participant { const newCodecs = await pub.videoTrack.setPublishingCodecs(update.subscribedCodecs); for await (const codec of newCodecs) { if (isBackupCodec(codec)) { - this.log.debug(`publish ${codec} for ${pub.videoTrack.sid}`, { - ...this.logContext, - ...getLogContextFromTrack(pub), - }); + this.log.debug(`publish ${codec} for ${pub.videoTrack.sid}`, getLogContextFromTrack(pub)); await this.publishAdditionalCodecForTrack(pub.videoTrack, codec, pub.options); } } @@ -2244,7 +2160,6 @@ export default class LocalParticipant extends Participant { const track = this.trackPublications.get(unpublished.trackSid); if (!track) { this.log.warn('received unpublished event for unknown track', { - ...this.logContext, trackSid: unpublished.trackSid, }); return; @@ -2257,10 +2172,7 @@ export default class LocalParticipant extends Participant { track.source === Track.Source.ScreenShare || track.source === Track.Source.ScreenShareAudio ) { - this.log.debug('unpublishing local track due to TrackEnded', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug('unpublishing local track due to TrackEnded', getLogContextFromTrack(track)); this.unpublishTrack(track); } else if (track.isUserProvided) { await track.mute(); @@ -2274,10 +2186,10 @@ export default class LocalParticipant extends Participant { name: track.source === Track.Source.Camera ? 'camera' : 'microphone', }); if (currentPermissions && currentPermissions.state === 'denied') { - this.log.warn(`user has revoked access to ${track.source}`, { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.warn( + `user has revoked access to ${track.source}`, + getLogContextFromTrack(track), + ); // detect granted change after permissions were denied to try and resume then currentPermissions.onchange = () => { @@ -2295,10 +2207,10 @@ export default class LocalParticipant extends Participant { } } if (!track.isMuted) { - this.log.debug('track ended, attempting to use a different device', { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.debug( + 'track ended, attempting to use a different device', + getLogContextFromTrack(track), + ); if (isLocalAudioTrack(track)) { // fall back to default device if available await track.restartTrack({ deviceId: 'default' }); @@ -2307,10 +2219,7 @@ export default class LocalParticipant extends Participant { } } } catch (e) { - this.log.warn(`could not restart track, muting instead`, { - ...this.logContext, - ...getLogContextFromTrack(track), - }); + this.log.warn(`could not restart track, muting instead`, getLogContextFromTrack(track)); await track.mute(); } } diff --git a/src/room/participant/Participant.ts b/src/room/participant/Participant.ts index 8706cd6530..fb501a01b9 100644 --- a/src/room/participant/Participant.ts +++ b/src/room/participant/Participant.ts @@ -140,8 +140,11 @@ export default class Participant extends (EventEmitter as new () => TypedEmitter ) { super(); - this.log = getLogger(loggerOptions?.loggerName ?? LoggerNames.Participant); this.loggerOptions = loggerOptions; + this.log = getLogger( + loggerOptions?.loggerName ?? LoggerNames.Participant, + () => this.logContext, + ); this.setMaxListeners(100); this.sid = sid;