UNPKG

nodejs-gcp-log-correlation

Version:

A Node.js package for automatic log correlation in Google Cloud Platform using trace context

2 lines (1 loc) 1.78 kB
import a from"winston";import{LoggingWinston as L}from"@google-cloud/logging-winston";import{AsyncLocalStorage as x}from"async_hooks";var u=new x,f=(e,o)=>u.run(e,o),m=()=>u.getStore()||{};var c=console,g=!1,y=()=>({info:(e,o)=>(g||p(),c.info(e,o)),warn:(e,o)=>(g||p(),c.warn(e,o)),error:(e,o)=>(g||p(),c.error(e,o)),debug:(e,o)=>(g||p(),c.debug(e,o))}),C=y();function w(e){return e.environment==="development"?{level:e.logLevel,transports:[new a.transports.Console],format:a.format.combine(a.format.timestamp(),a.format.printf(({level:t,message:r,timestamp:n,...s})=>{let l=Object.keys(s).length>0?` ${JSON.stringify(s)}`:"";return`[${n}] ${t.toUpperCase()}: ${r}${l}`}))}:{level:e.logLevel,transports:[new L],format:a.format.json()}}function v(e,o){let t=["info","warn","error","debug"],r={};return t.forEach(n=>{r[n]=(s,l={})=>{let i=m(),d={...l};return i.trace&&(d={"logging.googleapis.com/trace":i.trace.startsWith("projects/")?i.trace:`projects/${o.projectId}/traces/${i.trace}`,...d}),e[n](s,d)}}),r}function p(){if(g&&c!==console)return;let e=process.env.NODE_ENV||"development",o={environment:e,projectId:process.env.GOOGLE_CLOUD_PROJECT||"",logLevel:e==="development"?"debug":"info"};e!=="development"&&!o.projectId&&console.warn("nodejs-gcp-log-correlation: No GCP Project ID detected. Trace correlation may not work properly.");try{let t=w(o),r=a.createLogger(t);c=v(r,o)}catch(t){console.warn("Failed to initialize Winston logger, falling back to console:",t)}g=!0}function W(){return(e,o,t)=>{let r=e.header("x-cloud-trace-context")?.split("/")[0];f(r?{trace:r}:{},()=>{t()})}}function T(e){return(...o)=>{let r=o[0].header("x-cloud-trace-context")?.split("/")[0];return f(r?{trace:r}:{},()=>e(...o))}}export{C as logger,W as loggerMiddleware,T as wrapCloudFunction};