This commit is contained in:
2024-11-09 19:15:29 -05:00
parent 6d6e63ea0d
commit 23e234eac0
13 changed files with 460 additions and 9 deletions
+4
View File
@@ -36,6 +36,7 @@ export const jjEnsure = async (opts) => {
if (_.isEmpty(jjYamlObj?.environments || {})) {
opts.context.error(`Wrong ${answer.jjYamlPath} file`)
}
jjConfigs.jjWorkSpacePath = path.dirname(answer.jjYamlPath)
jjConfigs.jjYamlObj = jjYamlObj
@@ -43,6 +44,7 @@ export const jjEnsure = async (opts) => {
} else {
jjConfigs.jjYamlPath = await fs.readFile(jjConfigs.configSaveFilePath, "utf8")
jjConfigs.jjWorkSpacePath = path.dirname(jjConfigs.jjYamlPath)
const jjYamlRawContent = await fs.readFile(jjConfigs.jjYamlPath, "utf8")
const jjYamlObj: any = YAML.load(jjYamlRawContent)
if (_.isEmpty(jjYamlObj?.environments || {})) {
@@ -51,4 +53,6 @@ export const jjEnsure = async (opts) => {
jjConfigs.jjYamlObj = jjYamlObj
}
jjConfigs.processEnvs.JJ_WORKSPACE_DIR = jjConfigs.jjWorkSpacePath
}
+131
View File
@@ -0,0 +1,131 @@
#!/usr/bin/env bun
import { pino, type LoggerOptions, type Level } from 'pino';
import os from 'os';
import path from 'path';
import { fileURLToPath } from 'url';
import chalk from 'chalk';
import { customLevels } from './pino-pretty-transport';
import _ from 'lodash'
export const jjLoggerObj = {}
const __filename = fileURLToPath(import.meta.url);
const logFilePath = `${process.env.JJ_SOURCE_DIR}/~~tmp/jj.log`;
jjLoggerObj['logFilePath'] = logFilePath
export const jjLogger = pino({
customLevels: customLevels,
level: 'info',
base: {
host: os.hostname(),
filename: path.basename(__filename),
app: 'jj',
},
transport: {
targets: [
{
target: 'pino/file',
options: { destination: logFilePath, mkdir: true },
level: 'info',
},
{
target: './pino-pretty-transport',
},
],
}
});
jjLoggerObj['jjLogger'] = jjLogger
export const makeJJlogger = (opt) => {
const childJJLogger = jjLogger.child({
...opt
})
return childJJLogger
}
jjLoggerObj['makeJJlogger'] = makeJJlogger
export const jjLog = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.log(message);
}
jjLoggerObj['jjLog'] = jjLog
// jjLog('jjLog', { test1: 'test1' })
export const jjLogInfo = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.info(message, opt);
}
jjLoggerObj['jjLogInfo'] = jjLogInfo
// jjLogInfo('jjLogInfo', { test1: 'test1' })
export const jjLogHeading = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.heading(`=======================================================
${message}
========================================================`, opt);
}
jjLoggerObj['jjLogHeading'] = jjLogHeading
// jjLogHeading('jjLogHeading', { test1: 'test1' })
export const jjLogAction = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.action(`${message}`, opt);
}
jjLoggerObj['jjLogAction'] = jjLogAction
// jjLogAction('jjLogAction', { test1: 'test1' })
export const jjLogError = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.error(message, opt);
}
jjLoggerObj['jjLogError'] = jjLogError
// jjLogError('jjLogError')
export const jjLogWarning = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.warn(message, opt);
}
jjLoggerObj['jjLogWarning'] = jjLogWarning
// jjLogWarning('jjLogWarning', { test1: 'test1' })
export const jjLogSuccess = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.success(message, opt);
}
jjLoggerObj['jjLogSuccess'] = jjLogSuccess
// jjLogSuccess('jjLogSuccess', { test1: 'test1' })
export const jjBgRed = (message, opt = {}) => {
const cLogger = makeJJlogger(opt)
cLogger.bgRed(message, opt);
}
jjLoggerObj['jjBgRed'] = jjBgRed
// jjBgRed('jjBgRed', { test1: 'test1' })
if (_.get(process.argv, "[1]", "")?.includes('helpers/jjLogger.ts')) {
const args = [...process.argv]
args.shift()
args.shift()
if (args.length > 0) {
const loggerCal = jjLoggerObj[args[0]]
args.shift()
const [, ...restArgs] = [, ...args]
const message = restArgs[0]
if(!message){
process.exit(0)
}
restArgs.shift()
loggerCal(message, { ...restArgs })
}
}
+160
View File
@@ -0,0 +1,160 @@
import _ from 'lodash';
import pino from 'pino';
import chalk from 'chalk';
import moment from 'moment';
import { safeStringify } from './safeJson';
export const customLevels = {
...pino.levels.values,
log: 31,
action: 32,
heading: 33,
success: 35,
bgRed: 36
};
// https://github.com/chalk/chalk
const customColors = {
trace: "cyan",
debug: "blue",
info: "reset",
warn: "yellow",
error: "red",
fatal: "red",
log: 'white',
action: 'magenta',
heading: 'whiteBright',
success: "green",
bgRed: 'bgRed'
}
const customBold = {
trace: false,
debug: false,
info: false,
warn: true,
error: true,
fatal: true,
log: false,
action: true,
heading: true,
success: true,
bgRed: true
}
const customLevelsById = {}
Object.keys(customLevels).forEach((levelKey) => {
customLevelsById[customLevels[levelKey]] = {
levelKey,
color: customColors[levelKey],
isBold: customBold[levelKey] || false
}
})
function hostFormat(str) {
if (str.length < 9) {
const firstPart = str.slice(0, 5);
const remainingPart = str.slice(5);
return `${firstPart}#${remainingPart}`;
}
const firstPart = str.slice(0, 5);
const lastPart = str.slice(-4);
return `${firstPart}#${lastPart}`;
}
function messageMultilineToArray(message) {
// Split the message by newline characters (\n or \r\n)
const lines = message.split(/\r?\n/);
return lines;
}
function formatLogLevelString(str) {
const newStr = str.slice(0, 3);
if (newStr.length < 3) {
return newStr.padEnd(3, ' '); // Pad with spaces to reach 3 characters
}
return newStr.slice(0, 3); // Trim to 25 characters
}
function removeTrailingNewline(str) {
return str.replace(/[\r\n]+$/, '');
}
export default (opts) => require('pino-pretty')({
...opts,
customLevels: Object.entries(customLevels).map(([key, value]) => (`${key}:${value}`)).join(','),
customColors: customColors,
colorize: true,
colorizeObjects: true,
// crlf: true,
ignore: 'time,level',
// singleLine: true,
hideObject: true,
// levelLabel: 'levelLabel', // --levelLabel
// translateTime: 'SYS:standard',
// include: 'host,pid,time,level,filename,app', // --include
// sync: true
// messageFormat: (log, messageKey, levelLabel) => {
// // do some log message customization
// return "";
// }
messageFormat: (log, messageKey) => {
const logConfigObj = customLevelsById[log.level]
const cloneLog = _.cloneDeep(log)
let prefixMessage = ``
if (cloneLog.time) {
prefixMessage += `${moment(cloneLog.time).format('DDHHmmss')}#`
delete cloneLog.time
}
if (cloneLog.host) {
prefixMessage += `${hostFormat(cloneLog.host)}_`
delete cloneLog.host
}
if (cloneLog.app) {
prefixMessage += `${cloneLog.app}=`
delete cloneLog.app
}
if (cloneLog.filename) {
prefixMessage += `${cloneLog.filename} `
delete cloneLog.filename
}
prefixMessage += formatLogLevelString(`${logConfigObj.levelKey.toUpperCase()}: `)
const messageList = messageMultilineToArray(cloneLog[messageKey])
delete cloneLog.msg
delete cloneLog.level
let message = ''
messageList.forEach(mes=> {
message += `${prefixMessage} ${mes}\n`
})
message = removeTrailingNewline(message)
if (!_.isEmpty(cloneLog)) {
message += `\n${prefixMessage} ${safeStringify(cloneLog)}`
}
if (logConfigObj.color?.startsWith('bg')) {
return chalk[logConfigObj.color](message)
}
if (logConfigObj.isBold) {
return chalk.bold[logConfigObj.color](message)
}
return chalk[logConfigObj.color](message)
}
})
+13
View File
@@ -0,0 +1,13 @@
export function safeStringify(obj) {
const seen = new WeakSet();
return JSON.stringify(obj, (key, value) => {
if (typeof value === "object" && value !== null) {
if (seen.has(value)) {
return `[Circular ${key}]`; // Label circular reference with the key
}
seen.add(value);
}
return value;
});
}