Add date, log and number utils

This commit is contained in:
2021-09-13 18:34:26 +07:00
parent df1f0eb101
commit 9d1e61efc7
7 changed files with 162 additions and 5042 deletions

44
src/log/index.ts Normal file
View File

@@ -0,0 +1,44 @@
import chalk from "chalk"
import { formatDate } from "../date"
import Logger from "./writter"
let logger = Logger.getProvider()
const prefixColor = (
prefix: string,
message?: any,
color: string = "green"
) => {
const timestamp = formatDate(new Date())
if (Logger.isEnabled()) {
return `[${timestamp}] - ${prefix}: ${message}`
}
const firstStep = chalk`[${timestamp}] - {${color} ${prefix}}:`
return `${firstStep} ${message}`
}
export const debug = (message?: any, ...args: any[]) => {
const msg = prefixColor("DEBUG", message, "magentaBright")
args.length === 0 ? logger.log(msg) : logger.log(msg, ...args)
}
export const error = (message?: any, ...args: any[]) => {
const msg = prefixColor("ERROR", message, "red")
args.length === 0 ? logger.error(msg) : logger.error(msg, ...args)
}
export const warn = (message?: any, ...args: any[]) => {
const msg = prefixColor("WARN", message, "yellow")
args.length === 0 ? logger.warn(msg) : logger.warn(msg, ...args)
}
export const info = (message?: any, ...args: any[]) => {
const msg = prefixColor("INFO", message, "cyan")
args.length === 0 ? logger.info(msg) : logger.info(msg, ...args)
}
export const success = (message?: any, ...args: any[]) => {
const msg = prefixColor("SUCCESS", message)
args.length === 0 ? logger.info(msg) : logger.info(msg, ...args)
}

55
src/log/writter.ts Normal file
View File

@@ -0,0 +1,55 @@
import * as fs from "fs"
import { Console } from "console"
import * as path from "path"
import { formatDateOnly } from "../date"
class Logger {
private static enabled: boolean = false
public static setEnabled(enabled: boolean): void {
this.enabled = enabled
}
public static isEnabled(): boolean {
return this.enabled
}
private static logDir?: string
public static setLogDir(logDir: string): void {
this.logDir = logDir
}
public static getLogDir(): string | null | undefined {
return this.logDir
}
public static getProvider(): Console {
if (this.isEnabled()) {
const rootPath = path.resolve(this.getLogDir() || "./")
const logPath = `${rootPath}/logs`
if (!fs.existsSync(logPath)) {
fs.mkdirSync(logPath, { recursive: true })
}
const time = formatDateOnly(new Date()).replace(/\//g, "-")
console.log("Logs writing to path =>", logPath)
const output = fs.createWriteStream(
`${logPath}/stdout-${time}.log`,
{
flags: "a",
}
)
const errorOutput = fs.createWriteStream(
`${logPath}/stderr-${time}.log`,
{
flags: "a",
}
)
return new Console({ stdout: output, stderr: errorOutput })
}
return console
}
}
export default Logger