UNPKG

@incubrain/logger

Version:

A modern, type-safe logging library for Node.js and browser environments, built on top of Consola with additional features for enterprise applications.

3 lines (2 loc) 9.89 kB
var V=Object.defineProperty;var D=(r,e,t)=>e in r?V(r,e,{enumerable:!0,configurable:!0,writable:!0,value:t}):r[e]=t;var p=(r,e,t)=>(D(r,typeof e!="symbol"?e+"":e,t),t);var a={SILENT:-999,VERBOSE:999,FATAL:0,ERROR:0,WARN:1,LOG:2,INFO:3,SUCCESS:3,READY:3,START:3,DEBUG:4,TRACE:5},A={log:(r,e)=>{let{args:t=[],date:n,type:o,tag:s}=r,u=t.length>0&&typeof t[0]=="string"?t[0]:"",G=u===t[0]?t.slice(1):t,k=n instanceof Date?n.toISOString():new Date().toISOString(),$=s?`[${s}] `:"";console[o==="error"||o==="fatal"?"error":o==="warn"?"warn":o==="info"||o==="success"?"info":o==="debug"||o==="trace"?"debug":"log"](`[${k}] [${o.toUpperCase()}] ${$}${u}`,...G)}},f={level:3,reporters:[A],formatOptions:{date:!0,colors:!0,compact:!1}},E={development:"development",production:"production",test:"test"};var g=class extends Error{constructor(t,n){super(t);this.cause=n;this.name="LoggerError"}},O=class extends g{constructor(e,t){super(`Stream Error: ${e}`,t),this.name="StreamError"}},h=class extends g{constructor(t,n,o){super(`Serialization Error: ${t}`,o);this.data=n;this.name="SerializationError"}},d=class extends g{constructor(e,t){super(`Configuration Error: ${e}`,t),this.name="ConfigurationError"}},C=r=>{if(console.debug("[DEBUG] defaultErrorHandler received error:",{error:r}),console.error(`[LOGGER ERROR] ${r.name}:`,{message:r.message,cause:r.cause,stack:r.stack}),r instanceof O||r instanceof d)throw r};import{createConsola as T}from"consola";var U=process.env.DEBUG==="true"&&!1;function i(...r){U&&console.log("[LOGGER_DEBUG]",...r)}var l=class l{constructor(e={},t){p(this,"consola");p(this,"reporters",[]);p(this,"errorHandler");p(this,"options");p(this,"defaultLabels");this.errorHandler=t??C;try{i("Logger constructor called with options:",JSON.stringify(e,null,2)),this.options={...f,...e,context:e.context||{},level:e.level??f.level},e.reporters&&(i("Setting reporters from options:",e.reporters),this.reporters=e.reporters),i("Reporters after initialization:",this.reporters);let o={...this.options,level:this.options.level,formatOptions:{...f.formatOptions,...e.formatOptions},reporters:[]};this.reporters=e.reporters||[],this.defaultLabels={service:process.env.WORKER_TYPE||"unknown",version:process.env.WORKER_VERSION||"unknown",environment:"production"},i("Creating consola instance with options:",JSON.stringify(o,null,2)),this.consola=T(o)}catch(o){let s=new d("Failed to initialize logger",o instanceof Error?o:void 0);throw this.errorHandler(s),s}let n=this.error;this.error=(...o)=>{let s=o.findIndex(u=>u instanceof Error&&!(u instanceof g));return s>=0&&(o[s]=new g(o[s].message,o[s])),n.apply(this,o)}}safeClone(e){if(!e||e instanceof Error)return e;try{let t=new WeakSet;return JSON.parse(JSON.stringify(e,(n,o)=>{if(typeof o=="object"&&o!==null){if(t.has(o)){let s=new h("Circular reference detected",e);return this.errorHandler(s),"[Circular]"}t.add(o)}return o}))}catch(t){let n=new h("Failed to serialize object",e,t instanceof Error?t:void 0);return this.errorHandler(n),String(e)}}formatLogEntry(e,t,n=[],o){try{return{date:new Date,type:e,level:a[e]||3,tag:this.options.context?.serviceName||"",message:this.formatMessage(t),args:o?[o,...n.filter(u=>!(u instanceof Error))]:n,context:this.options.context||{},labels:{...this.defaultLabels,level:e,service:this.options.context?.serviceName||this.defaultLabels.service,environment:this.options.context?.environment||this.defaultLabels.environment}}}catch{return{date:new Date,additional:void 0,type:e,level:a[e]||3,tag:"",message:String(t),args:o?[o]:[],context:this.options.context||{}}}}formatMessage(e){return e instanceof Error?e.message:typeof e=="object"&&e!==null?e.message||JSON.stringify(e):String(e)}formatData(e,t){let n={};return t&&(n.error={name:t.name,message:t.message,stack:t.stack,...t.context}),e.length>0&&(n.args=e.map(o=>this.sanitizeValue(o))),n}shouldLog(e){let t=a[e],n=this.consola.level;return n===a.SILENT?!1:n===a.VERBOSE?!0:t<=n}sanitizeContext(e){return this.sanitizeValue(e)}sanitizeValue(e){if(!e)return e;if(e instanceof Error)return{name:e.name,message:e.message,stack:e.stack};try{let t=new WeakSet;return JSON.parse(JSON.stringify(e,(n,o)=>{if(typeof o=="object"&&o!==null){if(t.has(o))return"[Circular]";t.add(o)}return o instanceof Set?Array.from(o):o instanceof Map?Object.fromEntries(o):typeof o=="bigint"?o.toString():o}))}catch{return String(e)}}static getInstance(e){return i("getInstance called with options:",e),l.instance?i("Returning existing Logger instance"):(i("Creating new Logger instance"),l.instance=new l(e)),l.instance}withContext(e){i(`withContext called with: ${JSON.stringify(e)}`),i("Creating new logger with merged context");let t={level:this.options.level,formatOptions:{...this.options.formatOptions},context:{...this.options.context,...e}},n=new l(t);return i(`Setting reporters on new logger: ${JSON.stringify(this.reporters)}`),n.reporters=this.reporters,n}setLevel(e){this.consola.level=e,this.options.level=e}async end(){await Promise.all(this.reporters.map(e=>e.end?.()).filter(Boolean))}callReporters(e){let t={options:this.options};for(let n of this.reporters)typeof n.log=="function"&&n.log(e,t)}prompt(e,t){return this.consola.prompt(e,t)}debug(e,...t){if(!this.shouldLog("DEBUG"))return;let n=this.formatLogEntry("DEBUG",e,t);i(`debug method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.debug(e,...t)}info(e,...t){if(!this.shouldLog("INFO"))return;let n=this.formatLogEntry("INFO",e,t);i(`info method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.info(e,...t)}success(e,...t){if(!this.shouldLog("SUCCESS"))return;let n=this.formatLogEntry("SUCCESS",e,t);i(`success method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.success(e,...t)}warn(e,...t){if(!this.shouldLog("WARN"))return;let n=this.formatLogEntry("WARN",e,t);i(`warn method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.warn(e,...t)}error(e,...t){if(!this.shouldLog("ERROR"))return;let n=this.formatLogEntry("ERROR",e,t);i(`error method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.error(e,...t)}fatal(e,...t){if(!this.shouldLog("FATAL"))return;let n=this.formatLogEntry("FATAL",e,t);i(`fatal method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.fatal(e,...t)}trace(e,...t){if(!this.shouldLog("TRACE"))return;let n=this.formatLogEntry("TRACE",e,t);i(`trace method called with message: ${e}`),i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.trace(e,...t)}log(e,...t){if(!this.shouldLog("LOG"))return;let n=this.formatLogEntry("LOG",e,t);i(`Current reporters: ${this.reporters.length}`),this.callReporters(n),this.consola.log(e,...t)}};p(l,"instance"),p(l,"loggerCache",new Map);var L=l;function H(){return typeof window<"u"&&typeof window.document<"u"?"client":"server"}function S(){return H()==="client"}var x=class{getContext(){return{runtime:"server",isFileSystemAvailable:!0,isProcessAvailable:!0,environment:"production"}}getEnvVar(e){return process.env[e]}setupErrorHandlers(e){if(typeof process<"u"){process.on("uncaughtException",n=>{e.fatal("Uncaught Exception:",n),process.exit(1)}),process.on("unhandledRejection",(n,o)=>{e.error("Unhandled Rejection at:",o,"reason:",n)});let t=["SIGTERM","SIGINT","SIGUSR2"];for(let n of t)process.once(n,async()=>{e.info(`Received ${n}, shutting down...`),await e.end?.(),process.exit(0)})}}},w=class{getContext(){return{runtime:"client",isFileSystemAvailable:!1,isProcessAvailable:!1,environment:process.env?.MODE||"development"}}getEnvVar(e){return process.env?.[e]}setupErrorHandlers(e){typeof window<"u"&&(window.addEventListener("unhandledrejection",t=>{e.error("Unhandled Rejection:",t.reason)}),window.addEventListener("error",t=>{e.fatal("Uncaught Error:",t.error)}))}},v;function b(){return v||(v=S()?new w:new x),v}function N(r){return b().getEnvVar(r)}function R(){return b().getContext()}var F=!0;function c(...r){F&&console.log("[INIT_DEBUG]",...r)}var m=null;function j(r){if(r.level!==void 0&&(r.level<0||r.level>5))throw new d("Log level must be between 0 and 5")}function I(r={}){c("initLogger called with options:",JSON.stringify(r,null,2)),j(r);let e=R();c("Runtime context:",e),r.serviceName&&(!r.context||!r.context.serviceName)&&(r.context={...r.context||{},serviceName:r.serviceName},c("Added serviceName to context:",r.context));let t={environment:e.environment,runtime:e.runtime,serviceName:"default-service"};c("Default context:",t);let n={...f,...r,context:{...t,...r.context},formatOptions:{...f.formatOptions,...r.formatOptions}};if(c("Merged options:",JSON.stringify(n,null,2)),r.reporters&&(c("Setting reporters from options:",r.reporters),n.reporters=r.reporters),c("Final reporters:",n.reporters),c("Creating logger instance"),m=L.getInstance(n),!m)throw new Error("Failed to create logger instance");let o=r.level??B();return c("Setting log level:",o),m.setLevel(o),c("Logger instance created successfully"),m}function y(){return c("getLogger called, loggerInstance exists:",!!m),m||I()}function _(r){return c("createLogger called with context:",JSON.stringify(r,null,2)),y().withContext(r)}function B(){let r=N("LOG_LEVEL");if(r&&r in a)return a[r];switch(R().environment){case E.production:return a.INFO;case E.test:return a.ERROR;case E.development:default:return a.DEBUG}}var le=y();export{d as ConfigurationError,f as DEFAULT_OPTIONS,E as ENV,a as LOG_LEVELS,L as Logger,g as LoggerError,h as SerializationError,O as StreamError,_ as createLogger,C as defaultErrorHandler,y as getLogger,I as initLogger,le as logger}; //# sourceMappingURL=index.js.map