Skip to content

Commit

Permalink
Merge pull request #77 from AliMD/feat/refactor-log
Browse files Browse the repository at this point in the history
Complete refactor logger and fix all packages type issues
  • Loading branch information
alimd authored Mar 11, 2022
2 parents f1dbb5e + 67d82c1 commit db69818
Show file tree
Hide file tree
Showing 18 changed files with 485 additions and 194 deletions.
33 changes: 29 additions & 4 deletions demo/logger/index.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,32 @@
import {createLogger} from '@vatr/logger';

const log = createLogger('loggerScope', 'info');
const error = createLogger('loggerScope', 'error', true);
const logger = createLogger('logger/demo', 'green');

log('Hello ;)');
error('Err: Hello ;) - Forced to log');
console.debug('--- logger.logProperty ---');
logger.logProperty('name', 'ali');
logger.logProperty('options', {a: 1, b: 2});

console.debug('--- logger.logMethod ---');
logger.logMethod('myMethod');

console.debug('--- logger.logMethodArgs ---');
logger.logMethodArgs('myMethod', {a: 1, b: 2});

console.debug('--- logger.logMethodFull ---');
logger.logMethodFull('add', {a: 1, b: 2}, 3);

console.debug('--- logger.incident ---');
logger.incident('myMethod', 'abort_signal', 'Aborted signal received', {url: '/test.json'});

console.debug('--- logger.accident ---');
logger.accident('myMethod', 'file_not_found', 'Url requested return 404 not found', {url: '/test.json'});

console.debug('--- logger.logOther ---');
logger.logOther('foo:', 'bar', {a: 1});

console.debug('--- logger.error ---');
try {
throw new Error('my_error_message');
} catch (err) {
logger.error('myMethod', 'error_code', (err as Error).stack || err, {a: 1, b: 2});
}
8 changes: 4 additions & 4 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -31,15 +31,15 @@
"publish": "lerna publish from-package"
},
"devDependencies": {
"@typescript-eslint/eslint-plugin": "^5.12.1",
"@typescript-eslint/parser": "^5.12.1",
"@typescript-eslint/eslint-plugin": "^5.14.0",
"@typescript-eslint/parser": "^5.14.0",
"@web/dev-server": "^0.1.30",
"eslint": "^8.9.0",
"eslint": "^8.10.0",
"eslint-config-google": "^0.14.0",
"eslint-plugin-wc": "^1.3.2",
"lerna": "^4.0.0",
"npm-run-all": "^4.1.5",
"ts-lit-plugin": "^1.2.1",
"typescript": "^4.5.5"
"typescript": "^4.6.2"
}
}
19 changes: 12 additions & 7 deletions package/fetch/src/fetch.ts
Original file line number Diff line number Diff line change
@@ -1,7 +1,6 @@
import {createLogger, vatrRegisteredList} from '@vatr/logger';

const log = createLogger('vatr/fetch');
// const error = createLogger('vatr/fetch', 'error', true);
const logger = createLogger('vatr/fetch');

