From 1cd930b6a98cbe3fa621a86dc9e8c80105480260 Mon Sep 17 00:00:00 2001 From: Jeremiah Faluyi Date: Thu, 4 Aug 2022 08:09:36 +0100 Subject: [PATCH] fixed package.json location; ready for dist --- .gitignore | 2 +- dist/catch/index.js | 54 ++++++++++++++++++++ dist/index.d.ts | 30 ++++++++++++ dist/index.js | 35 +++++++++++++ dist/logger/index.js | 37 ++++++++++++++ dist/query/index.js | 84 ++++++++++++++++++++++++++++++++ dist/utils/datetime.js | 26 ++++++++++ package.json | 8 ++- src/.DS_Store | Bin 6148 -> 6148 bytes src/{handler => catch}/index.ts | 0 src/handler/.DS_Store | Bin 6148 -> 0 bytes src/index.ts | 31 +++++++----- src/query/index.ts | 2 +- src/tests/index.test.ts | 5 +- src/utils/datetime.ts | 18 ++++--- tsconfig.json | 12 +++-- {src/types => types}/index.d.ts | 0 17 files changed, 314 insertions(+), 30 deletions(-) create mode 100644 dist/catch/index.js create mode 100644 dist/index.d.ts create mode 100644 dist/index.js create mode 100644 dist/logger/index.js create mode 100644 dist/query/index.js create mode 100644 dist/utils/datetime.js rename src/{handler => catch}/index.ts (100%) delete mode 100644 src/handler/.DS_Store rename {src/types => types}/index.d.ts (100%) diff --git a/.gitignore b/.gitignore index 9ed310c..b89561d 100644 --- a/.gitignore +++ b/.gitignore @@ -82,7 +82,7 @@ typings/ # Nuxt.js build / generate output .nuxt -dist +# dist # Gatsby files .cache/ diff --git a/dist/catch/index.js b/dist/catch/index.js new file mode 100644 index 0000000..8cad868 --- /dev/null +++ b/dist/catch/index.js @@ -0,0 +1,54 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.catchSyncNoReturn = exports.catchSync = exports.catchAsyncNoReturn = exports.catchAsync = void 0; +const tslib_1 = require("tslib"); +const logger_1 = require("../logger"); +function catchAsync(resolve, cb, _throw = false) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + return (yield resolve); + } + catch (err) { + return handleError(err, cb, _throw); + } + }); +} +exports.catchAsync = catchAsync; +function catchAsyncNoReturn(resolve, cb, _throw = false) { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + try { + yield resolve; + } + catch (err) { + handleError(err, cb); + } + }); +} +exports.catchAsyncNoReturn = catchAsyncNoReturn; +function catchSync(result, cb, _throw = false) { + try { + return result; + } + catch (err) { + return handleError(err, cb); + } +} +exports.catchSync = catchSync; +function catchSyncNoReturn(result, cb, _throw = false) { + try { + result; + } + catch (err) { + handleError(err, cb); + } +} +exports.catchSyncNoReturn = catchSyncNoReturn; +function handleError(err, _throw, cb) { + const error = new Error(err.message); + (0, logger_1.logError)(error); + if (cb) + cb(err); + if (_throw) + throw new Error(err.message); + return undefined; +} diff --git a/dist/index.d.ts b/dist/index.d.ts new file mode 100644 index 0000000..7ba2259 --- /dev/null +++ b/dist/index.d.ts @@ -0,0 +1,30 @@ +export interface ILoggerConfig { + logName: string, + logPath: string, + maxSize?: number, + logToFile: boolean +} + +export interface IQueryFactory { + size: number; + lastLogTime: number | undefined; + logs: Array; + get: () => Array; + parse: (logBuffer: Buffer) => void; + head: (length: number) => Array; + tail: (length: number) => Array; + findByTimeStamp: (timestamp: number) => Log | undefined; + findByTimeRange: (startTime: number, stopTime: number) => IQueryFactory; + findByErrorLevel: (level: ErrorLevel) => IQueryFactory; + findByStack: (stack: string) => IQueryFactory; + findByErrorMessage: (message: string) => IQueryFactory; +} + +export interface Log { + timestamp: number; + level: ErrorLevel; + stack: string; + message: string; +} + +export declare type ErrorLevel = "INFO" | "WARN" | "LOW" | "MODERATE" | "HIGH" | "EMERGENCY" \ No newline at end of file diff --git a/dist/index.js b/dist/index.js new file mode 100644 index 0000000..6e0030d --- /dev/null +++ b/dist/index.js @@ -0,0 +1,35 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.config = void 0; +const tslib_1 = require("tslib"); +const process_1 = require("process"); +require("dotenv").config(); +function init() { + var _a, _b; + let config; + try { + let path = ""; + if (process.env.MODE === "DEVELOPMENT") { + path = "../package.json"; + } + else { + if ((0, process_1.cwd)().includes("node_modules")) { + path = (0, process_1.cwd)().split("node_modules")[0].concat("package.json"); + } + } + config = require(path).trollerConfig; + } + catch (err) { + config = undefined; + console.log("Could not read config from package.json. Using default config..."); + } + return { + logName: (_a = config === null || config === void 0 ? void 0 : config.logName) !== null && _a !== void 0 ? _a : "test.log", + logPath: process.env.MODE !== "DEVELOPMENT" ? `${(0, process_1.cwd)().split("node_modules")[0]}/logs/` : "/logs/", + logToFile: (_b = config === null || config === void 0 ? void 0 : config.logToFile) !== null && _b !== void 0 ? _b : true, + }; +} +exports.config = init(); +tslib_1.__exportStar(require("./logger"), exports); +tslib_1.__exportStar(require("./catch"), exports); +tslib_1.__exportStar(require("./query"), exports); diff --git a/dist/logger/index.js b/dist/logger/index.js new file mode 100644 index 0000000..ee713d0 --- /dev/null +++ b/dist/logger/index.js @@ -0,0 +1,37 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.logConsole = exports.logError = void 0; +const node_fs_1 = require("node:fs"); +const __1 = require("../"); +const datetime_1 = require("../utils/datetime"); +function logError(err) { + if (!err) + return; + logLocal(err); +} +exports.logError = logError; +function logMessage(err) { + var _a, _b; + const logLineDetails = (_b = (_a = err === null || err === void 0 ? void 0 : err.stack) === null || _a === void 0 ? void 0 : _a.split("at ")[1]) === null || _b === void 0 ? void 0 : _b.trim(); + return Buffer.from(`[${(0, datetime_1.formatDateTime)(Date.now())}] => ISSUE, Stack: ${logLineDetails}, ${err}\n`, "utf-8"); +} +function logLocal(err) { + let newLog = logMessage(err); + if (!__1.config.logToFile) + return; + let logs = Buffer.from([]); + try { + logs = (0, node_fs_1.readFileSync)(__1.config.logPath + __1.config.logName); + } + catch (err) { + if (!(0, node_fs_1.existsSync)(__1.config.logPath)) + (0, node_fs_1.mkdirSync)(__1.config.logPath); + logs = Buffer.from(`---- LOG HEAD | START DATE: ${(0, datetime_1.formatDateTime)(Date.now())}} ----\n`, "utf-8"); + } + newLog = Buffer.concat([logs, newLog]); + (0, node_fs_1.writeFileSync)(__1.config.logPath + __1.config.logName, newLog); +} +function logConsole(message) { + console.log(message); +} +exports.logConsole = logConsole; diff --git a/dist/query/index.js b/dist/query/index.js new file mode 100644 index 0000000..606ccd2 --- /dev/null +++ b/dist/query/index.js @@ -0,0 +1,84 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.Query = void 0; +const tslib_1 = require("tslib"); +const promises_1 = require("fs/promises"); +const __1 = require(".."); +const catch_1 = require("../catch"); +const datetime_1 = require("../utils/datetime"); +class Query { + constructor(logPath) { + this.logPath = logPath; + this.node = new QueryFactory(); + this.logPath = logPath || __1.config.logPath; + this.readFileToBuffer(); + } + ; + readFileToBuffer() { + return tslib_1.__awaiter(this, void 0, void 0, function* () { + const data = yield (0, catch_1.catchAsync)((0, promises_1.readFile)(this.logPath)); + this.node.parse(data); + }); + } +} +exports.Query = Query; +class QueryFactory { + constructor() { + this.size = 0; + this.logs = []; + this.temp = []; + } + get() { + const _temp = this.temp; + this.temp = []; + return _temp; + } + parse(logBuffer) { + var _a; + let buf = logBuffer.toString().split('\n').reverse(); + buf.pop(); + buf = buf.reverse(); + this.logs = buf.map(log => { + const parsedLog = log.split(","); + return { + timestamp: (0, datetime_1.parseDateTime)(parsedLog[0].split("=>")[0].trim().replace('[', '').replace(']', '')), + level: parsedLog[0].split("=>")[1].trim(), + stack: parsedLog[1].trim(), + message: parsedLog[2].trim() + }; + }); + this.size = this.logs.length; + this.lastLogTime = ((_a = this.logs.at(-1)) === null || _a === void 0 ? void 0 : _a.timestamp) || undefined; + } + head(length = 5) { + return this.logs.slice(0, length + 1); + } + tail(length = 5) { + return this.logs.slice(this.logs.length - length + 1); + } + findByTimeStamp(timestamp) { + return this.logs.find(log => log.timestamp === timestamp); + } + findByTimeRange(startTime, stopTime = 0) { + if (startTime <= 0) + throw new Error("Invalid startTime value"); + if (stopTime === 0) { + this.temp = (this.temp || this.logs).filter(log => log.timestamp >= startTime); + return this; + } + this.temp = (this.temp || this.logs).filter(log => log.timestamp >= startTime && log.timestamp <= stopTime); + return this; + } + findByErrorLevel(level) { + this.temp = (this.temp || this.logs).filter(log => log.level === level); + return this; + } + findByErrorMessage(message) { + this.temp = (this.temp || this.logs).filter(log => log.message.includes(message)); + return this; + } + findByStack(stack) { + this.temp = (this.temp || this.logs).filter((log) => log.stack.includes(stack)); + return this; + } +} diff --git a/dist/utils/datetime.js b/dist/utils/datetime.js new file mode 100644 index 0000000..4abfd73 --- /dev/null +++ b/dist/utils/datetime.js @@ -0,0 +1,26 @@ +"use strict"; +Object.defineProperty(exports, "__esModule", { value: true }); +exports.parseDateTime = exports.formatDateTime = void 0; +function formatDateTime(timestamp) { + const date = new Date(timestamp); + const day = date.getDate(); + const month = date.getMonth(); + const year = date.getFullYear(); + const hour = date.getHours(); + const mins = date.getMinutes(); + const secs = date.getSeconds(); + const mm = month + 1 > 9 ? month + 1 : `0${month + 1}`; + const dd = day > 9 ? day : `0${day}`; + const hh = hour > 9 ? hour : `0${hour}`; + const _mins = mins > 9 ? mins : `0${mins}`; + const _secs = secs > 9 ? secs : `0${secs}`; + return `${year}-${mm}-${dd} ${hh}:${_mins}:${_secs}`; +} +exports.formatDateTime = formatDateTime; +function parseDateTime(str) { + const timestamp = Date.parse(str.replaceAll(" ", "T")); + if (timestamp === 0 || isNaN(timestamp)) + throw new Error("Unable to parse datetime string; Invalid string format. [yyyy/mm/dd, hh:mm:ss]"); + return timestamp; +} +exports.parseDateTime = parseDateTime; diff --git a/package.json b/package.json index 19f4114..3470bcd 100644 --- a/package.json +++ b/package.json @@ -7,7 +7,9 @@ "license": "MIT", "private": true, "scripts": { - "start:dev": "export NODE_ENV=DEVELOPMENT && ts-node src/index.ts", + "start": "export MODE=PRODUCTION && ts-node src/index.ts", + "start:dev": "export MODE=DEVELOPMENT && ts-node src/index.ts", + "compile": "tsc && cp types/index.d.ts dist/", "test": "jest src/tests/test.spec.ts" }, "dependencies": { @@ -22,5 +24,7 @@ "ts-node": "^10.7.0", "tslib": "^2.3.1" }, - "trollerConfig": {} + "trollerConfig": { + "logName": "testfrompkg.log" + } } diff --git a/src/.DS_Store b/src/.DS_Store index 0943fb5dd6158041984eb1e9a0784227696ce7c2..ad5d68fef7f1ece3ba0c6f25a10b970a9ce0f126 100644 GIT binary patch delta 68 zcmZoMXfc=|#>B)qu~2NHo+2ar#(>?7jO?3vSe7zwKFMmww6Q^gX)`+qKL=3FWB!ku~2NHo+2a1#(>?7iv?Ji7&$icFfC;iWnsu+$Y)4rC@u>w%FD^m tOJ`tUVBEZp*^y~8I|n}pQ0Hbwmha4y`9&N#7#SFtfYJ<`BSh9P0|4Yj6hHs~ diff --git a/src/handler/index.ts b/src/catch/index.ts similarity index 100% rename from src/handler/index.ts rename to src/catch/index.ts diff --git a/src/handler/.DS_Store b/src/handler/.DS_Store deleted file mode 100644 index e247c538afaa04877996c11f32c1c46121fcc7d2..0000000000000000000000000000000000000000 GIT binary patch literal 0 HcmV?d00001 literal 6148 zcmeHKyG{c^3>-s>lW0;>?iWPj50)q?sQCdDLV*;K0+3Q(#dq;%Vf+vxI;ap08cX)< zdOf$fDb6tfTfT0ufH{DH?ua)JQ}c88iJeu(h;%;VfCXOge6!o%PpZF9ICsD!p0LHk zSN>+V-|)zE~o%@f34I3_Yfv!oJ}YBge5(wT2n*9*tQq{HH7KBsQBnoulmXTC)_ ztS2f;0V!~*z(T=(Cc6=E{S=W5c^IkY62A%n!6ZL1nb&*MdzgFM_T6r6G diff --git a/src/index.ts b/src/index.ts index 53224a4..09f8338 100644 --- a/src/index.ts +++ b/src/index.ts @@ -1,29 +1,38 @@ +import { cwd } from "process"; import {ILoggerConfig} from "@types"; require("dotenv").config(); -function validateConfig(): ILoggerConfig { - const configPath = process.env.NODE_ENV === "DEVELOPMENT" ? "../package.json" : "../../../package.json"; - const logPath = "./src/logs/"; +function init(): ILoggerConfig { let config: ILoggerConfig | undefined; - + try { - config = require(configPath).trollerConfig; + let path = ""; + if (process.env.MODE === "DEVELOPMENT") { + path = "../package.json"; + }else { + if(cwd().includes("node_modules")) { + path = cwd().split("node_modules")[0].concat("package.json"); + } + } + config = require(path).trollerConfig; } catch(err) { config = undefined; - // console.log("Could not find config; Using default values..."); + console.log("Could not read config from package.json. Using default config..."); } return { logName: config?.logName ?? "test.log", - logPath: config?.logPath ? `../../..${config?.logPath}/logs/` : logPath, - logToFile: config?.logToFile ?? true + logPath: process.env.MODE !== "DEVELOPMENT" ? `${cwd().split("node_modules")[0]}/logs/` : "/logs/", + logToFile: config?.logToFile ?? true, }; } -export const config = validateConfig(); +// const cfg = init(); +export const config = init(); +// export const config = cfg; export * from "./logger"; -export * from "./handler"; +export * from "./catch"; export * from "./query"; -// console.log(validateConfig()); \ No newline at end of file +// console.log(cfg); \ No newline at end of file diff --git a/src/query/index.ts b/src/query/index.ts index f624065..21cc2e2 100644 --- a/src/query/index.ts +++ b/src/query/index.ts @@ -1,6 +1,6 @@ import { readFile } from "fs/promises"; import { config } from ".."; -import { catchAsync } from "../handler"; +import { catchAsync } from "../catch"; import { IQueryFactory, Log, ErrorLevel } from "@types"; import { parseDateTime } from "../utils/datetime"; diff --git a/src/tests/index.test.ts b/src/tests/index.test.ts index f1aaecc..2848114 100644 --- a/src/tests/index.test.ts +++ b/src/tests/index.test.ts @@ -1,3 +1,4 @@ +import { cwd } from "node:process"; import { config } from "../index"; export function initTestSuite() { @@ -7,8 +8,8 @@ export function initTestSuite() { it("should have valid config values", () => { expect(config).toBeDefined(); - expect(config.logName).toEqual("test.log"); - expect(config.logPath).toEqual("./src/logs/"); + expect(typeof config.logName).toBe('string'); + expect(config.logPath).toEqual(process.env.MODE === "DEVELOPMENT" ? "/logs/" : `${cwd().split("node_modules")[0]}/logs/`); expect(config.logToFile).toBeTruthy(); }); } diff --git a/src/utils/datetime.ts b/src/utils/datetime.ts index 68b9559..ac23a27 100644 --- a/src/utils/datetime.ts +++ b/src/utils/datetime.ts @@ -13,24 +13,26 @@ export function formatDateTime(timestamp: number) { const mins = date.getMinutes(); const secs = date.getSeconds(); - const mm = (month + 1) > 9 ? month + 1 : `0${month + 1}`; + const mm = month + 1 > 9 ? month + 1 : `0${month + 1}`; const dd = day > 9 ? day : `0${day}`; + + const hh = hour > 9 ? hour : `0${hour}`; const _mins = mins > 9 ? mins : `0${mins}`; const _secs = secs > 9 ? secs : `0${secs}`; - return `${year}-${mm}-${dd} ${ - hour - }:${_mins}:${_secs}`; + return `${year}-${mm}-${dd} ${hh}:${_mins}:${_secs}`; } - /** * Converts a datetime string format to milliseconds - * @param {string} str datetime string in format: [yyyy-mm-dd hh:mm:ss] + * @param {string} str datetime string in format: [yyyy-mm-dd hh:mm:ss] * @returns {number} milliseconds */ export function parseDateTime(str: string) { const timestamp = Date.parse(str.replaceAll(" ", "T")); - if (timestamp === 0 || isNaN(timestamp)) throw new Error("Unable to parse datetime string; Invalid string format. [yyyy/mm/dd, hh:mm:ss]") + if (timestamp === 0 || isNaN(timestamp)) + throw new Error( + "Unable to parse datetime string; Invalid string format. [yyyy/mm/dd, hh:mm:ss]" + ); return timestamp; - } \ No newline at end of file +} diff --git a/tsconfig.json b/tsconfig.json index e5b6d0e..9cf0541 100644 --- a/tsconfig.json +++ b/tsconfig.json @@ -1,11 +1,11 @@ { "compilerOptions": { "target": "es6", /* Set the JavaScript language version for emitted JavaScript and include compatible library declarations. */ - "module": "esnext", /* Specify what module code is generated. */ + "module": "commonjs", /* Specify what module code is generated. */ "lib": ["ESNext"], - "rootDir": "./", /* Specify the root folder within your source files. */ + "rootDir": "./src", /* Specify the root folder within your source files. */ "moduleResolution": "node", /* Specify how TypeScript looks up a file from a given module specifier. */ - "baseUrl": "./src", /* Specify the base directory to resolve non-relative module names. */ + "baseUrl": "./", /* Specify the base directory to resolve non-relative module names. */ // "rootDirs": [], /* Allow multiple folders to be treated as one when resolving modules. */ // "typeRoots": [], /* Specify multiple folders that act like `./node_modules/@types`. */ // "types": [], /* Specify type package names to be included without being referenced in a source file. */ @@ -22,7 +22,9 @@ "skipLibCheck": true, /* Skip type checking all .d.ts files. */ "paths": { "@types": ["types/"], - "@utils/*": ["utils/*"] + "@utils/*": ["src/utils/*"] } - } + }, + "include": ["./src/"], + "exclude": ["*/tests", "/src/tests", "/src/tests/*", "*/**.test.ts", "*/**.spec.ts"], } diff --git a/src/types/index.d.ts b/types/index.d.ts similarity index 100% rename from src/types/index.d.ts rename to types/index.d.ts