Skip to content

Commit b1dcf7b

Browse files
committed
feat: add log levels; fix: default log level is WarnAndErrorOnly
1 parent 38d2140 commit b1dcf7b

File tree

2 files changed

+85
-49
lines changed

2 files changed

+85
-49
lines changed

src/main.ts

Lines changed: 80 additions & 41 deletions
Original file line numberDiff line numberDiff line change
@@ -23,31 +23,70 @@ type legacyIdDataType = {
2323
};
2424
type apiKeysObject = { [listname: string]: string };
2525

26-
type LogOptions = { extended?: boolean; logger?: UserLogger };
26+
// eslint doesnt like enums
27+
// eslint-disable-next-line no-shadow
28+
export enum LogLevel {
29+
None = 0x0000,
30+
ErrorOnly = 0x0010,
31+
WarnAndErrorOnly = 0x0020,
32+
All = 0x0030,
33+
}
34+
35+
type LogOptions = {
36+
extended?: boolean;
37+
logLevel?: LogLevel;
38+
logger?: UserLogger;
39+
};
2740

2841
let listData = fallbackData as listDataType;
2942
let legacyIds = legacyIdsFallbackData as legacyIdDataType;
3043
const lastUpdatedListAt = new Date(1999); // some date that's definitely past
31-
let extendedLogging = false;
3244
let useBotblockAPI = true;
3345

46+
let logLevel = LogLevel.WarnAndErrorOnly;
47+
3448
/**
3549
* the userLogger variable will later be defined with the
3650
* logger supplied by the user if they supplied any
3751
*/
3852
// eslint-disable-next-line max-len
3953
let userLogger: UserLogger | undefined;
4054