vatrRegisteredList.push({
name: '@vatr/fetch',
Expand Down Expand Up @@ -34,9 +33,10 @@ export interface FetchOptions extends RequestInit
* @example const response = await fetch(url, {jsonResponse: false});
*/
export function fetch(url: string, options?: FetchOptions): Promise<Response> {
log('fetch', url, options);
logger.logMethodArgs('fetch', {url, options});

if (!navigator.onLine) {
logger.accident('fetch', 'abort_signal', 'abort signal received', {url});
throw new Error('fetch_offline');
}

Expand All @@ -60,8 +60,10 @@ export function fetch(url: string, options?: FetchOptions): Promise<Response> {

if (options.bodyObject != null) {
options.body = JSON.stringify(options.bodyObject);
options.headers ??= {};
options.headers['Content-Type'] = 'application/json';
options.headers = {
...options.headers,
'Content-Type': 'application/json',
};
}

// @TODO: AbortController polyfill
Expand All @@ -74,11 +76,11 @@ export function fetch(url: string, options?: FetchOptions): Promise<Response> {
});
}
abortController.signal.addEventListener('abort', () => {
log('fetch: aborted %s', abortController.signal.reason);
logger.incident('fetch', 'abort_signal', 'abort signal received', {url, reason: abortController.signal.reason});
});
options.signal = abortController.signal;

const timeoutId = setTimeout(() => abortController.abort(), options.timeout);
const timeoutId = setTimeout(() => abortController.abort('fetch_timeout'), options.timeout);

// @TODO: browser fetch polyfill
const response = window.fetch(url, options);
Expand All @@ -96,6 +98,7 @@ export function getData(
queryParameters?: Record<string | number, string | number | boolean>,
options?: FetchOptions,
): Promise<Response> {
logger.logMethodArgs('getData', {url, queryParameters, options});
return fetch(url, {
queryParameters,
...options,
Expand All @@ -112,6 +115,7 @@ export async function getJson<ResponseType extends Record<string | number, unkno
queryParameters?: Record<string | number, string | number | boolean>,
options?: FetchOptions,
): Promise<ResponseType> {
logger.logMethodArgs('getJson', {url, queryParameters, options});
const response = await getData(url, queryParameters, options);

if (!response.ok) {
Expand All @@ -131,6 +135,7 @@ export function postData(
body: Record<string | number, unknown>,
options?: FetchOptions,
): Promise<Response> {
logger.logMethodArgs('postData', {url, body, options});
return fetch(url, {
method: 'POST',
bodyObject: body,
Expand Down
10 changes: 7 additions & 3 deletions package/i18n/src/core.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,7 @@ import {addSignalListener, requestSignal, setSignalProvider, waitForSignal} from
import {getJson} from '@vatr/fetch';
import type {I18nOptions, L10Resource} from './type';

export const log = createLogger('vatr/i18n');
export const error = createLogger('vatr/i18n', 'error', true);
export const logger = createLogger('vatr/i18n');

vatrRegisteredList.push({
name: '@vatr/i18n',
Expand All @@ -21,16 +20,19 @@ const loadingStr = '…';

let l10nResource: L10Resource;
addSignalListener('l10n-resource-change', (resource) => {
logger.logMethodArgs('l10nResourceChanged', {resource});
l10nResource = resource;
});

addSignalListener('local-change', (local) => {
logger.logMethodArgs('localChanged', {local});
if (configuration.autoFetchResources) requestSignal('l10n-resource-change', local);
document.documentElement.setAttribute('lang', local.code);
document.documentElement.setAttribute('dir', local.direction);
});

setSignalProvider('l10n-resource-change', async (local): Promise<L10Resource | void> => {
logger.logMethodArgs('l10nResourceProvider', {local});
const current = await waitForSignal('local-change', true);
if (current.code !== local.code) {
return await getJson<L10Resource>(`${configuration.resourcePath}/${local.code}.json`);
Expand All @@ -43,10 +45,12 @@ setSignalProvider('l10n-resource-change', async (local): Promise<L10Resource | v
* Localize a String_Key from the localization resource.
*/
export function _localize(key: string): string {
key = key.trim();
if (key === '') return '';
if (l10nResource == null) return loadingStr;
const localized = l10nResource[key];
if (localized == null) {
error('%s not found!', key);
logger.accident('localize', 'l10n_key_not_found', 'Key not defined in the localization resource', {key});
return `(${key})`;
}
return localized;
Expand Down
17 changes: 8 additions & 9 deletions package/i18n/src/i18n.ts
Original file line number Diff line number Diff line change
@@ -1,15 +1,16 @@
import {dispatchSignal, hasSignalDispatchedBefore} from '@vatr/signal';
import {log, _localize, configuration} from './core';
import {logger, _localize, configuration} from './core';
import type {I18nOptions} from './type';

/**
* Initial and config the internationalization.
*/
export function initialI18n(options?: I18nOptions): void {
log('initialI18n: %o', options);
export function initialI18n(options?: Partial<I18nOptions>): void {
logger.logMethodArgs('initialI18n', {options});
for (const key in options) {
if (Object.prototype.hasOwnProperty.call(options, key)) {
configuration[key] = options[key];
// WTF, mastmalize type.
(configuration[key as keyof I18nOptions] as unknown) = options[key as keyof I18nOptions] as unknown;
}
}

Expand All @@ -29,7 +30,7 @@ export function initialI18n(options?: I18nOptions): void {
* return null if the key is null or undefined (for optional input).
*
* @example
* localize('Hello_World'); // Hello world!
* localize('hello_world'); // Hello world!
*/
export function localize(key?: null): null;
/**
Expand All @@ -42,7 +43,7 @@ export function localize(key?: null): null;
* return null if the key is null or undefined (for optional input).
*
* @example
* localize('Hello_World'); // Hello world!
* localize('hello_world'); // Hello world!
*/
export function localize(key: string): string;
/**
Expand All @@ -55,13 +56,11 @@ export function localize(key: string): string;
* return null if the key is null or undefined (for optional input).
*
* @example
* localize('Hello_World'); // Hello world!
* localize('hello_world'); // Hello world!
*/
export function localize(key?: string | null): string | null;

export function localize(key?: string | null): string | null {
if (key == null) return null;
key = key.trim();
if (key === '') return '';
return _localize(key);
}
36 changes: 33 additions & 3 deletions package/logger/README.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,9 +4,39 @@ Fancy colorful console debugger with custom scope written in tiny TypeScript, ES

## Example usage

```js
```ts
import { createLogger } from 'https://esm.run/@vatr/logger';

const log = createLogger('my-scope', 'debug', true);
log('foo');
const logger = createLogger('demo');

function sayHello (name: string) {
logger.logMethodArgs('sayHello', {name});
}
```

### Debug Mode

Many of the methods in the logger are no-ops when the debug mode is off.
Please remember to **reload** the window after changing the debug mode.

- Debugging all scopes

```ts
window.localStorage?.setItem('VATR_LOG', '*');
```

- Debugging specific scope

```ts
window.localStorage?.setItem('VATR_LOG', 'scope_name');
```

- Debugging some scopes with pattern

```ts
window.localStorage?.setItem('VATR_LOG', '*vatr*');
```

### API

@TODO: update me from [type.ts](./src/type.ts)
Loading

0 comments on commit db69818

Please sign in to comment.