From ac34c59e60783041d47a1cf4bb4e5f28567f1c09 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jo=C3=A3o=20Lenon?= Date: Fri, 18 Feb 2022 12:23:55 -0300 Subject: [PATCH] refactor: remove config methods, tempDriver and changeDefaultChannel --- README.md | 15 +--- package-lock.json | 13 +++ package.json | 3 +- src/Drivers/ConsoleDriver.ts | 10 +-- src/Drivers/DebugDriver.ts | 8 +- src/Drivers/FileDriver.ts | 22 ++--- src/Log.ts | 6 -- src/Logger.ts | 155 +++++++---------------------------- src/utils/getConfigFile.ts | 8 -- 9 files changed, 61 insertions(+), 179 deletions(-) delete mode 100644 src/utils/getConfigFile.ts diff --git a/README.md b/README.md index 06afab3..3e016f2 100644 --- a/README.md +++ b/README.md @@ -92,8 +92,12 @@ export default { > With the config/logging file created you can use Log and Logger classes to start logging. ```ts +import { Config } from '@secjs/config' import { Log, Logger, Color } from '@secjs/logger' +// First you need to instantiate Config class and call loadSync method to load configuration files +new Confg().loadSync() + // Log and Logger will always use the default values of channel inside config/logging, the default channel in here is "application". Log.log('Hello World!') // [SecJS] - PID: 38114 - dd/mm/yyyy, hh:mm:ss PM [Logger] Hello World! +0ms @@ -117,17 +121,6 @@ Log.channel('debug').log('Hello debug world!', { namespace: 'api:example' }) // api:example [SecJS] - PID: 38114 - dd/mm/yyyy, hh:mm:ss PM [Debugger] Hello debug world! +0ms ``` -> You can use many channels to handle the log in all of then - -```ts -Log.channels('debug', 'application', 'file').info('Hello World!', { namespace: 'api:example' }) -// api:example [SecJS] - PID: 38114 - dd/mm/yyyy, hh:mm:ss PM [Debugger] Hello World! +0ms -// [SecJS] - PID: 38114 - dd/mm/yyyy, hh:mm:ss PM [Logger] Hello World! +0ms - -// In storage/logs/secjs.log file -// [SecJS] - PID: 196416 - dd/mm/yyyy, hh:mm:ss [INFO] Hello World! -``` - ### Extending drivers, channels and formatters > Nowadays, @secjs/logger has only FileDriver, DebugDriver and ConsoleDriver support, but you can extend the drivers for Logger class if you implement DriverContract interface. diff --git a/package-lock.json b/package-lock.json index 78e8fab..6c2b4e4 100644 --- a/package-lock.json +++ b/package-lock.json @@ -13,6 +13,7 @@ "debug": "4.3.1" }, "devDependencies": { + "@secjs/config": "1.1.3", "@secjs/env": "1.2.8", "@secjs/exceptions": "1.0.4", "@secjs/utils": "1.5.8", @@ -1297,6 +1298,12 @@ "node": ">= 8" } }, + "node_modules/@secjs/config": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@secjs/config/-/config-1.1.3.tgz", + "integrity": "sha512-dr8BAtS9gLAhaZwfIICzOsEOWFyim91Dp5OdvDQ/izYDfcU8DgLcvzIxEH9xcDHY8CoY60sexXcJ7W7q7xfxBw==", + "dev": true + }, "node_modules/@secjs/env": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/@secjs/env/-/env-1.2.8.tgz", @@ -9595,6 +9602,12 @@ "fastq": "^1.6.0" } }, + "@secjs/config": { + "version": "1.1.3", + "resolved": "https://registry.npmjs.org/@secjs/config/-/config-1.1.3.tgz", + "integrity": "sha512-dr8BAtS9gLAhaZwfIICzOsEOWFyim91Dp5OdvDQ/izYDfcU8DgLcvzIxEH9xcDHY8CoY60sexXcJ7W7q7xfxBw==", + "dev": true + }, "@secjs/env": { "version": "1.2.8", "resolved": "https://registry.npmjs.org/@secjs/env/-/env-1.2.8.tgz", diff --git a/package.json b/package.json index 6fb1203..9ef4925 100644 --- a/package.json +++ b/package.json @@ -1,6 +1,6 @@ { "name": "@secjs/logger", - "version": "1.2.6", + "version": "1.2.7", "description": "", "license": "MIT", "author": "João Lenon", @@ -22,6 +22,7 @@ "debug": "4.3.1" }, "devDependencies": { + "@secjs/config": "1.1.3", "@secjs/env": "1.2.8", "@secjs/exceptions": "1.0.4", "@secjs/utils": "1.5.8", diff --git a/src/Drivers/ConsoleDriver.ts b/src/Drivers/ConsoleDriver.ts index e462c2c..0d6def9 100644 --- a/src/Drivers/ConsoleDriver.ts +++ b/src/Drivers/ConsoleDriver.ts @@ -1,9 +1,7 @@ -import { Env } from '@secjs/env' +import { Config } from '@secjs/config' import { Color } from '../utils/Color' import { format } from '../utils/format' -import { File, Path } from '@secjs/utils' import { DriverContract } from '../Contracts/DriverContract' -import { getConfigFile } from '../utils/getConfigFile' export interface ConsoleDriverOpts { color: Color @@ -19,9 +17,7 @@ export class ConsoleDriver implements DriverContract { private readonly _streamType: string constructor(channel: string) { - const configFile = getConfigFile() - - const channelConfig = configFile.channels[channel] + const channelConfig = Config.get(`logging.channels.${channel}`) this._level = channelConfig.level || 'INFO' this._context = channelConfig.context || 'ConsoleDriver' @@ -45,5 +41,3 @@ export class ConsoleDriver implements DriverContract { process[this._streamType].write(`${message}\n`) } } - -new ConsoleDriver('debug') diff --git a/src/Drivers/DebugDriver.ts b/src/Drivers/DebugDriver.ts index 3c04a86..9d13830 100644 --- a/src/Drivers/DebugDriver.ts +++ b/src/Drivers/DebugDriver.ts @@ -1,10 +1,8 @@ import { debug } from 'debug' -import { Env } from '@secjs/env' +import { Config } from '@secjs/config' import { Color } from '../utils/Color' import { format } from '../utils/format' -import { File, Path } from '@secjs/utils' import { DriverContract } from '../Contracts/DriverContract' -import { getConfigFile } from '../utils/getConfigFile' export interface DebugDriverOpts { color: Color @@ -21,9 +19,7 @@ export class DebugDriver implements DriverContract { private readonly _namespace: string constructor(channel: string) { - const configFile = getConfigFile() - - const channelConfig = configFile.channels[channel] + const channelConfig = Config.get(`logging.channels.${channel}`) this._level = channelConfig.level || 'DEBUG' this._context = channelConfig.context || 'DebugDriver' diff --git a/src/Drivers/FileDriver.ts b/src/Drivers/FileDriver.ts index 28b9c83..b35a26e 100644 --- a/src/Drivers/FileDriver.ts +++ b/src/Drivers/FileDriver.ts @@ -1,10 +1,9 @@ import { parse } from 'path' -import { Env } from '@secjs/env' +import { Path } from '@secjs/utils' +import { Config } from '@secjs/config' import { Color } from '../utils/Color' -import { File, Path } from '@secjs/utils' import { DriverContract } from '../Contracts/DriverContract' import { createWriteStream, existsSync, mkdirSync } from 'fs' -import { getConfigFile } from '../utils/getConfigFile' export interface FileDriverOpts { level: string @@ -20,9 +19,7 @@ export class FileDriver implements DriverContract { private readonly _formatter: string constructor(channel: string) { - const configFile = getConfigFile() - - const channelConfig = configFile.channels[channel] + const channelConfig = Config.get(`logging.channels.${channel}`) this._level = channelConfig.level || 'INFO' this._context = channelConfig.context || 'FileDriver' @@ -30,7 +27,7 @@ export class FileDriver implements DriverContract { this._formatter = channelConfig.formatter || 'log' } - transport(message: string, options?: FileDriverOpts): void { + async transport(message: string, options?: FileDriverOpts): Promise { options = Object.assign( {}, { level: this._level, context: this._context, filePath: this._filePath }, @@ -43,14 +40,13 @@ export class FileDriver implements DriverContract { mkdirSync(path.dir, { recursive: true }) } - const stream = createWriteStream(options.filePath, { flags: 'a' }) + return new Promise((resolve, reject) => { + const stream = createWriteStream(options.filePath, { flags: 'a' }) - stream.write(`${Color.removeColors(message)}` + '\n') + stream.write(`${Color.removeColors(message)}` + '\n') - stream.on('error', err => { - throw err + stream.on('error', reject) + stream.end(resolve) }) - - stream.end() } } diff --git a/src/Log.ts b/src/Log.ts index 56eca25..832adac 100644 --- a/src/Log.ts +++ b/src/Log.ts @@ -39,12 +39,6 @@ export class Log { return this } - static channels(...channels: string[]): typeof Log { - this.logger.channels(...channels) - - return this - } - static log(message: any, options?: any) { options = { ...options, diff --git a/src/Logger.ts b/src/Logger.ts index c9c3846..9aba5af 100644 --- a/src/Logger.ts +++ b/src/Logger.ts @@ -3,17 +3,17 @@ import { NotImplementedException, } from '@secjs/exceptions' +import { Config } from '@secjs/config' import { Color } from './utils/Color' import { Drivers } from './Drivers/Drivers' -import { getConfigFile } from './utils/getConfigFile' import { Formatters } from './Formatters/Formatters' import { DriverContract } from './Contracts/DriverContract' import { FormatterContract } from './Contracts/FormatterContract' export class Logger { - private readonly _options?: any = {} - private _tempDrivers: DriverContract[] | null = null - private _defaultDriver: DriverContract | null = null + private runtimeConfig: any + private channelName: string + private driver: DriverContract static buildDriver(name: string, driver: DriverContract) { if (Drivers[name]) { @@ -39,191 +39,94 @@ export class Logger { return Object.keys(Formatters) } - constructor(options?: any) { - this._options = options + private createDriverInstance(channelName?: string) { + channelName = channelName || Config.get('logging.default') - const configFile = getConfigFile() - - const defaultChannel = configFile.default - const channelConfig = configFile.channels[defaultChannel] - - const driver = - this._options && this._options.driver - ? this._options.driver - : channelConfig.driver - - this._defaultDriver = new Drivers[driver](defaultChannel) - } - - private _driver(message: any, options?: any) { - if (this._tempDrivers && this._tempDrivers.length) { - this._tempDrivers.forEach(tempDriver => { - tempDriver.transport(message, options) - }) - - return - } - - this._defaultDriver.transport(message, options) - } - - changeDefaultChannel(channel: string): Logger { - const configFile = getConfigFile() - - const channelConfig = configFile.channels[channel] + const channelConfig = Config.get(`logging.channels.${channelName}`) if (!channelConfig) { throw new NotImplementedException( - `Channel ${channel} is not configured inside logging.channels object from config/logging file`, + `Channel ${channelName} is not configured inside logging.channels object from config/logging file`, ) } if (!Drivers[channelConfig.driver]) { throw new NotImplementedException( - `Driver ${channelConfig.driver} does not exist, use Storage.build method to create a new driver`, + `Driver ${channelConfig.driver} does not exist, use Logger.build method to create a new driver`, ) } - this._defaultDriver = new Drivers[channelConfig.driver](channel) + this.channelName = channelName - return this + return new Drivers[channelConfig.driver](channelName, this.runtimeConfig) } - channel(channel: string): Logger { - const configFile = getConfigFile() - - const channelConfig = configFile.channels[channel] - - if (!channelConfig) { - throw new NotImplementedException( - `Channel ${channel} is not configured inside logging.channels object from config/logging file`, - ) - } - - if (!Drivers[channelConfig.driver]) { - throw new NotImplementedException( - `Driver ${channelConfig.driver} does not exist, use Storage.build method to create a new driver`, - ) - } - - this._tempDrivers = [] - - this._tempDrivers.push(new Drivers[channelConfig.driver](channel)) - - return this + constructor(runtimeConfig: any = {}) { + this.runtimeConfig = runtimeConfig + this.driver = this.createDriverInstance() } - channels(...channels: string[]): Logger { - this._tempDrivers = [] + channel(channel: string, runtimeConfig?: any): Logger { + if (runtimeConfig) this.runtimeConfig = runtimeConfig - const configFile = getConfigFile() - - channels.forEach(channel => { - const channelConfig = configFile.channels[channel] - - if (!channelConfig) { - throw new NotImplementedException( - `Channel ${channel} is not configured inside logging.channels object from config/logging file`, - ) - } - - if (!Drivers[channelConfig.driver]) { - throw new NotImplementedException( - `Driver ${channelConfig.driver} does not exist, use Storage.build method to create a new driver`, - ) - } - - this._tempDrivers.push(new Drivers[channelConfig.driver](channel)) - }) + this.driver = this.createDriverInstance(channel) return this } - log(message: any, options?: any) { + async log(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) - this._driver(message, options) - - this._tempDrivers = [] + await this.driver.transport(message, options) } - info(message: any, options?: any) { + async info(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) options.level = 'INFO' options.color = Color.cyan options.streamType = 'stdout' - options = { - ...options, - ...this._options, - } - - this._driver(message, options) - this._tempDrivers = [] + await this.driver.transport(message, options) } - warn(message: any, options?: any) { + async warn(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) options.level = 'WARN' options.color = Color.orange options.streamType = 'stdout' - options = { - ...options, - ...this._options, - } - this._driver(message, options) - - this._tempDrivers = [] + await this.driver.transport(message, options) } - error(message: any, options?: any) { + async error(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) options.level = 'ERROR' options.color = Color.red options.streamType = 'stderr' - options = { - ...options, - ...this._options, - } - this._driver(message, options) - - this._tempDrivers = [] + await this.driver.transport(message, options) } - debug(message: any, options?: any) { + async debug(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) options.level = 'DEBUG' options.color = Color.purple options.streamType = 'stdout' - options = { - ...options, - ...this._options, - } - - this._driver(message, options) - this._tempDrivers = [] + await this.driver.transport(message, options) } - success(message: any, options?: any) { + async success(message: any, options?: any) { options = Object.assign({}, { context: 'Logger' }, options) options.level = 'SUCCESS' options.color = Color.green options.streamType = 'stdout' - options = { - ...options, - ...this._options, - } - - this._driver(message, options) - this._tempDrivers = [] + await this.driver.transport(message, options) } } diff --git a/src/utils/getConfigFile.ts b/src/utils/getConfigFile.ts deleted file mode 100644 index 83a80a2..0000000 --- a/src/utils/getConfigFile.ts +++ /dev/null @@ -1,8 +0,0 @@ -import { Env } from '@secjs/env' -import { File, Path } from '@secjs/utils' - -export function getConfigFile() { - const extension = Env('NODE_TS', '') === 'true' ? 'ts' : 'js' - - return require(new File(Path.config(`logging.${extension}`)).path).default -}