41-
const log = {
42-
info: (msg: string) => (userLogger
43-
? userLogger.info(`BLAPI: ${msg}`)
44-
: console.info(`[INFO] BLAPI: ${msg}`)),
45-
warn: (msg: string) => (userLogger
46-
? userLogger.warn(`BLAPI: ${msg}`)
47-
: console.warn(`[WARN] BLAPI: ${msg}`)),
48-
error: (err: any) => (userLogger
49-
? userLogger.error(`BLAPI: ${err}`)
50-
: console.error(`[ERROR] BLAPI ${err}`)),
55+
function createBlapiMessage(message: string) {
56+
return `BLAPI: ${message}`;
57+
}
58+
59+
const logger = {
60+
info: (msg: string) => {
61+
if (logLevel < LogLevel.All) {
62+
return;
63+
}
64+
if (userLogger) {
65+
userLogger.info(createBlapiMessage(msg));
66+
} else {
67+
console.info(createBlapiMessage(msg));
68+
}
69+
},
70+
warn: (msg: string) => {
71+
if (logLevel < LogLevel.WarnAndErrorOnly) {
72+
return;
73+
}
74+
if (userLogger) {
75+
userLogger.warn(createBlapiMessage(msg));
76+
} else {
77+
console.warn(createBlapiMessage(msg));
78+
}
79+
},
80+
error: (msg: string) => {
81+
if (logLevel < LogLevel.ErrorOnly) {
82+
return;
83+
}
84+
if (userLogger) {
85+
userLogger.error(createBlapiMessage(msg));
86+
} else {
87+
console.error(createBlapiMessage(msg));
88+
}
89+
},
5190
};
5291

5392
function convertLegacyIds(apiKeys: apiKeysObject) {
@@ -100,36 +139,36 @@ async function postToAllLists(
100139
try {
101140
const tmpListData = await get<listDataType>(
102141
'https://botblock.org/api/lists?filter=true',
103-
log,
142+
logger,
104143
);
105144
// make sure we only save it if nothing goes wrong
106145
if (tmpListData) {
107146
listData = tmpListData;
108-
log.info('Updated list endpoints.');
147+
logger.info('Updated list endpoints.');
109148
} else {
110-
log.error('Got empty list of endpoints from botblock.');
149+
logger.error('Got empty list of endpoints from botblock.');
111150
}
112151
} catch (e) {
113-
log.error(e);
114-
log.error(
152+
logger.error(String(e));
153+
logger.error(
115154
"Something went wrong when contacting BotBlock for the API of the lists, so we're using an older preset. Some lists might not be available because of this.",
116155
);
117156
}
118157
try {
119158
const tmpLegacyIdsData = await get<legacyIdDataType>(
120159
'https://botblock.org/api/legacy-ids',
121-
log,
160+
logger,
122161
);
123162
// make sure we only save it if nothing goes wrong
124163
if (tmpLegacyIdsData) {
125164
legacyIds = tmpLegacyIdsData;
126-
log.info('Updated legacy Ids.');
165+
logger.info('Updated legacy Ids.');
127166
} else {
128-
log.error('Got empty list of legacy Ids from botblock.');
167+
logger.error('Got empty list of legacy Ids from botblock.');
129168
}
130169
} catch (e) {
131-
log.error(e);
132-
log.error(
170+
logger.error(String(e));
171+
logger.error(
133172
"Something went wrong when contacting BotBlock for legacy Ids, so we're using an older preset. Some lists might not be available because of this.",
134173
);
135174
}
@@ -158,9 +197,7 @@ async function postToAllLists(
158197
sendObj[list.api_shards] = shards;
159198
}
160199

161-
posts.push(
162-
post(apiPath, updatedApiKeys[listname], sendObj, extendedLogging, log),
163-
);
200+
posts.push(post(apiPath, updatedApiKeys[listname], sendObj, logger));
164201
}
165202
});
166203

@@ -210,8 +247,8 @@ async function handleInternal(
210247
0,
211248
);
212249
} catch (e) {
213-
log.error(e);
214-
log.error('Error while fetching shard server counts:');
250+
logger.error(String(e));
251+
logger.error('Error while fetching shard server counts:');
215252
}
216253
// Checks if bot is sharded with internal sharding
217254
} else if (client.ws.shards.size > 1) {
@@ -223,7 +260,7 @@ async function handleInternal(
223260

224261
if (shards.length !== client.ws.shards.size) {
225262
// If not all shards are up yet, we skip this run of handleInternal
226-
log.info("Not all shards are up yet, so we're skipping this run.");
263+
logger.info("Not all shards are up yet, so we're skipping this run.");
227264
return;
228265
}
229266
server_count = shards.reduce(
@@ -251,8 +288,7 @@ async function handleInternal(
251288
shard_count,
252289
shards,
253290
),
254-
extendedLogging,
255-
log,
291+
logger,
256292
);
257293

258294
// they blacklisted botblock, so we need to do this, posting their stats manually
@@ -278,7 +314,7 @@ async function handleInternal(
278314
}
279315
}
280316
} else {
281-
log.error(
317+
logger.error(
282318
`Discord client seems to not be connected yet, so we're skipping this run of the post. We will try again in ${repeatInterval} minutes.`,
283319
);
284320
}
@@ -355,8 +391,7 @@ export async function manualPost(
355391
shard_count,
356392
shards,
357393
),
358-
extendedLogging,
359-
log,
394+
logger,
360395
),
361396
);
362397
if (updatedApiKeys['top.gg']) {
@@ -388,27 +423,31 @@ export async function manualPost(
388423

389424
export function setLogging(logOptions: LogOptions): void {
390425
if (
391-
Object.prototype.hasOwnProperty.call(logOptions, 'extended')
392-
&& typeof logOptions.extended === 'boolean'
426+
typeof logOptions.logLevel === 'number'
427+
) {
428+
logLevel = logOptions.logLevel;
429+
} else if (
430+
// backwards compatibility
431+
typeof logOptions.extended === 'boolean'
393432
) {
394-
extendedLogging = logOptions.extended;
433+
logLevel = logOptions.extended ? LogLevel.All : LogLevel.WarnAndErrorOnly;
395434
}
396435
// no logger supplied by user
397436
if (!Object.prototype.hasOwnProperty.call(logOptions, 'logger')) {
398437
return;
399438
}
400-
const logger = logOptions.logger!; // we checked that it exists beforehand
439+
const passedLogger = logOptions.logger!; // we checked that it exists beforehand
401440
// making sure the logger supplied by the user has our required log levels (info, warn, error)
402441
if (
403-
typeof logger.info !== 'function'
404-
|| typeof logger.warn !== 'function'
405-
|| typeof logger.error !== 'function'
442+
typeof passedLogger.info !== 'function'
443+
|| typeof passedLogger.warn !== 'function'
444+
|| typeof passedLogger.error !== 'function'
406445
) {
407446
throw new Error(
408447
'Your supplied logger does not seem to expose the log levels BLAPI needs to work. Make sure your logger offers the following methods: info() warn() error()',
409448
);
410449
}
411-
userLogger = logOptions.logger;
450+
userLogger = passedLogger;
412451
}
413452

414453
export function setBotblock(useBotblock: boolean): void {

src/requests.ts

Lines changed: 5 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,6 @@ export async function post(
1111
apiPath: string,
1212
apiKey: string,
1313
sendObj: object,
14-
logStuff: boolean,
1514
logger: UserLogger,
1615
) {
1716
const postData = JSON.stringify(sendObj);
@@ -24,13 +23,11 @@ export async function post(
2423
};
2524
const response = await request.body(postData).send();
2625

27-
if (logStuff) {
28-
logger.info(` posted to ${apiPath}`);
29-
logger.info(` statusCode: ${response.statusCode}`);
30-
logger.info(` headers: ${JSON.stringify(response.headers)}`);
31-
// it's text because text accepts both json and plain text, while json only supports json
32-
logger.info(` data: ${await response.text()}`);
33-
}
26+
logger.info(` posted to ${apiPath}`);
27+
logger.info(` statusCode: ${response.statusCode}`);
28+
logger.info(` headers: ${JSON.stringify(response.headers)}`);
29+
// it's text because text accepts both json and plain text, while json only supports json
30+
logger.info(` data: ${await response.text()}`);
3431

3532
return response;
3633
} catch (e) {

0 commit comments

Comments
 (0)