Skip to content

Commit

Permalink
fixed: warning not showing in console when warning level is hard
Browse files Browse the repository at this point in the history
  • Loading branch information
butthx committed May 14, 2024
1 parent df7d906 commit 028318a
Show file tree
Hide file tree
Showing 13 changed files with 1,000 additions and 1,269 deletions.
23 changes: 23 additions & 0 deletions .github/workflows/publish-to-gh.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
name: Publish package to GitHub Packages
on:
release:
types: [published]
jobs:
build:
runs-on: ubuntu-latest
permissions:
contents: read
packages: write
steps:
- uses: actions/checkout@v4
# Setup .npmrc file to publish to GitHub Packages
- uses: actions/setup-node@v4
with:
node-version: '20.x'
registry-url: 'https://npm.pkg.github.com'
# Defaults to the user or organization that owns the workflow file
scope: '@tgsnake'
- run: yarn install
- run: npm publish --access public
env:
NODE_AUTH_TOKEN: ${{ secrets.GITHUB_TOKEN }}
3 changes: 1 addition & 2 deletions .npmrc
Original file line number Diff line number Diff line change
@@ -1,2 +1 @@
engine-strict=true
@tgsnake:registry=https://npm.pkg.github.com
engine-strict=true
893 changes: 0 additions & 893 deletions .yarn/releases/yarn-4.0.2.cjs

This file was deleted.

894 changes: 894 additions & 0 deletions .yarn/releases/yarn-4.2.2.cjs

Large diffs are not rendered by default.

2 changes: 1 addition & 1 deletion .yarnrc.yml
Original file line number Diff line number Diff line change
Expand Up @@ -6,4 +6,4 @@ enableGlobalCache: false

nodeLinker: node-modules

yarnPath: .yarn/releases/yarn-4.0.2.cjs
yarnPath: .yarn/releases/yarn-4.2.2.cjs
28 changes: 0 additions & 28 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -40,34 +40,6 @@ log.log('Hello World'); // (name) info - Hello World DD/MM/YY hh:mm:ss.ms
- `setWarningLevel` : Setting the warning level. `hard` if you want show the context in all log level, `soft` if you want show the context only in `warning` or `debug` or `verbose` level.
- `setFilters` : Setting any instance that can display context in the console or terminal.

## Capturing log

**The log capture feature is only available on node js and deno platforms, not available for browsers!**

To capture logs we use env as the trigger. When in the env have `CAPTURELOG` The capture function will automatically work and stop when the program is finished (`beforeExit`, `exit` event on node and `beforeunload`,`unload`, `unhadlerejection` event on deno) or when it is forced to stop due to an error.
The log will be captured in the form of a log file with filename format: `{name}-{Date.now()}.log` and will be saved in the current work dir (cwd).
Value of env `CAPTURELOG` is name of logger or can be `'all'` for each instance the logger runs the capture function.

### Example :

```env
CAPTURELOG=tgsnake
```

With the example above, only the instance named `tgsnake` performs the capture function.

```env
CAPTURELOG=all
```

With the example above, all of the instance logger will be performs the capture function.

You don't need to create an .env file, you can do it like this :

```bash
CAPTURELOG="all" node index.js
```

## Options

