Skip to content

Commit e9b41fb

Browse files
perf: disable logs by default in prod
1 parent b791d33 commit e9b41fb

File tree

8 files changed

+118
-30
lines changed

8 files changed

+118
-30
lines changed

src/hooks.client.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
import posthog from "posthog-js";
2+
import { derror } from "$lib/debug";
23

34
export function handleError({ error, status, event }) {
45
if (status === 404) return;
5-
console.error(`[CLIENT] ${error}`);
6+
derror(`[CLIENT] ${error}`);
67
posthog.captureException(error, event);
78
}

src/hooks.server.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ import { redirect } from "@sveltejs/kit";
22
import { dev } from "$app/environment";
33
import { PUBLIC_POSTHOG_KEY } from "$env/static/public";
44
import { PostHog } from "posthog-node";
5+
import { derror } from "$lib/debug";
56

67
const client = new PostHog(PUBLIC_POSTHOG_KEY, {
78
host: "https://eu.i.posthog.com",
@@ -10,7 +11,7 @@ const client = new PostHog(PUBLIC_POSTHOG_KEY, {
1011

1112
export async function handleError({ error, status, event }) {
1213
if (status !== 404) {
13-
console.error(`[SERVER] ${error}`);
14+
derror(`[SERVER] ${error}`);
1415
client.captureException(error, undefined, event);
1516
await client.shutdown();
1617
}

src/lib/debug.ts

Lines changed: 83 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,83 @@
1+
import { dev } from "$app/environment";
2+
3+
const DEBUG = false;
4+
5+
export function dlog(message?: unknown, ...optionalParams: unknown[]) {
6+
if (DEBUG) console.log(message, ...optionalParams);
7+
}
8+
9+
export function dwarn(message?: unknown, ...optionalParams: unknown[]) {
10+
if (dev || DEBUG) console.warn(message, ...optionalParams);
11+
}
12+
13+
export function derror(message?: unknown, ...optionalParams: unknown[]) {
14+
if (dev || DEBUG) console.error(message, ...optionalParams);
15+
}
16+
17+
export function ddebug(message?: unknown, ...optionalParams: unknown[]) {
18+
if (DEBUG) console.debug(message, ...optionalParams);
19+
}
20+
21+
export function dclear() {
22+
if (DEBUG) console.clear();
23+
}
24+
25+
export function dassert(condition?: boolean, ...data: unknown[]) {
26+
if (dev || DEBUG) console.assert(condition, ...data);
27+
}
28+
29+
export function dcount(label?: string) {
30+
if (DEBUG) console.count(label);
31+
}
32+
33+
export function dcountReset(label?: string) {
34+
if (DEBUG) console.countReset(label);
35+
}
36+
37+
export function ddir(item?: unknown, options?: unknown) {
38+
if (DEBUG) console.dir(item, options);
39+
}
40+
41+
export function ddirxml(...data: unknown[]) {
42+
if (DEBUG) console.dirxml(...data);
43+
}
44+
45+
export function dgroup(...label: unknown[]) {
46+
if (DEBUG) console.group(...label);
47+
}
48+
49+
export function dgroupEnd() {
50+
if (DEBUG) console.groupEnd();
51+
}
52+
53+
export function dprofile(label?: string) {
54+
if (DEBUG) console.profile(label);
55+
}
56+
57+
export function dprofileEnd(label?: string) {
58+
if (DEBUG) console.profileEnd(label);
59+
}
60+
61+
export function dtable(tabularData?: unknown, properties?: string[]) {
62+
if (DEBUG) console.table(tabularData, properties);
63+
}
64+
65+
export function dtime(label?: string) {
66+
if (DEBUG) console.time(label);
67+
}
68+
69+
export function dtimeEnd(label?: string) {
70+
if (DEBUG) console.timeEnd(label);
71+
}
72+
73+
export function dtimeLog(label?: string, ...data: unknown[]) {
74+
if (DEBUG) console.timeLog(label, ...data);
75+
}
76+
77+
export function dtimeStamp(label?: string) {
78+
if (DEBUG) console.timeStamp(label);
79+
}
80+
81+
export function dtrace(message?: unknown, ...optionalParams: unknown[]) {
82+
if (DEBUG) console.trace(message, ...optionalParams);
83+
}

src/lib/server/cache-handler.ts

Lines changed: 10 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { Redis } from "@upstash/redis";
2+
import { derror, dlog } from "$lib/debug";
23

34
export type RedisJson = Parameters<InstanceType<typeof Redis>["json"]["set"]>[2];
45

@@ -27,23 +28,23 @@ export class CacheHandler {
2728
*/
2829
async get<T extends RedisJson>(key: string) {
2930
if (this.#isDev) {
30-
console.log(`Retrieving ${key} from in-memory cache`);
31+
dlog(`Retrieving ${key} from in-memory cache`);
3132
// In dev mode, use memory cache only
3233
const entry = this.#memoryCache.get(key);
3334

3435
if (!entry) {
35-
console.log("Nothing to retrieve");
36+
dlog("Nothing to retrieve");
3637
return null;
3738
}
3839

3940
// Check if entry is expired
4041
if (entry.expiresAt && entry.expiresAt < Date.now()) {
41-
console.log("Value expired, purging and returning null");
42+
dlog("Value expired, purging and returning null");
4243
this.#memoryCache.delete(key);
4344
return null;
4445
}
4546

46-
console.log("Returning found value from in-memory cache");
47+
dlog("Returning found value from in-memory cache");
4748
return entry.value as T;
4849
}
4950

@@ -69,7 +70,7 @@ export class CacheHandler {
6970
}
7071
return value;
7172
} catch (error) {
72-
console.error("Redis get error:", error);
73+
derror("Redis get error:", error);
7374
return null;
7475
}
7576
}
@@ -83,12 +84,12 @@ export class CacheHandler {
8384
*/
8485
async set<T extends RedisJson>(key: string, value: T, ttlSeconds?: number) {
8586
if (this.#isDev) {
86-
console.log(`Setting value for ${key} in memory cache`);
87+
dlog(`Setting value for ${key} in memory cache`);
8788
// In dev mode, use memory cache only
8889
const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : null;
8990
if (expiresAt) {
90-
console.log(`Defining cache for ${key}, expires at ${new Date(expiresAt)}`);
91-
} else console.log(`No cache set for ${key}`);
91+
dlog(`Defining cache for ${key}, expires at ${new Date(expiresAt)}`);
92+
} else dlog(`No cache set for ${key}`);
9293
this.#memoryCache.set(key, { value, expiresAt });
9394
} else {
9495
// In production, use both Redis and memory cache
@@ -99,7 +100,7 @@ export class CacheHandler {
99100
const expiresAt = ttlSeconds ? Date.now() + ttlSeconds * 1000 : null;
100101
this.#memoryCache.set(key, { value, expiresAt });
101102
} catch (error) {
102-
console.error("Redis set error:", error);
103+
derror("Redis set error:", error);
103104
}
104105
}
105106
}

src/lib/server/github-cache.ts

Lines changed: 7 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ import { Redis } from "@upstash/redis";
1818
import { App, Octokit } from "octokit";
1919
import semver from "semver";
2020
import parseChangelog from "$lib/changelog-parser";
21+
import { derror, dlog } from "$lib/debug";
2122
import type { Repository } from "$lib/repositories";
2223
import type { Issues, Pulls } from "$lib/types";
2324
import { CacheHandler, type RedisJson } from "./cache-handler";
@@ -277,11 +278,11 @@ export class GitHubCache {
277278
): Promise<RType> => {
278279
const cachedValue = await this.#cache.get<RType>(cacheKey);
279280
if (cachedValue) {
280-
console.log(`Cache hit for ${cacheKey}`);
281+
dlog(`Cache hit for ${cacheKey}`);
281282
return cachedValue;
282283
}
283284

284-
console.log(`Cache miss for ${cacheKey}`);
285+
dlog(`Cache miss for ${cacheKey}`);
285286

286287
const newValue = await transformer(await promise());
287288

@@ -330,20 +331,20 @@ export class GitHubCache {
330331
try {
331332
return await this.getPullRequestDetails(owner, repo, id);
332333
} catch (err) {
333-
console.error(`Error trying to get PR details for ${owner}/${repo}: ${err}`);
334+
derror(`Error trying to get PR details for ${owner}/${repo}: ${err}`);
334335
}
335336

336337
try {
337338
// doesn't come first because issues will also resolve for prs
338339
return await this.getIssueDetails(owner, repo, id);
339340
} catch (err) {
340-
console.error(`Error trying to get issue details for ${owner}/${repo}: ${err}`);
341+
derror(`Error trying to get issue details for ${owner}/${repo}: ${err}`);
341342
}
342343

343344
try {
344345
return await this.getDiscussionDetails(owner, repo, id);
345346
} catch (err) {
346-
console.error(`Error trying to get discussion details for ${owner}/${repo}: ${err}`);
347+
derror(`Error trying to get discussion details for ${owner}/${repo}: ${err}`);
347348
}
348349

349350
return null;
@@ -973,7 +974,7 @@ export class GitHubCache {
973974
if (res.status !== 200) return {};
974975
return (await res.json()) as { deprecated?: boolean | string };
975976
} catch (error) {
976-
console.error(`Error fetching npmjs.org for package ${packageName}:`, error);
977+
derror(`Error fetching npmjs.org for package ${packageName}:`, error);
977978
return {};
978979
}
979980
},

src/lib/server/package-discoverer.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
import { dlog } from "$lib/debug";
12
import { type Repository, publicRepos } from "$lib/repositories";
23
import type { Prettify } from "$lib/types";
34
import { GitHubCache, githubCache } from "./github-cache";
@@ -50,7 +51,7 @@ export class PackageDiscoverer {
5051
})
5152
)
5253
];
53-
console.log(
54+
dlog(
5455
`Discovered ${packages.length} packages for ${repo.repoOwner}/${repo.repoName}: ${packages.join(", ")}`
5556
);
5657
return {

src/routes/all-package-releases.ts

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
import type { PostHog } from "posthog-node";
2+
import { dwarn } from "$lib/debug";
23
import { discoverer } from "$lib/server/package-discoverer";
34
import { getPackageReleases } from "./package/releases";
45

@@ -19,7 +20,7 @@ export function getAllPackagesReleases(
1920
return packages.reduce<Record<string, ReturnType<typeof getPackageReleases>>>(
2021
(acc, { pkg: { name } }) => {
2122
if (acc[name])
22-
console.warn(
23+
dwarn(
2324
`Duplicate package "${name}" while aggregating packages releases; this should not happen!`
2425
);
2526
acc[name] = getPackageReleases(name, allPackages, posthog);

src/routes/package/releases.ts

Lines changed: 10 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
import type { PostHog } from "posthog-node";
22
import semver from "semver";
3+
import { dlog, dwarn } from "$lib/debug";
34
import type { Repository } from "$lib/repositories";
45
import { type GitHubRelease, githubCache } from "$lib/server/github-cache";
56
import type { discoverer } from "$lib/server/package-discoverer";
@@ -28,7 +29,7 @@ export async function getPackageReleases(
2829
const foundVersions = new Set<string>();
2930
const releases: ({ cleanName: string; cleanVersion: string } & GitHubRelease)[] = [];
3031

31-
console.log("Starting loading releases...");
32+
dlog("Starting loading releases...");
3233

3334
// Step 1: First identify all matching packages and create fetch tasks
3435
const matchingPackageTasks: {
@@ -57,9 +58,7 @@ export async function getPackageReleases(
5758
// Await the individual fetch and process its results
5859
const cachedReleases = await releasesFetch();
5960

60-
console.log(
61-
`${cachedReleases.length} releases found for repo ${repo.repoOwner}/${repo.repoName}`
62-
);
61+
dlog(`${cachedReleases.length} releases found for repo ${repo.repoOwner}/${repo.repoName}`);
6362

6463
// Filter out invalid releases and sort them
6564
const validReleases = cachedReleases
@@ -75,7 +74,7 @@ export async function getPackageReleases(
7574
repoName: repo.repoName,
7675
...release
7776
});
78-
console.warn(`Empty release tag name: ${JSON.stringify(release)}`);
77+
dwarn(`Empty release tag name: ${JSON.stringify(release)}`);
7978
return false;
8079
}
8180
const [name, version] = repo.metadataFromTag(release.tag_name);
@@ -87,7 +86,7 @@ export async function getPackageReleases(
8786
parsedName: name,
8887
parsedVersion: version
8988
});
90-
console.warn(
89+
dwarn(
9190
`Invalid version from \`metadataFromTag\` "${version}" gotten from ${release.tag_name}`
9291
);
9392
return false;
@@ -102,7 +101,7 @@ export async function getPackageReleases(
102101
const [, secondVersion] = repo.metadataFromTag(b.tag_name);
103102
return semver.rcompare(firstVersion, secondVersion);
104103
});
105-
console.log("Final filtered count:", validReleases.length);
104+
dlog("Final filtered count:", validReleases.length);
106105

107106
// Return the processed data for further processing
108107
return {
@@ -119,18 +118,18 @@ export async function getPackageReleases(
119118
const { dataFilter, metadataFromTag, changelogContentsReplacer, ...serializableRepo } = repo;
120119
for (const release of validReleases) {
121120
const [cleanName, cleanVersion] = repo.metadataFromTag(release.tag_name);
122-
console.log(`Release ${release.tag_name}, extracted version: ${cleanVersion}`);
121+
dlog(`Release ${release.tag_name}, extracted version: ${cleanVersion}`);
123122
if (foundVersions.has(cleanVersion)) continue;
124123

125124
// If not, add its version to the set and itself to the final version
126125
const currentNewestVersion = [...foundVersions].sort(semver.rcompare)[0];
127-
console.log("Current newest version", currentNewestVersion);
126+
dlog("Current newest version", currentNewestVersion);
128127
foundVersions.add(cleanVersion);
129128
releases.push({ cleanName, cleanVersion, ...release });
130129

131130
// If it is newer than the newest we got, set this repo as the "final repo"
132131
if (!currentNewestVersion || semver.gt(cleanVersion, currentNewestVersion)) {
133-
console.log(
132+
dlog(
134133
`Current newest version "${currentNewestVersion}" doesn't exist or is lesser than ${cleanVersion}, setting ${repo.repoOwner}/${repo.repoName} as final repo`
135134
);
136135
currentPackage = {
@@ -139,7 +138,7 @@ export async function getPackageReleases(
139138
};
140139
}
141140
}
142-
console.log("Done");
141+
dlog("Done");
143142
}
144143

145144
return currentPackage

0 commit comments

Comments
 (0)