zario 0.2.1 → 0.2.6
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/dist/core/Logger.d.ts +11 -3
- package/dist/index.js +3 -3
- package/dist/index.mjs +3 -3
- package/dist/utils/Timerutil.d.ts +8 -0
- package/package.json +1 -1
package/dist/core/Logger.d.ts
CHANGED
|
@@ -11,7 +11,7 @@ export interface LoggerOptions {
|
|
|
11
11
|
timestamp?: boolean;
|
|
12
12
|
context?: Record<string, any>;
|
|
13
13
|
parent?: Logger;
|
|
14
|
-
|
|
14
|
+
asyncMode?: boolean;
|
|
15
15
|
customLevels?: {
|
|
16
16
|
[level: string]: number;
|
|
17
17
|
};
|
|
@@ -28,14 +28,21 @@ export declare class Logger {
|
|
|
28
28
|
private asyncMode;
|
|
29
29
|
private customLevels;
|
|
30
30
|
private static _global;
|
|
31
|
+
private static readonly LEVEL_PRIORITIES;
|
|
31
32
|
prefix: string;
|
|
32
33
|
timestamp: boolean;
|
|
33
34
|
constructor(options?: LoggerOptions);
|
|
35
|
+
private isProductionEnvironment;
|
|
36
|
+
private getDefaultLevel;
|
|
37
|
+
private getDefaultColorizeValue;
|
|
38
|
+
private getDefaultJson;
|
|
39
|
+
private getDefaultTimestamp;
|
|
40
|
+
private getDefaultTransports;
|
|
41
|
+
private getDefaultAsyncMode;
|
|
34
42
|
private initTransports;
|
|
35
43
|
private shouldLog;
|
|
36
44
|
private getLevelPriority;
|
|
37
45
|
private log;
|
|
38
|
-
private logAsync;
|
|
39
46
|
private logAsyncDirect;
|
|
40
47
|
debug(message: string, metadata?: Record<string, any>): void;
|
|
41
48
|
info(message: string, metadata?: Record<string, any>): void;
|
|
@@ -49,9 +56,10 @@ export declare class Logger {
|
|
|
49
56
|
logWithLevel(level: LogLevel, message: string, metadata?: Record<string, any>): void;
|
|
50
57
|
setLevel(level: LogLevel): void;
|
|
51
58
|
setFormat(format: "text" | "json"): void;
|
|
52
|
-
|
|
59
|
+
setAsyncMode(asyncMode: boolean): void;
|
|
53
60
|
addTransport(transport: Transport): void;
|
|
54
61
|
getTimestampSetting(): boolean;
|
|
55
62
|
static get global(): Logger;
|
|
56
63
|
createChild(options?: LoggerOptions): Logger;
|
|
64
|
+
startTimer(name: string): any;
|
|
57
65
|
}
|
package/dist/index.js
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
"use strict";var
|
|
2
|
-
`;
|
|
3
|
-
`;await new Promise((o,
|
|
1
|
+
"use strict";var E=Object.create;var x=Object.defineProperty;var A=Object.getOwnPropertyDescriptor;var I=Object.getOwnPropertyNames;var M=Object.getPrototypeOf,j=Object.prototype.hasOwnProperty;var $=(a,t)=>()=>(a&&(t=a(a=0)),t);var O=(a,t)=>{for(var e in t)x(a,e,{get:t[e],enumerable:!0})},P=(a,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of I(t))!j.call(a,r)&&r!==e&&x(a,r,{get:()=>t[r],enumerable:!(i=A(t,r))||i.enumerable});return a};var D=(a,t,e)=>(e=a!=null?E(M(a)):{},P(t||!a||!a.__esModule?x(e,"default",{value:a,enumerable:!0}):e,a)),w=a=>P(x({},"__esModule",{value:!0}),a);var C={};O(C,{Timer:()=>S});var S,z=$(()=>{"use strict";S=class{constructor(t,e){this.hasEnded=!1;this.name=t,this.logFn=e,this.startTime=Date.now()}end(){if(this.hasEnded)return;let e=Date.now()-this.startTime;this.logFn(`${this.name} took ${e}ms`),this.hasEnded=!0}}});var Y={};O(Y,{ConsoleTransport:()=>d,FileTransport:()=>v,Logger:()=>y,default:()=>N});module.exports=w(Y);var L=class{static format(t,e){if(e==="ISO")return t.toISOString();if(e==="UTC")return t.toUTCString();if(e==="LOCAL")return t.toLocaleString();let i=t.getFullYear(),r=t.getMonth()+1,o=t.getDate(),l=t.getHours(),p=t.getMinutes(),m=t.getSeconds(),f=t.getMilliseconds(),c=[],s=0,g=0;for(;s<e.length;)e[s]==="Y"&&s+3<e.length&&e.slice(s,s+4)==="YYYY"?(c.push(e.substring(g,s)),c.push(i.toString().padStart(4,"0")),s+=4,g=s):e[s]==="M"&&s+1<e.length&&e.slice(s,s+2)==="MM"?(c.push(e.substring(g,s)),c.push(r.toString().padStart(2,"0")),s+=2,g=s):e[s]==="D"&&s+1<e.length&&e.slice(s,s+2)==="DD"?(c.push(e.substring(g,s)),c.push(o.toString().padStart(2,"0")),s+=2,g=s):e[s]==="H"&&s+1<e.length&&e.slice(s,s+2)==="HH"?(c.push(e.substring(g,s)),c.push(l.toString().padStart(2,"0")),s+=2,g=s):e[s]==="m"&&s+1<e.length&&e.slice(s,s+2)==="mm"?(c.push(e.substring(g,s)),c.push(p.toString().padStart(2,"0")),s+=2,g=s):e[s]==="s"&&s+1<e.length&&e.slice(s,s+2)==="ss"?(c.push(e.substring(g,s)),c.push(m.toString().padStart(2,"0")),s+=2,g=s):e[s]==="S"&&s+2<e.length&&e.slice(s,s+3)==="SSS"?(c.push(e.substring(g,s)),c.push(f.toString().padStart(3,"0")),s+=3,g=s):s++;return c.push(e.substring(g)),c.join("")}};var F=class a{static{this.ANSI_COLORS={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[36m",boring:"\x1B[37m",reset:"\x1B[0m"}}static colorize(t,e){return process.env.FORCE_COLOR!=="0"&&(process.stdout.isTTY||process.env.FORCE_COLOR==="1")?`${a.ANSI_COLORS[e]||a.ANSI_COLORS.reset}${t}${a.ANSI_COLORS.reset}`:t}};var b=class{constructor(t={}){let{colorize:e=!0,json:i=!1,timestampFormat:r="YYYY-MM-DD HH:mm:ss",timestamp:o=!1,customColors:l={}}=t;this.colorize=e,this.json=i,this.timestampFormat=r,this.timestamp=o,this.customColors=l}format(t){return this.json?this.formatAsJson(t):this.formatAsText(t)}formatAsJson(t){let e={level:t.level,message:t.message,...t.metadata};return this.timestamp&&(e.timestamp=t.timestamp.toISOString()),t.prefix&&(e.prefix=t.prefix),JSON.stringify(e)}formatAsText(t){let e=[];if(this.timestamp){let r=L.format(t.timestamp,this.timestampFormat);e.push(`[${r}] `)}t.prefix&&e.push(`${t.prefix} `);let i=t.level.toUpperCase();if(this.colorize){let r=this.customColors[t.level]||t.level;i=F.colorize(i,r)}return e.push(`[${i}] `),e.push(t.message),t.metadata&&e.push(` ${JSON.stringify(t.metadata)}`),e.join("")}setJson(t){this.json=t}isColorized(){return this.colorize}isJson(){return this.json}getTimestampFormat(){return this.timestampFormat}hasTimestamp(){return this.timestamp}getCustomColors(){return{...this.customColors}}};var d=class{constructor(t={}){let{colorize:e=!0}=t;this.colorize=e}write(t,e){let i=e.colorize;this.colorize!==i&&(e.colorize=this.colorize);let r=e.format(t);switch(this.colorize!==i&&(e.colorize=i),t.level){case"error":console.error(r);break;case"warn":console.warn(r);break;default:console.log(r);break}}async writeAsync(t,e){return setImmediate(()=>{this.write(t,e)}),Promise.resolve()}};var n=D(require("fs"),1),h=D(require("path"),1),v=class{constructor(t){let{path:e,maxSize:i=10*1024*1024,maxFiles:r=5}=t;this.filePath=e,this.maxSize=i,this.maxFiles=r;let o=h.dirname(this.filePath);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.existsSync(this.filePath)||n.writeFileSync(this.filePath,"","utf8")}write(t,e){let r=e.format(t)+`
|
|
2
|
+
`;n.appendFileSync(this.filePath,r),this.rotateIfNeeded()}async writeAsync(t,e){let r=e.format(t)+`
|
|
3
|
+
`;await new Promise((o,l)=>{n.appendFile(this.filePath,r,p=>{if(p){l(p);return}o()})}),await this.rotateIfNeededAsync()}rotateIfNeeded(){if(n.existsSync(this.filePath))try{n.statSync(this.filePath).size>=this.maxSize&&this.rotateFiles()}catch(t){console.error("Error checking file size for rotation:",t)}}async rotateIfNeededAsync(){if(n.existsSync(this.filePath))try{n.statSync(this.filePath).size>=this.maxSize&&await this.rotateFilesAsync()}catch(t){console.error("Error during rotation check:",t)}}rotateFiles(){try{let t="";n.existsSync(this.filePath)&&(t=n.readFileSync(this.filePath,"utf8"));let e=this.getRotatedFilePath();n.writeFileSync(e,t,"utf8"),n.writeFileSync(this.filePath,"","utf8"),this.cleanupOldFiles()}catch(t){console.error("Error during file rotation:",t)}}async rotateFilesAsync(){try{let t="";n.existsSync(this.filePath)&&(t=await n.promises.readFile(this.filePath,"utf8"));let e=this.getRotatedFilePath();await n.promises.writeFile(e,t,"utf8"),await n.promises.writeFile(this.filePath,"","utf8"),await this.cleanupOldFilesAsync()}catch(t){console.error("Error during async file rotation:",t)}}getRotatedFilePath(){let t=h.dirname(this.filePath),e=h.basename(this.filePath),i=Date.now();return h.join(t,`${e}.${i}`)}cleanupOldFiles(){try{let t=h.dirname(this.filePath),e=h.basename(this.filePath);try{n.accessSync(t,n.constants.F_OK)}catch{return}let r=n.readdirSync(t).filter(o=>!o||o===e?!1:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+$`).test(o)).sort((o,l)=>{let p=parseInt(o.split(".").pop()||"0");return parseInt(l.split(".").pop()||"0")-p});for(let o=this.maxFiles;o<r.length;o++){let l=r[o];if(l){if(l.includes("../")||l.includes("..\\")||l.startsWith(".."))continue;let p=h.join(t,l),m=h.resolve(p),f=h.resolve(t);if(!m.startsWith(f+h.sep)&&m!==f)continue;try{n.unlinkSync(p)}catch(c){console.error(`Failed to delete old log file ${p}:`,c)}}}}catch(t){console.error("Error during cleanup of old files:",t)}}async cleanupOldFilesAsync(){try{let t=h.dirname(this.filePath),e=h.basename(this.filePath);try{await n.promises.access(t,n.constants.F_OK)}catch{return}let r=(await n.promises.readdir(t)).filter(l=>!l||l===e?!1:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+$`).test(l)).sort((l,p)=>{let m=parseInt(l.split(".").pop()||"0");return parseInt(p.split(".").pop()||"0")-m}),o=[];for(let l=this.maxFiles;l<r.length;l++){let p=r[l];if(p){if(p.includes("../")||p.includes("..\\")||p.startsWith(".."))continue;let m=h.join(t,p),f=h.resolve(m),c=h.resolve(t);if(!f.startsWith(c+h.sep)&&f!==c)continue;o.push(n.promises.access(m,n.constants.F_OK).then(()=>n.promises.unlink(m)).catch(s=>{s.code!=="ENOENT"&&console.error(`Failed to delete old log file ${m}:`,s)}))}}await Promise.all(o)}catch(t){console.error("Error during async cleanup of old files:",t)}}};var y=class a{constructor(t={}){this.transports=[];let{level:e,colorize:i,json:r,transports:o=[],timestampFormat:l="YYYY-MM-DD HH:mm:ss",prefix:p,timestamp:m,context:f={},parent:c,asyncMode:s,customLevels:g={},customColors:T={}}=t;if(this.parent=c,this.context={...f},this.customLevels=g,this.asyncMode=!1,this.parent){this.level=e??this.parent.level,this.prefix=p??this.parent.prefix,this.timestamp=m??this.parent.timestamp,this.asyncMode=s??this.parent.asyncMode,this.transports=o&&o.length>0?this.initTransports(o,this.getDefaultColorizeValue(i)):this.parent.transports;let u={...this.parent.formatter.getCustomColors(),...T};this.formatter=new b({colorize:this.getDefaultColorizeValue(i)??this.parent.formatter.isColorized(),json:r??this.parent.formatter.isJson(),timestampFormat:l??this.parent.formatter.getTimestampFormat(),timestamp:m??this.parent.formatter.hasTimestamp(),customColors:u}),this.context={...this.parent.context,...this.context},this.customLevels={...this.parent.customLevels,...g}}else{let u=this.isProductionEnvironment();this.level=e??this.getDefaultLevel(u),this.prefix=p??"",this.timestamp=m??this.getDefaultTimestamp(u);let R=o&&o.length>0?o:this.getDefaultTransports(u);this.asyncMode=s??this.getDefaultAsyncMode(u),this.transports=this.initTransports(R,this.getDefaultColorizeValue(i)),this.formatter=new b({colorize:this.getDefaultColorizeValue(i),json:r??this.getDefaultJson(u),timestampFormat:l,timestamp:this.getDefaultTimestamp(u),customColors:T})}a._global||(a._global=this)}static{this.LEVEL_PRIORITIES={silent:0,boring:1,debug:2,info:3,warn:4,error:5}}isProductionEnvironment(){let t=process.env.NODE_ENV?.toLowerCase();return t==="production"||t==="prod"}getDefaultLevel(t){return t?"warn":"debug"}getDefaultColorizeValue(t){return t!==void 0?t:!this.isProductionEnvironment()}getDefaultJson(t){return t}getDefaultTimestamp(t){return!0}getDefaultTransports(t){return t?[{type:"console"},{type:"file",options:{path:"./logs/app.log"}}]:[{type:"console"}]}getDefaultAsyncMode(t){return t}initTransports(t,e){let i=[];for(let r of t)if(r.type==="console"){let o=new d({colorize:r.options?.colorize??e});i.push(o)}else if(r.type==="file"){if(r.options?.path){let o={path:r.options.path};r.options.maxSize!==void 0&&(o.maxSize=r.options.maxSize),r.options.maxFiles!==void 0&&(o.maxFiles=r.options.maxFiles);let l=new v(o);i.push(l)}}else r.type==="custom"&&r.instance&&i.push(r.instance);return i}shouldLog(t){let e=this.getLevelPriority(this.level);return this.getLevelPriority(t)>=e}getLevelPriority(t){if(a.LEVEL_PRIORITIES.hasOwnProperty(t))return a.LEVEL_PRIORITIES[t];if(this.customLevels&&t in this.customLevels){let e=this.customLevels[t];return e!==void 0?e:999}return 999}log(t,e,i){if(this.shouldLog(t)&&t!=="silent")if(this.asyncMode)this.logAsyncDirect(t,e,i);else{let r=new Date,o;this.context&&Object.keys(this.context).length>0?i?o={...this.context,...i}:o=this.context:i&&(o=i);let l={level:t,message:e,timestamp:r,metadata:o&&Object.keys(o).length>0?o:void 0,prefix:this.prefix};for(let p of this.transports)p.write(l,this.formatter)}}logAsyncDirect(t,e,i){if(!this.shouldLog(t)||t==="silent")return;let r=new Date,o;this.context&&Object.keys(this.context).length>0?i?o={...this.context,...i}:o=this.context:i&&(o=i);let l={level:t,message:e,timestamp:r,metadata:o&&Object.keys(o).length>0?o:void 0,prefix:this.prefix};for(let p of this.transports)p.writeAsync?p.writeAsync(l,this.formatter).catch(m=>{console.error("Error during async logging:",m)}):setImmediate(()=>{p.write(l,this.formatter)})}debug(t,e){this.log("debug",t,e)}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}error(t,e){this.log("error",t,e)}silent(t,e){this.log("silent",t,e)}boring(t,e){this.log("boring",t,e)}logWithLevel(t,e,i){this.log(t,e,i)}setLevel(t){this.level=t}setFormat(t){this.formatter.setJson(t==="json")}setAsyncMode(t){this.asyncMode=t}addTransport(t){this.transports.push(t)}getTimestampSetting(){return this.timestamp}static get global(){return a._global||(a._global=new a),a._global}createChild(t={}){return new a({...t,parent:this})}startTimer(t){let{Timer:e}=(z(),w(C));return new e(t,i=>this.info(i))}};var N=y;0&&(module.exports={ConsoleTransport,FileTransport,Logger});
|
package/dist/index.mjs
CHANGED
|
@@ -1,3 +1,3 @@
|
|
|
1
|
-
var
|
|
2
|
-
`;
|
|
3
|
-
`;await new Promise((
|
|
1
|
+
var F=Object.defineProperty;var w=Object.getOwnPropertyDescriptor;var C=Object.getOwnPropertyNames;var z=Object.prototype.hasOwnProperty;var R=(l,t)=>()=>(l&&(t=l(l=0)),t);var E=(l,t)=>{for(var e in t)F(l,e,{get:t[e],enumerable:!0})},A=(l,t,e,i)=>{if(t&&typeof t=="object"||typeof t=="function")for(let r of C(t))!z.call(l,r)&&r!==e&&F(l,r,{get:()=>t[r],enumerable:!(i=w(t,r))||i.enumerable});return l};var I=l=>A(F({},"__esModule",{value:!0}),l);var O={};E(O,{Timer:()=>S});var S,P=R(()=>{"use strict";S=class{constructor(t,e){this.hasEnded=!1;this.name=t,this.logFn=e,this.startTime=Date.now()}end(){if(this.hasEnded)return;let e=Date.now()-this.startTime;this.logFn(`${this.name} took ${e}ms`),this.hasEnded=!0}}});var y=class{static format(t,e){if(e==="ISO")return t.toISOString();if(e==="UTC")return t.toUTCString();if(e==="LOCAL")return t.toLocaleString();let i=t.getFullYear(),r=t.getMonth()+1,o=t.getDate(),a=t.getHours(),p=t.getMinutes(),m=t.getSeconds(),f=t.getMilliseconds(),c=[],s=0,g=0;for(;s<e.length;)e[s]==="Y"&&s+3<e.length&&e.slice(s,s+4)==="YYYY"?(c.push(e.substring(g,s)),c.push(i.toString().padStart(4,"0")),s+=4,g=s):e[s]==="M"&&s+1<e.length&&e.slice(s,s+2)==="MM"?(c.push(e.substring(g,s)),c.push(r.toString().padStart(2,"0")),s+=2,g=s):e[s]==="D"&&s+1<e.length&&e.slice(s,s+2)==="DD"?(c.push(e.substring(g,s)),c.push(o.toString().padStart(2,"0")),s+=2,g=s):e[s]==="H"&&s+1<e.length&&e.slice(s,s+2)==="HH"?(c.push(e.substring(g,s)),c.push(a.toString().padStart(2,"0")),s+=2,g=s):e[s]==="m"&&s+1<e.length&&e.slice(s,s+2)==="mm"?(c.push(e.substring(g,s)),c.push(p.toString().padStart(2,"0")),s+=2,g=s):e[s]==="s"&&s+1<e.length&&e.slice(s,s+2)==="ss"?(c.push(e.substring(g,s)),c.push(m.toString().padStart(2,"0")),s+=2,g=s):e[s]==="S"&&s+2<e.length&&e.slice(s,s+3)==="SSS"?(c.push(e.substring(g,s)),c.push(f.toString().padStart(3,"0")),s+=3,g=s):s++;return c.push(e.substring(g)),c.join("")}};var x=class l{static{this.ANSI_COLORS={black:"\x1B[30m",red:"\x1B[31m",green:"\x1B[32m",yellow:"\x1B[33m",blue:"\x1B[34m",magenta:"\x1B[35m",cyan:"\x1B[36m",white:"\x1B[37m",brightRed:"\x1B[91m",brightGreen:"\x1B[92m",brightYellow:"\x1B[93m",brightBlue:"\x1B[94m",brightMagenta:"\x1B[95m",brightCyan:"\x1B[96m",brightWhite:"\x1B[97m",info:"\x1B[32m",warn:"\x1B[33m",error:"\x1B[31m",debug:"\x1B[36m",boring:"\x1B[37m",reset:"\x1B[0m"}}static colorize(t,e){return process.env.FORCE_COLOR!=="0"&&(process.stdout.isTTY||process.env.FORCE_COLOR==="1")?`${l.ANSI_COLORS[e]||l.ANSI_COLORS.reset}${t}${l.ANSI_COLORS.reset}`:t}};var d=class{constructor(t={}){let{colorize:e=!0,json:i=!1,timestampFormat:r="YYYY-MM-DD HH:mm:ss",timestamp:o=!1,customColors:a={}}=t;this.colorize=e,this.json=i,this.timestampFormat=r,this.timestamp=o,this.customColors=a}format(t){return this.json?this.formatAsJson(t):this.formatAsText(t)}formatAsJson(t){let e={level:t.level,message:t.message,...t.metadata};return this.timestamp&&(e.timestamp=t.timestamp.toISOString()),t.prefix&&(e.prefix=t.prefix),JSON.stringify(e)}formatAsText(t){let e=[];if(this.timestamp){let r=y.format(t.timestamp,this.timestampFormat);e.push(`[${r}] `)}t.prefix&&e.push(`${t.prefix} `);let i=t.level.toUpperCase();if(this.colorize){let r=this.customColors[t.level]||t.level;i=x.colorize(i,r)}return e.push(`[${i}] `),e.push(t.message),t.metadata&&e.push(` ${JSON.stringify(t.metadata)}`),e.join("")}setJson(t){this.json=t}isColorized(){return this.colorize}isJson(){return this.json}getTimestampFormat(){return this.timestampFormat}hasTimestamp(){return this.timestamp}getCustomColors(){return{...this.customColors}}};var v=class{constructor(t={}){let{colorize:e=!0}=t;this.colorize=e}write(t,e){let i=e.colorize;this.colorize!==i&&(e.colorize=this.colorize);let r=e.format(t);switch(this.colorize!==i&&(e.colorize=i),t.level){case"error":console.error(r);break;case"warn":console.warn(r);break;default:console.log(r);break}}async writeAsync(t,e){return setImmediate(()=>{this.write(t,e)}),Promise.resolve()}};import*as n from"fs";import*as h from"path";var b=class{constructor(t){let{path:e,maxSize:i=10*1024*1024,maxFiles:r=5}=t;this.filePath=e,this.maxSize=i,this.maxFiles=r;let o=h.dirname(this.filePath);n.existsSync(o)||n.mkdirSync(o,{recursive:!0}),n.existsSync(this.filePath)||n.writeFileSync(this.filePath,"","utf8")}write(t,e){let r=e.format(t)+`
|
|
2
|
+
`;n.appendFileSync(this.filePath,r),this.rotateIfNeeded()}async writeAsync(t,e){let r=e.format(t)+`
|
|
3
|
+
`;await new Promise((o,a)=>{n.appendFile(this.filePath,r,p=>{if(p){a(p);return}o()})}),await this.rotateIfNeededAsync()}rotateIfNeeded(){if(n.existsSync(this.filePath))try{n.statSync(this.filePath).size>=this.maxSize&&this.rotateFiles()}catch(t){console.error("Error checking file size for rotation:",t)}}async rotateIfNeededAsync(){if(n.existsSync(this.filePath))try{n.statSync(this.filePath).size>=this.maxSize&&await this.rotateFilesAsync()}catch(t){console.error("Error during rotation check:",t)}}rotateFiles(){try{let t="";n.existsSync(this.filePath)&&(t=n.readFileSync(this.filePath,"utf8"));let e=this.getRotatedFilePath();n.writeFileSync(e,t,"utf8"),n.writeFileSync(this.filePath,"","utf8"),this.cleanupOldFiles()}catch(t){console.error("Error during file rotation:",t)}}async rotateFilesAsync(){try{let t="";n.existsSync(this.filePath)&&(t=await n.promises.readFile(this.filePath,"utf8"));let e=this.getRotatedFilePath();await n.promises.writeFile(e,t,"utf8"),await n.promises.writeFile(this.filePath,"","utf8"),await this.cleanupOldFilesAsync()}catch(t){console.error("Error during async file rotation:",t)}}getRotatedFilePath(){let t=h.dirname(this.filePath),e=h.basename(this.filePath),i=Date.now();return h.join(t,`${e}.${i}`)}cleanupOldFiles(){try{let t=h.dirname(this.filePath),e=h.basename(this.filePath);try{n.accessSync(t,n.constants.F_OK)}catch{return}let r=n.readdirSync(t).filter(o=>!o||o===e?!1:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+$`).test(o)).sort((o,a)=>{let p=parseInt(o.split(".").pop()||"0");return parseInt(a.split(".").pop()||"0")-p});for(let o=this.maxFiles;o<r.length;o++){let a=r[o];if(a){if(a.includes("../")||a.includes("..\\")||a.startsWith(".."))continue;let p=h.join(t,a),m=h.resolve(p),f=h.resolve(t);if(!m.startsWith(f+h.sep)&&m!==f)continue;try{n.unlinkSync(p)}catch(c){console.error(`Failed to delete old log file ${p}:`,c)}}}}catch(t){console.error("Error during cleanup of old files:",t)}}async cleanupOldFilesAsync(){try{let t=h.dirname(this.filePath),e=h.basename(this.filePath);try{await n.promises.access(t,n.constants.F_OK)}catch{return}let r=(await n.promises.readdir(t)).filter(a=>!a||a===e?!1:new RegExp(`^${e.replace(/[.*+?^${}()|[\]\\]/g,"\\$&")}\\.\\d+$`).test(a)).sort((a,p)=>{let m=parseInt(a.split(".").pop()||"0");return parseInt(p.split(".").pop()||"0")-m}),o=[];for(let a=this.maxFiles;a<r.length;a++){let p=r[a];if(p){if(p.includes("../")||p.includes("..\\")||p.startsWith(".."))continue;let m=h.join(t,p),f=h.resolve(m),c=h.resolve(t);if(!f.startsWith(c+h.sep)&&f!==c)continue;o.push(n.promises.access(m,n.constants.F_OK).then(()=>n.promises.unlink(m)).catch(s=>{s.code!=="ENOENT"&&console.error(`Failed to delete old log file ${m}:`,s)}))}}await Promise.all(o)}catch(t){console.error("Error during async cleanup of old files:",t)}}};var L=class l{constructor(t={}){this.transports=[];let{level:e,colorize:i,json:r,transports:o=[],timestampFormat:a="YYYY-MM-DD HH:mm:ss",prefix:p,timestamp:m,context:f={},parent:c,asyncMode:s,customLevels:g={},customColors:T={}}=t;if(this.parent=c,this.context={...f},this.customLevels=g,this.asyncMode=!1,this.parent){this.level=e??this.parent.level,this.prefix=p??this.parent.prefix,this.timestamp=m??this.parent.timestamp,this.asyncMode=s??this.parent.asyncMode,this.transports=o&&o.length>0?this.initTransports(o,this.getDefaultColorizeValue(i)):this.parent.transports;let u={...this.parent.formatter.getCustomColors(),...T};this.formatter=new d({colorize:this.getDefaultColorizeValue(i)??this.parent.formatter.isColorized(),json:r??this.parent.formatter.isJson(),timestampFormat:a??this.parent.formatter.getTimestampFormat(),timestamp:m??this.parent.formatter.hasTimestamp(),customColors:u}),this.context={...this.parent.context,...this.context},this.customLevels={...this.parent.customLevels,...g}}else{let u=this.isProductionEnvironment();this.level=e??this.getDefaultLevel(u),this.prefix=p??"",this.timestamp=m??this.getDefaultTimestamp(u);let D=o&&o.length>0?o:this.getDefaultTransports(u);this.asyncMode=s??this.getDefaultAsyncMode(u),this.transports=this.initTransports(D,this.getDefaultColorizeValue(i)),this.formatter=new d({colorize:this.getDefaultColorizeValue(i),json:r??this.getDefaultJson(u),timestampFormat:a,timestamp:this.getDefaultTimestamp(u),customColors:T})}l._global||(l._global=this)}static{this.LEVEL_PRIORITIES={silent:0,boring:1,debug:2,info:3,warn:4,error:5}}isProductionEnvironment(){let t=process.env.NODE_ENV?.toLowerCase();return t==="production"||t==="prod"}getDefaultLevel(t){return t?"warn":"debug"}getDefaultColorizeValue(t){return t!==void 0?t:!this.isProductionEnvironment()}getDefaultJson(t){return t}getDefaultTimestamp(t){return!0}getDefaultTransports(t){return t?[{type:"console"},{type:"file",options:{path:"./logs/app.log"}}]:[{type:"console"}]}getDefaultAsyncMode(t){return t}initTransports(t,e){let i=[];for(let r of t)if(r.type==="console"){let o=new v({colorize:r.options?.colorize??e});i.push(o)}else if(r.type==="file"){if(r.options?.path){let o={path:r.options.path};r.options.maxSize!==void 0&&(o.maxSize=r.options.maxSize),r.options.maxFiles!==void 0&&(o.maxFiles=r.options.maxFiles);let a=new b(o);i.push(a)}}else r.type==="custom"&&r.instance&&i.push(r.instance);return i}shouldLog(t){let e=this.getLevelPriority(this.level);return this.getLevelPriority(t)>=e}getLevelPriority(t){if(l.LEVEL_PRIORITIES.hasOwnProperty(t))return l.LEVEL_PRIORITIES[t];if(this.customLevels&&t in this.customLevels){let e=this.customLevels[t];return e!==void 0?e:999}return 999}log(t,e,i){if(this.shouldLog(t)&&t!=="silent")if(this.asyncMode)this.logAsyncDirect(t,e,i);else{let r=new Date,o;this.context&&Object.keys(this.context).length>0?i?o={...this.context,...i}:o=this.context:i&&(o=i);let a={level:t,message:e,timestamp:r,metadata:o&&Object.keys(o).length>0?o:void 0,prefix:this.prefix};for(let p of this.transports)p.write(a,this.formatter)}}logAsyncDirect(t,e,i){if(!this.shouldLog(t)||t==="silent")return;let r=new Date,o;this.context&&Object.keys(this.context).length>0?i?o={...this.context,...i}:o=this.context:i&&(o=i);let a={level:t,message:e,timestamp:r,metadata:o&&Object.keys(o).length>0?o:void 0,prefix:this.prefix};for(let p of this.transports)p.writeAsync?p.writeAsync(a,this.formatter).catch(m=>{console.error("Error during async logging:",m)}):setImmediate(()=>{p.write(a,this.formatter)})}debug(t,e){this.log("debug",t,e)}info(t,e){this.log("info",t,e)}warn(t,e){this.log("warn",t,e)}error(t,e){this.log("error",t,e)}silent(t,e){this.log("silent",t,e)}boring(t,e){this.log("boring",t,e)}logWithLevel(t,e,i){this.log(t,e,i)}setLevel(t){this.level=t}setFormat(t){this.formatter.setJson(t==="json")}setAsyncMode(t){this.asyncMode=t}addTransport(t){this.transports.push(t)}getTimestampSetting(){return this.timestamp}static get global(){return l._global||(l._global=new l),l._global}createChild(t={}){return new l({...t,parent:this})}startTimer(t){let{Timer:e}=(P(),I(O));return new e(t,i=>this.info(i))}};var et=L;export{v as ConsoleTransport,b as FileTransport,L as Logger,et as default};
|