| parameter | type | description |
Expand Down
11 changes: 5 additions & 6 deletions package.json
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
{
"name": "@tgsnake/log",
"version": "1.6.2",
"version": "1.6.3",
"description": "logging framework for tgsnake",
"main": "./lib/index.js",
"devDependencies": {
"@types/node": "20.10.5",
"deno2node": "1.11.0",
"prettier": "3.1.1",
"ts-node": "10.9.2"
"@types/node": "20.12.12",
"deno2node": "1.12.0",
"prettier": "3.2.5"
},
"scripts": {
"build": "deno2node tsconfig.json",
Expand All @@ -26,7 +25,7 @@
"lib/**/**"
],
"license": "MIT",
"packageManager": "yarn@4.0.2",
"packageManager": "yarn@4.2.2",
"dependencies": {
"chalk": "4.1.2"
}
Expand Down
29 changes: 0 additions & 29 deletions src/Capture.ts

This file was deleted.

86 changes: 12 additions & 74 deletions src/Logger.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,19 +7,9 @@
* tgsnake is a free software : you can redistribute it and/or modify
* it under the terms of the MIT License as published.
*/
import {
type Chalk,
ChalkInstance,
inspect,
onEndProcess,
path,
cwd,
fs,
isBrowser,
} from './platform.deno.ts';
import { type Chalk, ChalkInstance, inspect, isBrowser } from './platform.deno.ts';
import { getLS, LocalStorage } from './LocalStorage.ts';
import { sendLog, formatColor } from './Utilities.ts';
import { Capture } from './Capture.ts';

export interface LoggerColor {
debug?: string;
Expand All @@ -44,8 +34,6 @@ export class Logger {
/** @ignore */
private _storage: LocalStorage = getLS();
/** @ignore */
private _captures: Capture = new Capture();
/** @ignore */
private _chalk: Chalk = new ChalkInstance({ level: 3 });
constructor(options: LoggerOptions = {}) {
options = Object.assign(
Expand Down Expand Up @@ -75,25 +63,23 @@ export class Logger {
},
options.customColor,
);
if (!isBrowser && this._storage.getItem('CAPTURELOG')) {
onEndProcess(
this.handleEventCapture(
this._captures,
this._storage,
this._name,
this._level.join(','),
this._storage.getItem('LOGWARNINGLEVEL') || 'hard',
this.isAllowed(),
),
);
}
}
/**
* @ignore
* Creating a log template.
*/
private template(level: string, ...args: Array<any>) {
let now = new Date();
if (isBrowser) {
return [
`%c(${this._name}) %c${level} - %c${'%o'.repeat(args.length)} %c${now.getDate()}/${now.getMonth() + 1}/${now.getFullYear()} ${now.getHours()}:${now.getMinutes()}:${now.getSeconds()}.${now.getMilliseconds()}`,
`color: ${this._color.name};`,
`color: ${this._color[level]};`,
``,
...args,
`color: ${this._color.date};`,
];
}
return [
formatColor(this._chalk, this._color.name!, `(${this._name})`),
formatColor(this._chalk, this._color[level], level),
Expand All @@ -118,50 +104,6 @@ export class Logger {
if (env.includes('all')) return true;
return env.includes(this._name);
}
/**
* @ignore
* Capture all log
*/
private capture(...args: Array<any>) {
if (!isBrowser && this._storage.getItem('CAPTURELOG')) {
const capturelog = (this._storage.getItem('CAPTURELOG') || 'all').split(',');
if (capturelog.includes('all') || capturelog.includes(this._name)) {
if (this._captures.length >= 500) {
this._captures.remove(0, 2);
}
this._captures.push(args.join(''));
}
}
}
/**
* @ignore
* Create a capture file when process is stoped
*/
private handleEventCapture(
captures: Capture,
storage: LocalStorage,
name: string,
level: string,
warningLevel: string,
isAllowed: boolean,
) {
return () => {
if (!isBrowser && storage.getItem('CAPTURELOG') && captures.length) {
const filename = path.join(
cwd(),
`${name.replace(/[/\\?%*:|"<>]/g, '-')}-${Date.now()}.log`,
);
fs.writeFileSync(
filename,
`Captured\t:\t${new Date()}\nLogger Name\t:\t${name}\nLog Level : ${level}\nWarning Level\t:\t${warningLevel}\nIs Allowed\t:\t${isAllowed}\n=============== CAPTURE BEGIN (ONLY 500 LAST LOG) ===============\n${captures.captures.join(
'\n',
)}`,
);
console.log(`Capture taken at : ${filename}`);
captures.clear();
}
};
}
/**
* @ignore
* Get the current log level
Expand Down Expand Up @@ -225,7 +167,6 @@ export class Logger {
* Create log without template and without levels.
*/
log(...args: Array<any>) {
this.capture(...args);
return sendLog(console.log, this.isAllowed(), ...args);
}
/**
Expand All @@ -245,7 +186,6 @@ export class Logger {
info(...args: Array<any>) {
let level: Array<TypeLogLevel> = ['info', 'debug', 'verbose'];
const prnt = this.template('info'!, ...args);
this.capture(...prnt);
for (let l of this._level) {
if (level.includes(l)) {
return sendLog(console.info, this.isAllowed(), ...prnt);
Expand All @@ -258,7 +198,6 @@ export class Logger {
error(...args: Array<any>) {
let level: Array<TypeLogLevel> = ['error', 'debug', 'verbose'];
const prnt = this.template('error'!, ...args);
this.capture(...prnt);
for (let l of this._level) {
if (level.includes(l)) {
return sendLog(console.error, this.isAllowed(), ...prnt);
Expand All @@ -271,10 +210,9 @@ export class Logger {
warning(...args: Array<any>) {
let level: Array<TypeLogLevel> = ['warning', 'debug', 'verbose'];
if (this._storage.getItem('LOGWARNINGLEVEL') === 'hard') {
level.concat(['none', 'info', 'error']);
level = level.concat(['none', 'info', 'error']);
}
const prnt = this.template('warning'!, ...args);
this.capture(...prnt);
for (let l of this._level) {
if (level.includes(l)) {
return sendLog(console.warn, this.isAllowed(), ...prnt);
Expand Down
11 changes: 2 additions & 9 deletions src/platform.deno.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,13 +9,6 @@
*/

import { Chalk } from 'https://deno.land/x/[email protected]/source/index.js';
import * as path from 'node:path';
import * as fs from 'node:fs';
export const { inspect, cwd } = Deno;
export { type Chalk, Chalk as ChalkInstance, path, fs };
export function onEndProcess(cb: { (e?: any): any }) {
globalThis.addEventListener('beforeunload', cb);
globalThis.addEventListener('unload', cb);
globalThis.addEventListener('unhandledrejection', cb);
}
export const { inspect } = Deno;
export { type Chalk, Chalk as ChalkInstance };
export const isBrowser = !('Deno' in globalThis);
9 changes: 1 addition & 8 deletions src/platform.node.ts
Original file line number Diff line number Diff line change
Expand Up @@ -8,13 +8,6 @@
* it under the terms of the MIT License as published.
*/
import { type Chalk, Instance } from 'chalk';
import * as path from 'node:path';
import * as fs from 'node:fs';
export { inspect } from 'util';
export { type Chalk, Instance as ChalkInstance, path, fs };
export function onEndProcess(cb: { (e?: any): any }) {
process.on('beforeExit', cb);
process.on('exit', cb);
}
export const { cwd } = process;
export { type Chalk, Instance as ChalkInstance };
export const isBrowser = typeof window !== 'undefined';
2 changes: 1 addition & 1 deletion test/index.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import { Logger } from '../src/index.ts';
const log = new Logger({
level: ['warning', 'info'],
level: ['error', 'info'],
});

for (let i = 0; i < 20; i++) {
Expand Down
Loading

0 comments on commit 028318a

Please sign in to comment.