itivrutaha 2.0.14 → 3.0.0-beta.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/bun.lockb ADDED
Binary file
@@ -0,0 +1,48 @@
1
+ import chalk from 'chalk'
2
+ import { itivrutaha } from '../dist/index.js'
3
+
4
+ const log = itivrutaha({
5
+ theme: `:time ${chalk.gray.dim('•')} :scope :emoji :type :msg :data`,
6
+ timeFormat: 'hh:mm:ss dd-MM-yyyy',
7
+ scopes: [
8
+ {
9
+ name: 'app',
10
+ color: chalk.redBright
11
+ },
12
+ {
13
+ name: 'web',
14
+ color: chalk.cyanBright
15
+ }
16
+ ],
17
+ types: [
18
+ {
19
+ name: 'error',
20
+ emoji: 'x',
21
+ color: chalk.redBright
22
+ },
23
+ {
24
+ name: 'warning',
25
+ emoji: 'construction',
26
+ color: chalk.yellowBright
27
+ }
28
+ ]
29
+ })
30
+
31
+ log.error('a simple error message')
32
+ log.warning('a simple warning message', {
33
+ hello: {
34
+ works: false,
35
+ some: 'wow!'
36
+ },
37
+ world: 'šŸŽŠ'
38
+ })
39
+
40
+ log.error({
41
+ msg: 'hellow rold',
42
+ scope: 'app'
43
+ })
44
+
45
+ log.warning({
46
+ msg: 'wow!',
47
+ scope: 'web'
48
+ })
package/package.json CHANGED
@@ -1,16 +1,16 @@
1
1
  {
2
2
  "name": "itivrutaha",
3
- "description": "( ą¤‡ą¤¤ą¤æą¤µą„ƒą¤¤ą„ą¤¤ą¤ƒ ) — Logging system āœ for Node.js with šŸ¬ theming and file šŸ—ƒ logging support.",
4
- "version": "2.0.14",
3
+ "description": "",
4
+ "version": "3.0.0-beta.1",
5
5
  "license": "MIT",
6
6
  "type": "module",
7
- "main": "dist/itivrutaha.js",
7
+ "main": "dist/index.js",
8
8
  "homepage": "https://github.com/vsnthdev/itivrutaha#readme",
9
9
  "bugs": "https://github.com/vsnthdev/itivrutaha/issues",
10
10
  "author": {
11
- "name": "Vasanth Srivatsa",
12
- "email": "vasanth@vasanthdeveloper.com",
13
- "url": "https://vsnth.dev"
11
+ "email": "hey@vsnth.dev",
12
+ "url": "https://vsnth.dev",
13
+ "name": "Vasanth Srivatsa"
14
14
  },
15
15
  "repository": {
16
16
  "type": "git",
@@ -18,51 +18,18 @@
18
18
  },
19
19
  "scripts": {
20
20
  "dev": "tsc --watch",
21
- "build": "rimraf ./dist && tsc --incremental false",
22
- "docs": "rimraf docs/ && node scripts/docs.js",
23
- "clean": "rimraf dist"
21
+ "clean": "rimraf dist",
22
+ "build": "rimraf dist && tsc"
24
23
  },
25
- "keywords": [
26
- "cli",
27
- "tty",
28
- "log",
29
- "logs",
30
- "shell",
31
- "logger",
32
- "logging",
33
- "terminal",
34
- "command-line"
35
- ],
36
24
  "dependencies": {
37
- "chalk": "^5.0.1",
38
- "clear-terminal-line": "^0.0.1",
39
- "deepmerge": "^4.2.2",
40
- "del": "^7.0.0",
41
- "env-paths": "^3.0.0",
42
- "joi": "^17.6.0",
43
- "luxon": "^3.0.1",
44
- "mkdirp": "^1.0.4",
45
- "node-cleanup": "^2.1.2",
46
- "node-emoji": "^1.11.0",
47
- "read-pkg-up": "^9.1.0",
48
- "strip-ansi": "^7.0.1"
25
+ "chalk": "^5.3.0",
26
+ "cli-highlight": "^2.1.11",
27
+ "date-format": "^4.0.14",
28
+ "node-emoji": "^2.1.3"
49
29
  },
50
30
  "devDependencies": {
51
- "@types/luxon": "^3.0.0",
52
- "@types/mkdirp": "^1.0.2",
53
- "@types/node": "^18.6.1",
54
- "@types/node-cleanup": "^2.1.2",
55
- "@types/node-emoji": "^1.8.1",
56
- "@typescript-eslint/eslint-plugin": "^5.30.7",
57
- "@typescript-eslint/parser": "^5.30.7",
58
- "es-dirname": "^0.1.0",
59
- "eslint": "^8.20.0",
60
- "eslint-config-prettier": "^8.5.0",
61
- "eslint-plugin-import": "^2.26.0",
62
- "eslint-plugin-prettier": "^4.2.1",
63
- "eslint-plugin-simple-import-sort": "^7.0.0",
64
- "prettier": "^2.7.1",
65
- "rimraf": "^3.0.2",
66
- "typescript": "^4.7.4"
31
+ "@types/node": "^20.10.6",
32
+ "rimraf": "^5.0.5",
33
+ "typescript": "^5.3.3"
67
34
  }
68
- }
35
+ }
package/src/index.ts ADDED
@@ -0,0 +1,6 @@
1
+ /*
2
+ * Entryfile for itivrutaha logging module.
3
+ * Created On 29 October 2023
4
+ */
5
+
6
+ export { itivrutaha } from './itivrutaha.js'
@@ -0,0 +1,46 @@
1
+ /*
2
+ * Contains an exportable logger function.
3
+ * Created On 29 October 2023
4
+ */
5
+
6
+ import { ChalkInstance } from "chalk"
7
+ import { render } from "./renderer.js"
8
+
9
+ export interface IScope<ScopeName> {
10
+ name: ScopeName
11
+ color: ChalkInstance
12
+ }
13
+
14
+ export interface LogType<Name> {
15
+ name: Name
16
+ emoji: string
17
+ color: ChalkInstance
18
+ }
19
+
20
+ export interface Config<ScopeName, LogTypeName> {
21
+ theme: string
22
+ timeFormat: string
23
+ scopes: IScope<ScopeName>[]
24
+ types: LogType<LogTypeName>[]
25
+ }
26
+
27
+ export interface UnifiedData<ScopeName> {
28
+ scope?: ScopeName
29
+ msg: string
30
+ [key: string]: any
31
+ }
32
+
33
+ export function itivrutaha<Scope extends string, LogTypeName extends string>(config: Config<Scope, LogTypeName>) {
34
+ type Types = typeof config['types'][0]['name']
35
+ type Signature = (msgOrData: string | UnifiedData<Scope>, data?: any, scope?: Scope) => void
36
+
37
+ type ReturnSignature = {
38
+ [Type in Types]: Signature
39
+ }
40
+
41
+ // return all the log functions
42
+ return config.types.reduce((previous, current) => ({
43
+ ...previous,
44
+ [current.name]: render(config, current)
45
+ }), {}) as ReturnSignature
46
+ }
@@ -0,0 +1,43 @@
1
+ /*
2
+ * Renders a single log line by consuming an object.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import { filterObject } from './utilts.js';
7
+ import { Config, LogType, UnifiedData } from './itivrutaha.js'
8
+ import { emojify } from 'node-emoji';
9
+ import * as variables from './variables/index.js'
10
+
11
+ function line<ScopeName, LogTypeName extends string>(config: Config<ScopeName, LogTypeName>, type: LogType<LogTypeName>, msg: string, scopeName?: ScopeName, data?: any) {
12
+ // filter internal keys from data
13
+ if (data) data = filterObject(data, ['msg', 'scope'])
14
+
15
+ console.log(
16
+ config.theme
17
+ .replace(/:time/g, variables.time(config))
18
+ .replace(/:scope/g, variables.scope(config, scopeName))
19
+ .replace(/:emoji/g, variables.emoji(type))
20
+ .replace(/:type/g, variables.type(type))
21
+ .replace(/:msg/g, emojify(msg))
22
+ .replace(/:data/g, variables.data(data))
23
+ )
24
+ }
25
+
26
+ export function render<ScopeName, LogTypeName extends string>(config: Config<ScopeName, LogTypeName>, type: LogType<LogTypeName>) {
27
+ // consume all the log objects
28
+
29
+ return (msgOrData: string | UnifiedData<ScopeName>, data?: any, scope?: ScopeName) => {
30
+ // determine whether we're using unified data or seperate arguments
31
+ if (typeof msgOrData == 'string') {
32
+ // seperate arguments
33
+ line(config, type, msgOrData, scope, data)
34
+ } else {
35
+ // unified data
36
+ // ensure scope & data are not given in both placces
37
+ if (scope) throw Error(`Specifying scope as argument is not allowed`)
38
+ if (data) throw Error(`Specifying data separately is not allowed`)
39
+
40
+ line(config, type, msgOrData.msg, msgOrData.scope, msgOrData)
41
+ }
42
+ }
43
+ }
package/src/utilts.ts ADDED
@@ -0,0 +1,10 @@
1
+ /*
2
+ * Contains small utility functions used across this project.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ export function filterObject(obj: Record<string, any>, keysToExclude: string[]): Record<string, any> {
7
+ return Object.fromEntries(
8
+ Object.entries(obj).filter(([key]) => !keysToExclude.includes(key))
9
+ )
10
+ }
@@ -0,0 +1,40 @@
1
+ /*
2
+ * Renders the ":data" variable.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import chalk from 'chalk'
7
+ import { highlight } from 'cli-highlight'
8
+
9
+ function formatJSON(data: any) {
10
+ return JSON.stringify(data)
11
+ .replace(/{"/g, '{ "')
12
+ .replace(/"}/g, '" }')
13
+ .replace(/,"/g, ", \"")
14
+ .replace(/":/g, '": ')
15
+ }
16
+
17
+ export function data(input: any) {
18
+ if (!input) return ''
19
+
20
+ let str = ''
21
+
22
+ for (const key in input) {
23
+ const value = input[key]
24
+ const keyBlock = `${chalk.cyanBright(key)}${chalk.whiteBright('=')}`
25
+
26
+
27
+ if (typeof value == 'object') {
28
+ str = str.concat(keyBlock).concat(highlight(formatJSON(value), {
29
+ language: 'json',
30
+ ignoreIllegals: true,
31
+ })).concat(' ')
32
+ } else if (typeof value == 'string') {
33
+ str = str.concat(keyBlock).concat(chalk.magentaBright(value)).concat(' ')
34
+ } else {
35
+ str = str.concat(keyBlock).concat(chalk.magentaBright(JSON.stringify(value))).concat(' ')
36
+ }
37
+ }
38
+
39
+ return str.trim()
40
+ }
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Renders the ":emoji" variable if an emoji is specified.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import { get } from "node-emoji";
7
+ import { type LogType } from '../itivrutaha.js';
8
+
9
+ export function emoji<LogTypeName extends string>(type: LogType<LogTypeName>) {
10
+ return get(type.emoji)
11
+ }
@@ -0,0 +1,10 @@
1
+ /*
2
+ * Exports all render functions neatly as single package.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ export * from './time.js'
7
+ export * from './type.js'
8
+ export * from './data.js'
9
+ export * from './emoji.js'
10
+ export * from './scope.js'
@@ -0,0 +1,11 @@
1
+ /*
2
+ * Renders ":scope" variable with the current log line's scope.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import { Config } from "../itivrutaha.js"
7
+
8
+ export function scope<ScopeName, LogTypeName extends string>(config: Config<ScopeName, LogTypeName>, scopeName?: ScopeName) {
9
+ const scope = scopeName ? config.scopes.find(sco => sco.name == scopeName) : config.scopes[0]
10
+ return scope.color(scope.name)
11
+ }
@@ -0,0 +1,12 @@
1
+ /*
2
+ * Renders the ":time" variable printing current time.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import chalk from 'chalk'
7
+ import { Config } from "../itivrutaha.js"
8
+ import format from 'date-format'
9
+
10
+ export function time<ScopeName, LogTypeName extends string>(config: Config<ScopeName, LogTypeName>) {
11
+ return chalk.gray.dim(format.asString(config.timeFormat))
12
+ }
@@ -0,0 +1,10 @@
1
+ /*
2
+ * Renders the ":type" variable.
3
+ * Created On 15 January 2024
4
+ */
5
+
6
+ import { LogType } from "../itivrutaha.js";
7
+
8
+ export function type<LogTypeName extends string>(type: LogType<LogTypeName>) {
9
+ return type.color(type.name)
10
+ }
package/tsconfig.json ADDED
@@ -0,0 +1,19 @@
1
+ {
2
+ "compileOnSave": true,
3
+ "compilerOptions": {
4
+ "newLine": "LF",
5
+ "outDir": "dist/",
6
+ "target": "ESNext",
7
+ "declaration": true,
8
+ "incremental": false,
9
+ "module": "NodeNext",
10
+ "alwaysStrict": true,
11
+ "removeComments": true,
12
+ "esModuleInterop": true,
13
+ "preserveConstEnums": true,
14
+ "moduleResolution": "NodeNext"
15
+ },
16
+ "include": [
17
+ "src"
18
+ ]
19
+ }
package/LICENSE.md DELETED
@@ -1,9 +0,0 @@
1
- ## MIT License
2
-
3
- Copyright Ā© 2019 Vasanth Developer.
4
-
5
- Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
6
-
7
- The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
8
-
9
- THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md DELETED
@@ -1,82 +0,0 @@
1
- <h5 align="center">
2
- <img src="https://github.com/vasanthdeveloper/itivrutaha/blob/designs/header.png?raw=true" alt="itivrutaha">
3
- </h5>
4
- <p align="center"><strong>( ą¤‡ą¤¤ą¤æą¤µą„ƒą¤¤ą„ą¤¤ą¤ƒ ) — Logging system āœ for Node.js with šŸ¬ theming and file šŸ—ƒ logging support.</strong></p>
5
- <p align="center">
6
- <a target="_blank" rel="noopener" href="https://www.npmjs.com/package/itivrutaha">
7
- <img src="https://img.shields.io/npm/v/itivrutaha.svg?style=flat-square" alt="">
8
- </a>
9
- <a target="_blank" rel="noopener" href="https://www.npmjs.com/package/itivrutaha?activeTab=versions">
10
- <img src="https://img.shields.io/npm/dm/itivrutaha.svg?style=flat-square" alt="">
11
- </a>
12
- <a href="https://github.com/vasanthdeveloper/itivrutaha/issues">
13
- <img src="https://img.shields.io/github/issues/vasanthdeveloper/itivrutaha.svg?style=flat-square" alt="">
14
- </a>
15
- <a href="https://github.com/vasanthdeveloper/itivrutaha/commits/main">
16
- <img src="https://img.shields.io/github/last-commit/vasanthdeveloper/itivrutaha.svg?style=flat-square"
17
- alt="">
18
- </a>
19
- </p>
20
- <br>
21
-
22
- <!-- header -->
23
-
24
- **itivrutaha** is my first ever JavaScript (initially) project. It is a console logging module for Node.js to be used in CLIs, GUI desktop frameworks (like <a href="https://github.com/electron/electron" target="_blank" rel="noopener">Electron</a> & <a href="https://github.com/nodegui/nodegui" target="_blank" rel="noopener">NodeGUI</a>) and for web servers.
25
-
26
- > Tweet me <a target="_blank" rel="noopener" href="https://vas.cx/twitter">@vsnthdev</a>, I would love to know your opinion/experience on this project šŸ˜
27
-
28
- ## āš”ļø Features
29
-
30
- 1. Save logs to files
31
- 2. Create multiple loggers with context
32
- 3. Flexible theming support with <a href="https://www.npmjs.com/package/chalk" target="_blank" rel="noopener">chalk</a>
33
- 4. Terminal emoji support
34
- 5. Written in TypeScript
35
-
36
- ## šŸ’æ Installation
37
- <a href="https://www.npmjs.com/package/itivrutaha"><img src="https://nodei.co/npm/itivrutaha.png?downloads=true&downloadRank=true&stars=true" alt="npm module badge"></a>
38
- ```
39
- npm i itivrutaha
40
- ```
41
-
42
- ## šŸš“ā€ā™‚ļø Quick Start
43
- After installing `itivrutaha` using the above commands, you can use it in the following way:
44
-
45
- ```javascript
46
- import itivrutaha from 'itivrutaha'
47
-
48
- // create a new instance of the logger
49
- const logger = await itivrutaha.createNewLogger({
50
- // optional configuration
51
- })
52
-
53
- // examples of logging with itivrutaha
54
- logger.error('Ouch!')
55
- logger.note('Point to be noted')
56
- logger.okay('Not an info message')
57
- logger.success('Makes users happy')
58
- logger.info('Nice to know something is happening')
59
- logger.verbose("Always makes developer's life easy")
60
- ```
61
-
62
- To know more configuration options like **file logging**, **themes**, and **time formatting** see the [customization page](docs/Customization.md).
63
-
64
- ## šŸ›  Building
65
-
66
- * `npm install` — Installs all dependencies.
67
- * `npm run dev` — Builds TypeScript and docs automatically upon save.
68
- * `npm run build` — Deletes existing build files & freshly compiles TypeScript code.
69
- * `npm run docs` — Deletes existing docs and freshly builds by reading code.
70
-
71
- **Note:** Run `node examples/index.js` to test `itivrutaha` with the latest code.
72
-
73
- <!-- footer -->
74
-
75
- ## šŸ“° License
76
- > The **itivrutaha** project is released under the [MIT license](https://github.com/vasanthdeveloper/itivrutaha/blob/main/LICENSE.md). <br> Developed &amp; maintained By Vasanth Srivatsa. Copyright 2022 Ā© Vasanth Developer.
77
- <hr>
78
-
79
- > <a href="https://vsnth.dev" target="_blank" rel="noopener">vsnth.dev</a> &nbsp;&middot;&nbsp;
80
- > YouTube <a href="https://vas.cx/videos" target="_blank" rel="noopener">@vasanthdeveloper</a> &nbsp;&middot;&nbsp;
81
- > Twitter <a href="https://vas.cx/twitter" target="_blank" rel="noopener">@vsnthdev</a> &nbsp;&middot;&nbsp;
82
- > Discord <a href="https://vas.cx/discord" target="_blank" rel="noopener">Vasanth Developer</a>
@@ -1,13 +0,0 @@
1
- import { ConfigImpl, DataImpl } from '../config.js';
2
- export declare class Logger {
3
- config: ConfigImpl;
4
- data: DataImpl;
5
- constructor(config: ConfigImpl, data: DataImpl);
6
- success: (msg: string) => void;
7
- note: (msg: string) => void;
8
- info: (msg: string) => void;
9
- okay: (msg: string) => void;
10
- warning: (msg: string | Error) => void;
11
- error: (msg: string | Error, exitCode?: number) => void;
12
- verbose: (msg: string) => void;
13
- }
@@ -1,36 +0,0 @@
1
- /*
2
- * This class which holds all the log functions.
3
- * Created On 11 October 2019
4
- */
5
- import { configSchema } from '../config.js';
6
- import lifecycle from './lifecycle.js';
7
- import render from './wrapper.js';
8
- export class Logger {
9
- // constructor() executes when the class is initialized
10
- constructor(config, data) {
11
- this.success = (msg) => render({ msg, config: this.config, data: this.data });
12
- this.note = (msg) => render({ msg, config: this.config, data: this.data });
13
- this.info = (msg) => render({ msg, config: this.config, data: this.data });
14
- this.okay = (msg) => render({ msg, config: this.config, data: this.data });
15
- this.warning = (msg) => render({ msg, config: this.config, data: this.data });
16
- this.error = (msg, exitCode) => render({ msg, config: this.config, data: this.data, exitCode });
17
- // verbose() will only log the message
18
- // when a flag/command/option is found in the
19
- // command-line arguments
20
- this.verbose = (msg) => render({
21
- msg,
22
- config: this.config,
23
- data: this.data,
24
- condition: () => this.config.verboseIdentifier.some(argument => process.argv.includes(argument)),
25
- });
26
- const valid = configSchema.validate(config);
27
- if (valid.error)
28
- throw new Error(`itivrutaha was misconfigured: ${valid.error.message}`);
29
- // make the config globally relative accessible
30
- this.config = valid.value;
31
- this.data = data;
32
- // log a message that the the application has
33
- // started/stopped as per user's request
34
- lifecycle(valid.value, data);
35
- }
36
- }
@@ -1,3 +0,0 @@
1
- import { ConfigImpl, DataImpl } from '../config';
2
- declare const _default: (config: ConfigImpl, data: DataImpl) => void;
3
- export default _default;
@@ -1,65 +0,0 @@
1
- /*
2
- * Logs when application starts or stops.
3
- * Created On 15 April 2021
4
- */
5
- import ctl from 'clear-terminal-line';
6
- import { DateTime } from 'luxon';
7
- import cleanup from 'node-cleanup';
8
- import { close } from './log.js';
9
- import render from './wrapper.js';
10
- const startup = (config, data) => {
11
- render({
12
- data,
13
- config,
14
- msg: `${config.appName} startup`,
15
- type: 'note',
16
- condition: () => config.bootLog,
17
- });
18
- render({
19
- data,
20
- config,
21
- msg: `Started on ${DateTime.local().toFormat('hh:mm:ss a, LLL dd yyyy')}`,
22
- type: 'info',
23
- condition: () => config.bootLog,
24
- });
25
- };
26
- const shutdown = (config, data, signal) => {
27
- const now = DateTime.local().diff(data.startedOn, [
28
- 'days',
29
- 'hours',
30
- 'minutes',
31
- 'seconds',
32
- 'milliseconds',
33
- ]);
34
- const time = [];
35
- now.days && time.push(`${Math.round(now.days)} days`);
36
- now.hours && time.push(`${Math.round(now.hours)} hours`);
37
- now.minutes && time.push(`${Math.round(now.minutes)} minutes`);
38
- now.seconds && time.push(`${Math.round(now.seconds)} seconds`);
39
- now.milliseconds && time.push(`${Math.round(now.milliseconds)} ms`);
40
- if (signal == 'SIGINT' && config.clearOnSIGINT) {
41
- ctl();
42
- process.stdout.write('\r');
43
- }
44
- render({
45
- data,
46
- config,
47
- msg: `Bye šŸ‘‹ ran for ${time.slice(-3).join(', ')}`,
48
- type: 'info',
49
- condition: () => config.shutdownLog,
50
- });
51
- render({
52
- data,
53
- config,
54
- msg: `${config.appName} shutdown`,
55
- type: 'note',
56
- condition: () => config.shutdownLog,
57
- });
58
- close(true, data);
59
- };
60
- export default (config, data) => {
61
- startup(config, data);
62
- cleanup((exitCode, signal) => {
63
- shutdown(config, data, signal);
64
- });
65
- };
@@ -1,5 +0,0 @@
1
- import { ConfigImpl, DataImpl } from '../config';
2
- export declare const close: (close: boolean, data: DataImpl) => Promise<void>;
3
- export declare const open: (config: ConfigImpl) => Promise<DataImpl>;
4
- declare const _default: (log: string, type: string, config: ConfigImpl, data: DataImpl) => Promise<void>;
5
- export default _default;
package/dist/class/log.js DELETED
@@ -1,60 +0,0 @@
1
- /*
2
- * Handles writing log files.
3
- * Created On 15 April 2021
4
- */
5
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
6
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7
- return new (P || (P = Promise))(function (resolve, reject) {
8
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11
- step((generator = generator.apply(thisArg, _arguments || [])).next());
12
- });
13
- };
14
- import paths from 'env-paths';
15
- import fs from 'fs/promises';
16
- import { DateTime } from 'luxon';
17
- import mkdirp from 'mkdirp';
18
- import cleanup from 'node-cleanup';
19
- import path from 'path';
20
- import strip from 'strip-ansi';
21
- export const close = (close, data) => __awaiter(void 0, void 0, void 0, function* () {
22
- if (close && (data.error || data.output)) {
23
- yield data.output.close();
24
- yield data.error.close();
25
- }
26
- });
27
- export const open = (config) => __awaiter(void 0, void 0, void 0, function* () {
28
- // variable to store data
29
- const data = {
30
- startedOn: DateTime.local(),
31
- };
32
- if (config.logs.enable == true && !config.logs.dir) {
33
- const { log } = paths(config.appName, {
34
- suffix: '',
35
- });
36
- config.logs.dir = log;
37
- }
38
- if (config.logs.enable) {
39
- // make sure that the folder exists
40
- yield mkdirp(config.logs.dir);
41
- // open log files
42
- data.output = yield fs.open(path.join(config.logs.dir, config.logs.output), 'a', 0o666);
43
- data.error = yield fs.open(path.join(config.logs.dir, config.logs.error), 'a', 0o666);
44
- }
45
- // attach the closing hook
46
- cleanup(() => {
47
- close(!config.shutdownLog, data);
48
- });
49
- return data;
50
- });
51
- export default (log, type, config, data) => __awaiter(void 0, void 0, void 0, function* () {
52
- if (config.logs.enable == false)
53
- return;
54
- // whether to write in error or output file
55
- const stream = ['error', 'warning'].includes(type) ? 'error' : 'output';
56
- // strip ansi terminal styling codes
57
- log = strip(log) + '\n';
58
- // write it!
59
- yield data[stream].appendFile(log);
60
- });
@@ -1,3 +0,0 @@
1
- import { ConfigImpl } from '../config.js';
2
- declare const _default: (typeStr: string, msg: string, config: ConfigImpl) => string;
3
- export default _default;
@@ -1,33 +0,0 @@
1
- /*
2
- * This file will replace all the placeholders with real values.
3
- * Created On 12 October 2019
4
- */
5
- import ne from 'node-emoji';
6
- import path from 'path';
7
- import emoji from './variables/emoji.js';
8
- import time from './variables/time.js';
9
- import type from './variables/type.js';
10
- export default (typeStr, msg, config) => config.theme.string
11
- // <!-- docs -->
12
- // The time of the log message. A [Luxon](https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens) format string can be given as `theme.timeFormat` to change the formatting.
13
- .replace(':time', time(config))
14
- // Emoji according to the message type.
15
- .replace(':emoji', emoji(typeStr))
16
- // Log message in terminal's default color.
17
- .replace(':message', ne.emojify(msg))
18
- // Full path to Node.js executable.
19
- .replace(':node_path', process.argv[0])
20
- // Message type (ie. info, warning, error, etc).
21
- .replace(':type', type(typeStr, config))
22
- // Full path of the Node.js entry JavaScript file.
23
- .replace(':script_path', process.argv[1])
24
- // Version of Node.js running.
25
- .replace(':node_version', process.version)
26
- // Version of V8 engine running along with Node.js.
27
- .replace(':v8_version', process.versions.v8)
28
- // Filename of the Node.js entryfile.
29
- .replace(':filename', path.basename(process.argv[1]))
30
- // Version of OpenSSL running along with Node.js.
31
- .replace(':openssl_version', process.versions.openssl)
32
- // Version of Electron.js running. Returns `undefined` if not Electron.
33
- .replace(':electron_version', process.versions.electron);
@@ -1,2 +0,0 @@
1
- declare const _default: (type: string) => string;
2
- export default _default;
@@ -1,15 +0,0 @@
1
- /*
2
- * Renders ":emoji" variable in log messages.
3
- * Created On 15 April 2021
4
- */
5
- import emoji from 'node-emoji';
6
- const emojis = {
7
- okay: 'thumbsup',
8
- info: 'loudspeaker',
9
- error: 'x',
10
- note: 'memo',
11
- verbose: 'telescope',
12
- success: 'white_check_mark',
13
- warning: 'construction',
14
- };
15
- export default (type) => emoji.emojify(`:${emojis[type]}:`).trim();
@@ -1,3 +0,0 @@
1
- import { ConfigImpl } from '../../config.js';
2
- declare const _default: (config: ConfigImpl) => string;
3
- export default _default;
@@ -1,9 +0,0 @@
1
- /*
2
- * This file will render the ":time" variable.
3
- * Created On 12 October 2019
4
- */
5
- import chalk from 'chalk';
6
- import { DateTime } from 'luxon';
7
- export default (config) => config.theme.colored
8
- ? chalk.gray.dim(DateTime.local().toFormat(config.theme.timeFormat))
9
- : DateTime.local().toFormat(config.theme.timeFormat);
@@ -1,3 +0,0 @@
1
- import { ConfigImpl } from '../../config.js';
2
- declare const _default: (type: string, config: ConfigImpl) => string;
3
- export default _default;
@@ -1,34 +0,0 @@
1
- /*
2
- * This file will render the ":type" variable in the theme.
3
- * Created On 12 October 2019
4
- */
5
- import chalk from 'chalk';
6
- // bold() will make the text bold
7
- const bold = (type, config) => config.theme.boldType ? chalk.bold(type) : type;
8
- // this function will call the rest of the styling
9
- // functions will make a function chain like that
10
- const colorize = (type, config) => {
11
- if (!config.theme.colored)
12
- return bold(type, config);
13
- const colors = {
14
- okay: chalk.gray,
15
- info: chalk.blueBright,
16
- error: chalk.redBright,
17
- note: chalk.magentaBright,
18
- verbose: chalk.cyanBright,
19
- success: chalk.greenBright,
20
- warning: chalk.yellowBright,
21
- };
22
- return bold(colors[type](type), config);
23
- };
24
- // casing() will set the character casing
25
- const casing = (type, config) => {
26
- const toTitleCase = (str) => str.replace(/\w\S*/g, txt => txt.charAt(0).toUpperCase() + txt.substr(1).toLowerCase());
27
- const func = {
28
- 0: (str) => str.toUpperCase(),
29
- 1: (str) => str.toLowerCase(),
30
- 2: (str) => toTitleCase(str),
31
- };
32
- return colorize(func[config.theme.typeCase](type), config);
33
- };
34
- export default (type, config) => casing(type, config);
@@ -1,10 +0,0 @@
1
- import { ConfigImpl, DataImpl } from '../config.js';
2
- declare const _default: ({ msg, type, data, config, exitCode, condition, }: {
3
- type?: string;
4
- data: DataImpl;
5
- exitCode?: number;
6
- config: ConfigImpl;
7
- msg: string | Error;
8
- condition?: (config: ConfigImpl) => boolean;
9
- }) => void;
10
- export default _default;
@@ -1,29 +0,0 @@
1
- /*
2
- * A wrapper function that handles all specifics
3
- * before passing data to the render function.
4
- * Created On 14 April 2021
5
- */
6
- import writeLog from './log.js';
7
- import renderer from './renderer.js';
8
- const getType = () => new Error().stack.split('\n')[3].trim().slice(10).split(' ')[0];
9
- export default ({ msg, type, data, config, exitCode, condition, }) => {
10
- // check if there's a condition
11
- const showOutput = condition ? condition(config) : true;
12
- // set the type, incase it isn't already
13
- if (!type)
14
- type = getType();
15
- // handle if Error or message string
16
- if (typeof msg == 'object')
17
- msg = msg.message;
18
- // render the log message
19
- const log = renderer(type, msg, config);
20
- writeLog(log, type, config, data);
21
- if (!showOutput)
22
- return;
23
- if (config.quietIdentifier.some(argument => process.argv.includes(argument)) == false) {
24
- console.log(log);
25
- }
26
- // handle the exitCode
27
- if (exitCode)
28
- process.exit(exitCode);
29
- };
package/dist/config.d.ts DELETED
@@ -1,40 +0,0 @@
1
- /// <reference types="node" />
2
- import { FileHandle } from 'fs/promises';
3
- import Joi from 'joi';
4
- import { DateTime } from 'luxon';
5
- export declare enum typeCase {
6
- 'upper' = 0,
7
- 'lower' = 1,
8
- 'title' = 2
9
- }
10
- export interface ConfigImpl {
11
- appName?: string;
12
- bootLog?: boolean;
13
- shutdownLog?: boolean;
14
- clearOnSIGINT?: boolean;
15
- quietIdentifier?: Array<string>;
16
- verboseIdentifier?: Array<string>;
17
- context?: {
18
- name: string;
19
- color: (str: string) => string;
20
- };
21
- theme?: {
22
- string?: string;
23
- colored?: boolean;
24
- boldType?: boolean;
25
- typeCase?: typeCase;
26
- timeFormat?: string;
27
- };
28
- logs?: {
29
- dir?: string;
30
- error?: string;
31
- output?: string;
32
- enable?: boolean;
33
- };
34
- }
35
- export declare const configSchema: Joi.ObjectSchema<any>;
36
- export interface DataImpl {
37
- output?: FileHandle;
38
- error?: FileHandle;
39
- startedOn: DateTime;
40
- }
package/dist/config.js DELETED
@@ -1,38 +0,0 @@
1
- /*
2
- * This file will contain code related to loading and storing configuration.
3
- * Created On 11 October 2019
4
- */
5
- import Joi from 'joi';
6
- // typeCase enumerator will hold the
7
- // int values for type string case
8
- export var typeCase;
9
- (function (typeCase) {
10
- typeCase[typeCase["upper"] = 0] = "upper";
11
- typeCase[typeCase["lower"] = 1] = "lower";
12
- typeCase[typeCase["title"] = 2] = "title";
13
- })(typeCase || (typeCase = {}));
14
- export const configSchema = Joi.object({
15
- appName: Joi.string(),
16
- bootLog: Joi.bool().required(),
17
- shutdownLog: Joi.bool().required(),
18
- clearOnSIGINT: Joi.bool().required(),
19
- quietIdentifier: Joi.array().items(Joi.string()),
20
- verboseIdentifier: Joi.array().items(Joi.string()),
21
- context: Joi.object({
22
- color: Joi.any().required(),
23
- name: Joi.string().allow(null).required(),
24
- }),
25
- theme: Joi.object({
26
- string: Joi.string().required(),
27
- colored: Joi.bool(),
28
- boldType: Joi.bool(),
29
- typeCase: Joi.number(),
30
- timeFormat: Joi.string(),
31
- }),
32
- logs: Joi.object({
33
- dir: Joi.string().allow(null).required(),
34
- output: Joi.string().required(),
35
- error: Joi.string().required(),
36
- enable: Joi.bool().required(),
37
- }),
38
- });
@@ -1,17 +0,0 @@
1
- import { Logger } from './class/index.js';
2
- import { ConfigImpl } from './config.js';
3
- declare const _default: {
4
- /**
5
- * Creates a new instance of a logger.
6
- * @param config {ConfigImpl}
7
- * @returns Logger
8
- */
9
- createNewLogger: (config?: ConfigImpl) => Promise<Logger>;
10
- /**
11
- * Deletes the log directory for a given logger.
12
- * @param logger {Logger}
13
- * @returns string[]
14
- */
15
- clearLogs: (logger: Logger) => Promise<string[]>;
16
- };
17
- export default _default;
@@ -1,118 +0,0 @@
1
- /*
2
- * Entryfile for itivrutaha logging module.
3
- * Created On 10 October 2019
4
- */
5
- var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
6
- function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
7
- return new (P || (P = Promise))(function (resolve, reject) {
8
- function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
9
- function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
10
- function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
11
- step((generator = generator.apply(thisArg, _arguments || [])).next());
12
- });
13
- };
14
- import chalk from 'chalk';
15
- import merge from 'deepmerge';
16
- import { deleteAsync } from 'del';
17
- import { DateTime } from 'luxon';
18
- import { readPackageUpSync } from 'read-pkg-up';
19
- import { Logger } from './class/index.js';
20
- import { open } from './class/log.js';
21
- import { typeCase } from './config.js';
22
- // Holds the default configuration which acts like a
23
- // replacement when no value is provided for a
24
- // particular configuration key
25
- const defaults = {
26
- // The name of your app, if not provided
27
- // the value will be determined by reading
28
- // package.json of the above project.
29
- appName: null,
30
- // Whether to log when the logger is initialized.
31
- bootLog: true,
32
- // Whether to log when the Node.js process exits.
33
- // Logs when terminating gracefully, due to an error
34
- // or when POSIX signals are received.
35
- shutdownLog: true,
36
- // remove the "^CāŽ" after terminating the process
37
- // when Ctrl+C is pressed
38
- clearOnSIGINT: true,
39
- // Command-line arguments that suppress the output
40
- // to the console if found.
41
- quietIdentifier: ['--quiet', '-q'],
42
- // Command-line arguments that render verbose message
43
- // type to the console if found.
44
- verboseIdentifier: ['--verbose', '-v'],
45
- // Configuration for this particular logger.
46
- // Useful when application has multiple loggers.
47
- context: {
48
- // Name of the context, example "app", "api",
49
- // "bot", "server"...
50
- name: null,
51
- // Chalk color function for this context.
52
- color: chalk.blueBright,
53
- },
54
- // Configuration options related to rendering the
55
- // log messages to the console.
56
- theme: {
57
- // The theme string, that determines which variables
58
- // are to be rendered.
59
- string: `:time ${chalk.gray.dim('•')} :emoji :type :message`,
60
- // Whether to log colored output
61
- // or plain.
62
- colored: true,
63
- // Whether to render message type (":type" variable)
64
- // in bold.
65
- boldType: true,
66
- // The character casing to render message type or
67
- // the (":type" variable).
68
- typeCase: typeCase.lower,
69
- // Luxon time formatting used to render the
70
- // ":time" variable. See šŸ‘‡ for formatting guide
71
- // https://moment.github.io/luxon/docs/manual/formatting.html#table-of-tokens
72
- timeFormat: 'HH:mm:ss dd-LL-yyyy',
73
- },
74
- logs: {
75
- // Whether to enable file logging or not.
76
- enable: false,
77
- // The directory where log files are saved.
78
- dir: null,
79
- // Filename for writing output (stdout)
80
- // logs.
81
- output: `output-${DateTime.local().toFormat('dd-LL-yyyy')}.log`,
82
- // Filename for writing error (stderr)
83
- // logs.
84
- error: `error-${DateTime.local().toFormat('dd-LL-yyyy')}.log`,
85
- },
86
- };
87
- // createNewLogger() will create a new instance of the logger class
88
- const createNewLogger = (config = defaults) => __awaiter(void 0, void 0, void 0, function* () {
89
- // if custom properties were given merge those together
90
- // with defaults so we have all properties defined
91
- config = merge(defaults, config);
92
- // fill out the fields which are specific to this
93
- // particular instance of Logger
94
- if (config.appName == null)
95
- config.appName = readPackageUpSync().packageJson.name;
96
- if (config.context.name)
97
- config.theme.string = `:time ${chalk.gray.dim('•')} ${config.context.color(config.context.name)} :emoji :type :message`;
98
- // initialize file logging according to the configuration
99
- const data = yield open(config);
100
- // return a new LoggerClass instance
101
- return new Logger(config, data);
102
- });
103
- const clearLogs = (logger) => __awaiter(void 0, void 0, void 0, function* () { return yield deleteAsync(logger.config.logs.dir, { force: true }); });
104
- // Export the above two functions
105
- export default {
106
- /**
107
- * Creates a new instance of a logger.
108
- * @param config {ConfigImpl}
109
- * @returns Logger
110
- */
111
- createNewLogger,
112
- /**
113
- * Deletes the log directory for a given logger.
114
- * @param logger {Logger}
115
- * @returns string[]
116
- */
117
- clearLogs,
118
- };