UNPKG

@jvddavid/pino-rotating-file

Version:

A transport for pino that writes logs to rotating files

1 lines 2.3 kB
import t from"close-with-grace";import r from"pino-abstract-transport";import{EventEmitter as e}from"node:events";import{join as n}from"node:path";import{SonicBoom as s}from"sonic-boom";class i extends e{currentFile=0;currentSize=0;currentStream;options;writable=!0;constructor(t){super(),this.options={maxSize:10485760,path:"logs",pattern:"log-%Y-%M-%d-%H-%m-%s-%l-%N.log",sync:!1,fsync:!1,append:!0,mkdir:!0,...t},this.currentStream=this.createStream()}createStream(){const{path:t,pattern:r,maxSize:e,sync:i,fsync:a,mkdir:o,append:c}=this.options,u=new Date,m=n(t,r.replace(/%[a-zA-Z]/g,(t=>{switch(t){case"%Y":return u.getFullYear().toString();case"%M":return(u.getMonth()+1).toString().padStart(2,"0");case"%d":return u.getDate().toString().padStart(2,"0");case"%H":return u.getHours().toString().padStart(2,"0");case"%m":return u.getMinutes().toString().padStart(2,"0");case"%s":return u.getSeconds().toString().padStart(2,"0");case"%l":return u.getMilliseconds().toString().padStart(3,"0");case"%N":return this.currentFile.toString().padStart(3,"0");default:return t}}))),h=new s({dest:m,append:c??!0,mkdir:o??!0,sync:i??!1,contentMode:"utf8",fsync:a,maxWrite:e});return this.currentFile++,h.on("error",(t=>this.emit("error",t))),h}rotateStream(){this.currentStream&&(this.currentStream.removeAllListeners(),this.currentStream.flush((t=>{t&&this.emit("error",t),this.currentStream.end()}))),this.currentStream=this.createStream()}flush(){return new Promise(((t,r)=>{this.currentStream.flush((e=>{e?r(e):t()}))}))}write(t){return!!this.writable&&(this.currentSize+=t.length,this.currentSize>=this.options.maxSize&&(this.rotateStream(),this.currentSize=t.length),this.currentStream.write(`${t}\n`))}close(){return this.writable=!1,new Promise(((t,r)=>{this.currentStream.once("close",t),this.currentStream.once("error",r),this.currentStream.flush((t=>{t?r(t):this.currentStream.end()}))}))}end(){return this.writable=!1,this.currentStream.once("close",(()=>this.emit("close"))),this.currentStream.once("error",(t=>this.emit("error",t))),this.currentStream.flush((t=>{t&&this.emit("error",t),this.currentStream.end()})),this}}var a=e=>{const n=new i(e);return t((()=>{n.end()})),r((t=>{t.pipe(n)}),{close(t,r){n.on("close",r.bind(null,t)),n.end()},parse:"lines",parseLine:t=>t})};export{a as default};