Skip to content

Commit

Permalink
feat: add logs
Browse files Browse the repository at this point in the history
  • Loading branch information
phoebus-84 committed May 3, 2024
1 parent c750500 commit ca6d2e5
Show file tree
Hide file tree
Showing 12 changed files with 161 additions and 5 deletions.
14 changes: 14 additions & 0 deletions src/lib/components/molecules/HiddenLogsButton.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
<script lang="ts">
import { goto } from "$lib/i18n";
let clicked:number = 0;
const clicksNeeded = 5
const onClick = () => {
clicked++;
if (clicked === clicksNeeded) {
clicked = 0;
goto('/logs');
}
}
</script>
<button on:click={onClick} class="absolute left-1/2 top-0 z-50 h-6 w-20"></button>
16 changes: 16 additions & 0 deletions src/lib/hooks.client.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import { log } from '$lib/log';
import type { HandleClientError } from '@sveltejs/kit';

export const handleError: HandleClientError = async ({ error, event, status, message }) => {
await log(String(error))
await log(JSON.stringify(event))
await log(JSON.stringify(status));
await log(message)

return {
message,
status,
event,
error
};
};
29 changes: 29 additions & 0 deletions src/lib/log.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,29 @@
// import { dev } from '$app/environment';
import { setLogPreference } from './preferences/logs';

const dev = true;

export const log = dev ? logAndSave : () => {};

async function logAndSave(message: string) {
const stackTrace = new Error().stack;
let callerInfo = '';

if (stackTrace) {
const stackLines = stackTrace.split('\n');
for (let i = 2; i < stackLines.length; i++) {
const match = stackLines[i].match(/at\s+(.*)\s+\((.*):(\d+):(\d+)\)/);
if (match) {
const functionName = match[1];
const fileName = match[2]?.replace(/^.*\/\/[^/]+/, '');
const lineNumber = match[3];
const columnNumber = match[4];
callerInfo = `${functionName} (${fileName}:${lineNumber}:${columnNumber})`;
break;
}
}
}
const logMessage = callerInfo ? `${callerInfo}: ${message}` : message;
console.log(logMessage);
await setLogPreference(logMessage);
}
4 changes: 4 additions & 0 deletions src/lib/preferences/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,10 @@ export const removePreference = async (key: string) => {
await Preferences.remove({ key });
};

export const clearPreferences = async () => {
await Preferences.clear();
};

export const getStructuredPreferences = async <T>(key: string): Promise<T | undefined> => {
try {
const value = await getPreference(key);
Expand Down
40 changes: 40 additions & 0 deletions src/lib/preferences/logs.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,40 @@
import { getStructuredPreferences, setStructuredPreferences } from '.';
import dayjs from 'dayjs';

//

export const LOGS_PREFERENCES_KEY = 'logs';

export type Log = {
date: number;
message: string;
};

const getNow = async () => {
return dayjs().valueOf();
};

export async function setLogPreference(message: string): Promise<Log> {
const logs = await getLogsPreference();
const date = await getNow();
const c = {
message,
date
};
if (logs) {
logs.push(c);
await setStructuredPreferences(LOGS_PREFERENCES_KEY, logs);
return c;
}

await setStructuredPreferences(LOGS_PREFERENCES_KEY, [c]);
return c;
}

export async function getLogsPreference(): Promise<Log[] | undefined> {
return await getStructuredPreferences(LOGS_PREFERENCES_KEY);
}

export async function clearLogsPreferences(): Promise<void> {
await setStructuredPreferences(LOGS_PREFERENCES_KEY, []);
}
3 changes: 2 additions & 1 deletion src/lib/slangroom/login.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ import { Slangroom } from '@slangroom/core';
import { pocketbase } from '@slangroom/pocketbase';
import authenticate from './authenticate.zen?raw';
import { backendUri } from '$lib/backendUri';
import { log } from '$lib/log';

const slangroom = new Slangroom(pocketbase);

Expand All @@ -17,7 +18,7 @@ export const login = async (email: string, password: string) => {
const res = await slangroom.execute(authenticate, {data});
return res.result.output;
} catch (e: unknown) {
console.log(e);
log(e);
throw new Error(JSON.stringify(e));
}
};
3 changes: 2 additions & 1 deletion src/lib/slangroom/verificationFlows.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@ import { Slangroom } from '@slangroom/core';
import getPbList from '$lib/slangroom/getPbList.zen?raw';
import getPbRecord from '$lib/slangroom/getPbRecord.zen?raw';
import { pocketbase, type ShowRecordParameters } from '@slangroom/pocketbase';
import { log } from '$lib/log';

export type VerificationFlow = {
collectionId: string;
Expand Down Expand Up @@ -93,7 +94,7 @@ export const getVerificationFlow = async (id: string): Promise<VerificationFlow>
//@ts-expect-error output needs to be typed
return res.result?.output;
} catch (e: unknown) {
console.log(e);
log(JSON.stringify(e));
throw new Error(JSON.stringify(e));
}
};
2 changes: 2 additions & 0 deletions src/routes/+layout.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
import { ParaglideJS } from '@inlang/paraglide-js-adapter-sveltekit';
import { i18n } from '$lib/i18n';
import { removeOldRuAndSid } from '$lib/preferences/sidRu';
import HiddenLogsButton from '$lib/components/molecules/HiddenLogsButton.svelte';
document.addEventListener(
'deviceready',
Expand All @@ -38,6 +39,7 @@
</svelte:head>

<ParaglideJS {i18n}>
<HiddenLogsButton />
<ion-app>
<slot />
</ion-app>
Expand Down
3 changes: 2 additions & 1 deletion src/routes/[[lang]]/(protected)/[id]/verify/+page.svelte
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
import { backendUri } from '$lib/backendUri';
import { saveRuAndSid } from '$lib/preferences/sidRu';
import { jwsToId, jwsToIdSuccess } from './_lib/tools';
import { log } from '$lib/log';
export let data: any;
Expand Down Expand Up @@ -43,7 +44,7 @@
await PushNotifications.addListener('pushNotificationReceived', (notification) => {
incomingNotification = notification;
console.log('Push notification received: ', notification);
log(`Push notification received: /n ${JSON.stringify(notification)}`);
});
};
Expand Down
5 changes: 3 additions & 2 deletions src/routes/[[lang]]/(protected)/[id]/verify/_lib/tools.ts
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import { zencode } from '@slangroom/zencode';
import { getRuAndSid } from '$lib/preferences/sidRu';
import verify from '$lib/mobile_zencode/verifier/verify.zen?raw';
import verifyKeys from '$lib/mobile_zencode/verifier/verify.keys.json?raw';
import { log } from '$lib/log';

