UNPKG

@incubrain/logger

Version:

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

3 lines (2 loc) 6.89 kB
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},F={log:(t,e)=>{let{args:r=[],date:o,type:n,tag:S}=t,f,v=[...r];typeof t.message=="string"&&t.message.length>0?(f=t.message,r.length>0&&r[0]===f&&(v=r.slice(1))):r.length>0&&typeof r[0]=="string"?(f=r[0],v=r.slice(1)):f="[No message]";let N=r.find(L=>L instanceof Error),U=N?` Error: ${N.message}`:"",m=v.filter(L=>!(L instanceof Error)),V=o instanceof Date?o.toISOString():new Date().toISOString(),T=S?`[${S}] `:"",$=n==="error"||n==="fatal"?"error":n==="warn"?"warn":n==="info"||n==="success"?"info":n==="debug"||n==="trace"?"debug":"log",y="";if(m.length>0)try{y=" "+JSON.stringify(m.length===1?m[0]:m)}catch{y=" [Cannot stringify metadata]"}console[$](`[${V}] [${n.toUpperCase()}] ${T}${f}${U}${y}`)}},a={level:3,reporters:[F],formatOptions:{date:!0,colors:!0,compact:!1}},E={development:"development",production:"production",test:"test"};var u=class extends Error{constructor(r,o){super(r);this.cause=o;this.name="LoggerError"}},x=class extends u{constructor(e,r){super(`Stream Error: ${e}`,r),this.name="StreamError"}},I=class extends u{constructor(r,o,n){super(`Serialization Error: ${r}`,n);this.data=o;this.name="SerializationError"}},c=class extends u{constructor(e,r){super(`Configuration Error: ${e}`,r),this.name="ConfigurationError"}},M=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}),t instanceof x||t instanceof c)throw t};import{createConsola as H}from"consola";var j=process.env.DEBUG==="true"&&!1;function g(...t){j&&console.log("[LOGGER_DEBUG]",...t)}var d=class t{static instance;consola;reporters=[];options;constructor(e={},r){try{this.consola=r||H({level:e.level??a.level,reporters:e.reporters||a.reporters,formatOptions:{...a.formatOptions,...e.formatOptions}}),this.options={...a,...e,context:e.context||{}}}catch(o){throw new c("Failed to initialize logger",o instanceof Error?o:void 0)}}shouldLog(e){let r=s[e],o=this.consola.level;return o===s.SILENT?!1:o===s.VERBOSE?!0:r<=o}static getInstance(e){return g("getInstance called with options:",e),t.instance?g("Returning existing Logger instance"):(g("Creating new Logger instance"),t.instance=new t(e)),t.instance}withContext(e){g(`withContext called with: ${JSON.stringify(e)}`),g("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 g(`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))}prompt(e,r){return this.consola.prompt(e,r)}debug(e,...r){this.shouldLog("DEBUG")&&(typeof e=="string"&&r.length===0?this.consola.debug(e):this.consola.debug(e,...r))}info(e,...r){this.shouldLog("INFO")&&(typeof e=="string"&&r.length===0?this.consola.info(e):this.consola.info(e,...r))}success(e,...r){this.shouldLog("SUCCESS")&&(typeof e=="string"&&r.length===0?this.consola.success(e):this.consola.success(e,...r))}warn(e,...r){this.shouldLog("WARN")&&(typeof e=="string"&&r.length===0?this.consola.warn(e):this.consola.warn(e,...r))}error(e,...r){this.shouldLog("ERROR")&&(typeof e=="string"&&r.length===0?this.consola.error(e):this.consola.error(e,...r))}fatal(e,...r){this.shouldLog("FATAL")&&(typeof e=="string"&&r.length===0?this.consola.fatal(e):this.consola.fatal(e,...r))}trace(e,...r){this.shouldLog("TRACE")&&(typeof e=="string"&&r.length===0?this.consola.trace(e):this.consola.trace(e,...r))}log(e,...r){this.shouldLog("LOG")&&(typeof e=="string"&&r.length===0?this.consola.log(e):this.consola.log(e,...r))}};function B(){return typeof window<"u"&&typeof window.document<"u"?"client":"server"}function b(){return B()==="client"}var R=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",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)})}}},C=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)}))}},O;function G(){return O||(O=b()?new C:new R),O}function D(t){return G().getEnvVar(t)}function w(){return G().getContext()}var P=!1;function i(...t){P&&console.log("[INIT_DEBUG]",...t)}var l=null;function _(t){if(t.level!==void 0&&(t.level<0||t.level>5))throw new c("Log level must be between 0 and 5")}function p(t){try{let e=new WeakSet;return JSON.stringify(t,(r,o)=>{if(typeof o=="object"&&o!==null){if(e.has(o))return"[Circular].js";e.add(o)}return typeof o=="function"?"[Function].js":o},2)}catch(e){return`[Cannot stringify: ${e.message}]`}}function A(t={}){i("initLogger called with options:",p(t)),_(t);let e=w();i("Runtime context:",p(e)),t.serviceName&&(!t.context||!t.context.serviceName)&&(t.context={...t.context||{},serviceName:t.serviceName},i("Added serviceName to context:",p(t.context)));let r={environment:e.environment,runtime:e.runtime,serviceName:"default-service"};i("Default context:",p(r));let o={...a,...t,context:{...r,...t.context},formatOptions:{...a.formatOptions,...t.formatOptions}};if(i("Merged options:",p(o)),t.reporters&&(i("Setting reporters from options:",typeof t.reporters),o.reporters=t.reporters),i("Final reporters count:",o.reporters?.length),i("Creating logger instance"),l=d.getInstance(o),!l)throw new Error("Failed to create logger instance");let n=t.level??z();return i("Setting log level:",n),l.setLevel(n),i("Logger instance created successfully"),l}function h(){return i("getLogger called, loggerInstance exists:",!!l),l||A()}function k(t){return i("createLogger called with context:",p(t)),h().withContext(t)}function z(){let t=D("LOG_LEVEL");if(t&&t in s)return s[t];switch(w().environment){case E.production:return s.INFO;case E.test:return s.ERROR;case E.development:default:return s.DEBUG}}var fe=h();export{c as ConfigurationError,a as DEFAULT_OPTIONS,E as ENV,s as LOG_LEVELS,d as Logger,u as LoggerError,I as SerializationError,x as StreamError,k as createLogger,M as defaultErrorHandler,h as getLogger,A as initLogger,fe as logger}; //# sourceMappingURL=index.js.map