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