const slangroom = new Slangroom(http, helpers, zencode);
export const jwsToIdSuccess = 'Signature_verification_successful' as const;
Expand Down Expand Up @@ -33,11 +34,11 @@ export const jwsToId = async (jws: string): Promise<JwsToIdResponse> => {
claims_url: ru
};
const res = await slangroom.execute(verify, { data: dataVerify, keys: JSON.parse(verifyKeys) });
console.log(res);
log(JSON.stringify(res));
const message = res.result.result as typeof jwsToIdSuccess | typeof jwsToIdFailure;
return { message, id };
} catch (e) {
console.log(e);
log(JSON.stringify(e));
return {message:jwsToIdFailure, id}
}
};
41 changes: 41 additions & 0 deletions src/routes/logs/+page.svelte
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
<script lang="ts">
import { goto, r } from '$lib/i18n/index.js';
import dayjs from 'dayjs';
import { onMount } from 'svelte';
import { clearLogsPreferences } from '$lib/preferences/logs.js';
import { clearPreferences } from '$lib/preferences/index.js';
export let data;
let element: HTMLElement;
$: if (logs && element) scrollToBottom(element);
onMount(() => {
if (logs && element) scrollToBottom(element);
});
const scrollToBottom = async (node: HTMLElement) => {
node.scroll({ top: node.scrollHeight, behavior: 'smooth' });
};
const clear = async () => {
await clearLogsPreferences();
window.location.reload()
};
const { logs } = data;
</script>

<div class="ion-padding flex h-screen flex-col gap-4 overflow-auto" bind:this={element}>
<div class="flex gap-2">
<d-button href={r('/home')}> back </d-button>
<d-button on:click={clear}> clear </d-button>
<d-button on:click={clearPreferences}> clear storage </d-button>
</div>
{#if logs}
{#each logs as log}
{@const date = dayjs(log.date)}
<div class="flex gap-2 rounded-md border border-on bg-primary p-2">
<div class="flex flex-col">
<div class="text-sm text-on">{date.format('YY/MM/DD')}</div>
<div class="text-sm text-on">{date.format('HH:mm:ss')}</div>
</div>
<div class="break-all text-sm text-on">{log.message}</div>
</div>
{/each}
{/if}
</div>
6 changes: 6 additions & 0 deletions src/routes/logs/+page.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,6 @@
import { getLogsPreference } from '$lib/preferences/logs.js';

export const load = async () => {
const logs = await getLogsPreference() || [];
return { logs };
};

0 comments on commit ca6d2e5

Please sign in to comment.