Skip to content

Commit 1b6a6a0

Browse files
author
Josh Long
committed
dev: migrate to scoped logmanager (wip)
1 parent d0f3677 commit 1b6a6a0

File tree

2 files changed

+57
-38
lines changed

2 files changed

+57
-38
lines changed

packages/core/src/lib/lit-core.ts

Lines changed: 40 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -71,7 +71,7 @@ import {
7171
} from '@lit-protocol/types';
7272

7373
import { composeLitUrl } from './endpoint-version';
74-
import { LogLevel } from '@lit-protocol/logger';
74+
import { Logger, LogLevel, LogManager } from '@lit-protocol/logger';
7575

7676
// eslint-disable-next-line @typescript-eslint/no-explicit-any
7777
type Listener = (...args: any[]) => void;
@@ -162,6 +162,7 @@ export class LitCore {
162162
};
163163
private _blockHashUrl =
164164
'https://block-indexer.litgateway.com/get_most_recent_valid_block';
165+
protected _logger!: Logger;
165166

166167
// ========== Constructor ==========
167168
constructor(config: LitNodeClientConfig | CustomNetwork) {
@@ -203,7 +204,7 @@ export class LitCore {
203204

204205
// -- set global variables
205206
globalThis.litConfig = this.config;
206-
bootstrapLogManager(
207+
this._logger = bootstrapLogManager(
207208
'core',
208209
this.config.debug ? LogLevel.DEBUG : LogLevel.OFF
209210
);
@@ -215,6 +216,7 @@ export class LitCore {
215216
// If the user sets a new file path, we respect it over the default path.
216217
if (this.config.storageProvider?.provider) {
217218
log(
219+
this._logger,
218220
'localstorage api not found, injecting persistence instance found in config'
219221
);
220222
// using Object defineProperty in order to set a property previously defined as readonly.
@@ -228,18 +230,19 @@ export class LitCore {
228230
!this.config.storageProvider?.provider
229231
) {
230232
log(
233+
this._logger,
231234
'Looks like you are running in NodeJS and did not provide a storage provider, your sessions will not be cached'
232235
);
233236
}
234237
}
235238

236239
// ========== Logger utilities ==========
237240
getLogsForRequestId = (id: string): string[] => {
238-
return globalThis.logManager.getLogsForId(id);
241+
return LogManager.Instance.getLogsForId(id);
239242
};
240243

241-
getRequestIds = (): Set<string> => {
242-
return globalThis.logManager.LoggerIds;
244+
getRequestIds = (): string[] => {
245+
return LogManager.Instance.LoggerIds;
243246
};
244247

245248
/**
@@ -323,6 +326,7 @@ export class LitCore {
323326
// We don't need to handle node urls changing on centralised networks, since their validator sets are static
324327
try {
325328
log(
329+
this._logger,
326330
'State found to be new validator set locked, checking validator set'
327331
);
328332
const existingNodeUrls: string[] = [...this.config.bootstrapUrls];
@@ -342,6 +346,7 @@ export class LitCore {
342346
network request to the previous epoch's node set before changing over.
343347
*/
344348
log(
349+
this._logger,
345350
'Active validator sets changed, new validators ',
346351
delta,
347352
'starting node connection'
@@ -384,6 +389,7 @@ export class LitCore {
384389

385390
if (this._stakingContract) {
386391
log(
392+
this._logger,
387393
'listening for state change on staking contract: ',
388394
this._stakingContract.address
389395
);
@@ -526,7 +532,7 @@ export class LitCore {
526532
{}
527533
);
528534
if (this.config.litNetwork === LitNetwork.Custom) {
529-
log('using custom contracts: ', logAddresses);
535+
log(this._logger, 'using custom contracts: ', logAddresses);
530536
}
531537
}
532538

@@ -556,8 +562,8 @@ export class LitCore {
556562
globalThis.litNodeClient = this;
557563
this.ready = true;
558564

559-
log(`🔥 lit is ready. "litNodeClient" variable is ready to use globally.`);
560-
log('current network config', {
565+
log(this._logger, `🔥 lit is ready. "litNodeClient" variable is ready to use globally.`);
566+
log(this._logger, 'current network config', {
561567
networkPubkey: this.networkPubKey,
562568
networkPubKeySet: this.networkPubKeySet,
563569
hdRootPubkeys: this.hdRootPubkeys,
@@ -607,16 +613,18 @@ export class LitCore {
607613
keys.networkPubKeySet === 'ERR'
608614
) {
609615
logErrorWithRequestId(
616+
this._logger,
610617
requestId,
611618
'Error connecting to node. Detected "ERR" in keys',
612619
url,
613620
keys
614621
);
615622
}
616623

617-
log(`Handshake with ${url} returned keys: `, keys);
624+
log(this._logger, `Handshake with ${url} returned keys: `, keys);
618625
if (!keys.latestBlockhash) {
619626
logErrorWithRequestId(
627+
this._logger,
620628
requestId,
621629
`Error getting latest blockhash from the node ${url}.`
622630
);
@@ -638,12 +646,12 @@ export class LitCore {
638646
}
639647

640648
// actually verify the attestation by checking the signature against AMD certs
641-
log('Checking attestation against amd certs...');
649+
log(this._logger, 'Checking attestation against amd certs...');
642650

643651
try {
644652
// ensure we won't try to use a node with an invalid attestation response
645653
await checkSevSnpAttestation(attestation, challenge, url);
646-
log(`Lit Node Attestation verified for ${url}`);
654+
log(this._logger, `Lit Node Attestation verified for ${url}`);
647655
// eslint-disable-next-line @typescript-eslint/no-explicit-any
648656
} catch (e: any) {
649657
throwError({
@@ -654,6 +662,7 @@ export class LitCore {
654662
}
655663
} else if (this.config.litNetwork === 'custom') {
656664
log(
665+
this._logger,
657666
`Node attestation SEV verification is disabled. You must explicitly set "checkNodeAttestation" to true when using 'custom' network`
658667
);
659668
}
@@ -698,7 +707,7 @@ export class LitCore {
698707
errorCode: LIT_ERROR.INIT_ERROR.name,
699708
});
700709
} catch (e) {
701-
logErrorWithRequestId(requestId, e);
710+
logErrorWithRequestId(this._logger, requestId, e);
702711
reject(e);
703712
}
704713
}, this.config.connectTimeout);
@@ -739,6 +748,7 @@ export class LitCore {
739748

740749
if (!latestBlockhash) {
741750
logErrorWithRequestId(
751+
this._logger,
742752
requestId,
743753
'Error getting latest blockhash from the nodes.'
744754
);
@@ -809,11 +819,12 @@ export class LitCore {
809819
this.lastBlockHashRetrieved &&
810820
currentTime - this.lastBlockHashRetrieved < blockHashValidityDuration
811821
) {
812-
log('Blockhash is still valid. No need to sync.');
822+
log(this._logger, 'Blockhash is still valid. No need to sync.');
813823
return;
814824
}
815825

816826
log(
827+
this._logger,
817828
'Syncing state for new blockhash ',
818829
'current blockhash: ',
819830
this.latestBlockhash
@@ -824,7 +835,7 @@ export class LitCore {
824835
const blockHashBody: EthBlockhashInfo = await resp.json();
825836
this.latestBlockhash = blockHashBody.blockhash;
826837
this.lastBlockHashRetrieved = Date.now();
827-
log('Done syncing state new blockhash: ', this.latestBlockhash);
838+
log(this._logger, 'Done syncing state new blockhash: ', this.latestBlockhash);
828839

829840
// If the blockhash retrieval failed, throw an error to trigger fallback in catch block
830841
if (!this.latestBlockhash) {
@@ -835,19 +846,22 @@ export class LitCore {
835846
})
836847
.catch(async (err: BlockHashErrorResponse | Error) => {
837848
logError(
849+
this._logger,
838850
'Error while attempting to fetch new latestBlockhash:',
839851
err instanceof Error ? err.message : err.messages,
840852
'Reason: ',
841853
err instanceof Error ? err : err.reason
842854
);
843855

844856
log(
857+
this._logger,
845858
'Attempting to fetch blockhash manually using ethers with fallback RPC URLs...'
846859
);
847860
const provider = await this._getProviderWithFallback();
848861

849862
if (!provider) {
850863
logError(
864+
this._logger,
851865
'All fallback RPC URLs failed. Unable to retrieve blockhash.'
852866
);
853867
return;
@@ -858,11 +872,12 @@ export class LitCore {
858872
this.latestBlockhash = latestBlock.hash;
859873
this.lastBlockHashRetrieved = Date.now();
860874
log(
875+
this._logger,
861876
'Successfully retrieved blockhash manually: ',
862877
this.latestBlockhash
863878
);
864879
} catch (ethersError) {
865-
logError('Failed to manually retrieve blockhash using ethers');
880+
logError(this._logger, 'Failed to manually retrieve blockhash using ethers');
866881
}
867882
});
868883
}
@@ -937,7 +952,7 @@ export class LitCore {
937952
endpoint: LIT_ENDPOINT.HANDSHAKE,
938953
});
939954

940-
log(`handshakeWithNode ${urlWithPath}`);
955+
log(this._logger, `handshakeWithNode ${urlWithPath}`);
941956

942957
const data = {
943958
clientPublicKey: 'test',
@@ -956,6 +971,7 @@ export class LitCore {
956971
): Promise<Pick<EpochCache, 'startTime' | 'currentNumber'>> {
957972
if (!epochInfo) {
958973
log(
974+
this._logger,
959975
'epochinfo not found. Not a problem, fetching current epoch state from staking contract'
960976
);
961977
const validatorData = await this._getValidatorData();
@@ -1023,6 +1039,7 @@ export class LitCore {
10231039
}
10241040

10251041
logWithRequestId(
1042+
this._logger,
10261043
requestId,
10271044
`sendCommandToNode with url ${url} and data`,
10281045
data
@@ -1247,6 +1264,7 @@ export class LitCore {
12471264
);
12481265

12491266
logErrorWithRequestId(
1267+
this._logger,
12501268
requestId || '',
12511269
`most common error: ${JSON.stringify(mostCommonError)}`
12521270
);
@@ -1274,7 +1292,7 @@ export class LitCore {
12741292
res.error.errorCode === 'not_authorized') &&
12751293
this.config.alertWhenUnauthorized
12761294
) {
1277-
log('You are not authorized to access this content');
1295+
log(this._logger, 'You are not authorized to access this content');
12781296
}
12791297

12801298
throwError({
@@ -1328,6 +1346,7 @@ export class LitCore {
13281346
canonicalAccessControlConditionFormatter(c)
13291347
);
13301348
log(
1349+
this._logger,
13311350
'formattedAccessControlConditions',
13321351
JSON.stringify(formattedAccessControlConditions)
13331352
);
@@ -1336,6 +1355,7 @@ export class LitCore {
13361355
canonicalEVMContractConditionFormatter(c)
13371356
);
13381357
log(
1358+
this._logger,
13391359
'formattedEVMContractConditions',
13401360
JSON.stringify(formattedEVMContractConditions)
13411361
);
@@ -1346,6 +1366,7 @@ export class LitCore {
13461366
canonicalSolRpcConditionFormatter(c)
13471367
);
13481368
log(
1369+
this._logger,
13491370
'formattedSolRpcConditions',
13501371
JSON.stringify(formattedSolRpcConditions)
13511372
);
@@ -1355,6 +1376,7 @@ export class LitCore {
13551376
canonicalUnifiedAccessControlConditionFormatter(c)
13561377
);
13571378
log(
1379+
this._logger,
13581380
'formattedUnifiedAccessControlConditions',
13591381
JSON.stringify(formattedUnifiedAccessControlConditions)
13601382
);
@@ -1383,7 +1405,7 @@ export class LitCore {
13831405
sigType: LIT_CURVE = LIT_CURVE.EcdsaCaitSith
13841406
): string => {
13851407
if (!this.hdRootPubkeys) {
1386-
logError('root public keys not found, have you connected to the nodes?');
1408+
logError(this._logger, 'root public keys not found, have you connected to the nodes?');
13871409
throwError({
13881410
message: `root public keys not found, have you connected to the nodes?`,
13891411
errorKind: LIT_ERROR.LIT_NODE_CLIENT_NOT_READY_ERROR.kind,

packages/misc/src/lib/misc.ts

Lines changed: 17 additions & 20 deletions
Original file line numberDiff line numberDiff line change
@@ -28,7 +28,7 @@ import {
2828
} from '@lit-protocol/types';
2929
import { JsonRpcProvider } from '@ethersproject/providers';
3030
import { Contract } from '@ethersproject/contracts';
31-
import { LogLevel, LogManager } from '@lit-protocol/logger';
31+
import { Logger, LogLevel, LogManager } from '@lit-protocol/logger';
3232
import { version } from '@lit-protocol/constants';
3333
import Ajv, { JSONSchemaType } from 'ajv';
3434

@@ -226,8 +226,6 @@ declare global {
226226
var litConfig: any;
227227
var wasmExport: any;
228228
var wasmECDSA: any;
229-
var logger: any;
230-
var logManager: any;
231229
}
232230

233231
export const throwRemovedFunctionError = (functionName: string) => {
@@ -238,22 +236,21 @@ export const throwRemovedFunctionError = (functionName: string) => {
238236
});
239237
};
240238

239+
export const getLoggerbyId = (id: string) => {
240+
return LogManager.Instance.get(id);
241+
};
242+
241243
export const bootstrapLogManager = (
242244
id: string,
243245
level: LogLevel = LogLevel.DEBUG
244-
) => {
245-
if (!globalThis.logManager) {
246-
globalThis.logManager = LogManager.Instance;
247-
globalThis.logManager.withConfig({
248-
condenseLogs: true,
249-
});
250-
globalThis.logManager.setLevel(level);
251-
}
246+
): Logger => {
252247

253-
globalThis.logger = globalThis.logManager.get(id);
254-
};
248+
globalThis.logManager = LogManager.Instance;
249+
globalThis.logManager.withConfig({
250+
condenseLogs: true,
251+
});
252+
globalThis.logManager.setLevel(level);
255253

256-
export const getLoggerbyId = (id: string) => {
257254
return globalThis.logManager.get(id);
258255
};
259256

@@ -265,7 +262,7 @@ export const getLoggerbyId = (id: string) => {
265262
*
266263
* @returns { void }
267264
*/
268-
export const log = (...args: any): void => {
265+
export const log = (logger: Logger, ...args: any): void => {
269266
if (!globalThis) {
270267
// there is no globalThis, just print the log
271268
console.log(...args);
@@ -282,13 +279,13 @@ export const log = (...args: any): void => {
282279
// if there are there are logs in buffer, print them first and empty the buffer.
283280
while (logBuffer.length > 0) {
284281
const log = logBuffer.shift() ?? '';
285-
globalThis?.logger && globalThis?.logger.debug(...log);
282+
logger.debug(...log);
286283
}
287284

288-
globalThis?.logger && globalThis?.logger.debug(...args);
285+
globalThis?.logger && logger.debug(...args);
289286
};
290287

291-
export const logWithRequestId = (id: string, ...args: any) => {
288+
export const logWithRequestId = (logger: Logger, id: string, ...args: any) => {
292289
if (!globalThis) {
293290
// there is no globalThis, just print the log
294291
console.log(...args);
@@ -315,7 +312,7 @@ export const logWithRequestId = (id: string, ...args: any) => {
315312
globalThis.logManager.get(globalThis.logger.category, id).debug(...args);
316313
};
317314

318-
export const logErrorWithRequestId = (id: string, ...args: any) => {
315+
export const logErrorWithRequestId = (logger: Logger, id: string, ...args: any) => {
319316
if (!globalThis) {
320317
// there is no globalThis, just print the log
321318
console.log(...args);
@@ -342,7 +339,7 @@ export const logErrorWithRequestId = (id: string, ...args: any) => {
342339
globalThis.logManager.get(globalThis.logger.category, id).error(...args);
343340
};
344341

345-
export const logError = (...args: any) => {
342+
export const logError = (logger: Logger, ...args: any) => {
346343
if (!globalThis) {
347344
// there is no globalThis, just print the log
348345
console.log(...args);

0 commit comments

Comments
 (0)