@xrystal/core 3.51.2 → 3.51.3
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/package.json
CHANGED
|
@@ -21,6 +21,7 @@ export default class Logger implements IProvide<any> {
|
|
|
21
21
|
private isKafkaReady;
|
|
22
22
|
private kafkaProducer;
|
|
23
23
|
private kafkaLogsTopic;
|
|
24
|
+
private queueLogLevel;
|
|
24
25
|
winston: ICustomLogger;
|
|
25
26
|
constructor({ system, configs, kafkaForCore, }: {
|
|
26
27
|
system: System;
|
|
@@ -31,9 +32,10 @@ export default class Logger implements IProvide<any> {
|
|
|
31
32
|
onInit: () => Promise<void>;
|
|
32
33
|
syncFromTmp: () => Promise<void>;
|
|
33
34
|
private teardownLogger;
|
|
34
|
-
winstonLoader: ({ loadPath, loggerLevel }: {
|
|
35
|
+
winstonLoader: ({ loadPath, loggerLevel, queueLogLevel, }: {
|
|
35
36
|
loadPath: string;
|
|
36
37
|
loggerLevel: string;
|
|
38
|
+
queueLogLevel: string;
|
|
37
39
|
}) => ICustomLogger;
|
|
38
40
|
private safeReplacer;
|
|
39
41
|
private getTracingFormat;
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
import
|
|
2
|
-
Payload: ${JSON.stringify(e.payload,this.safeReplacer)}`:"",n=e.code?` [Code: ${e.code}]`:"";return`${e.timestamp} [${this.serviceName}] ${e.level}${n}: ${t}${a}${
|
|
1
|
+
import m,{format as i}from"winston";import u from"winston-transport";import"winston-daily-rotate-file";import g from"node:path";import{Partitioners as y}from"kafkajs";import{LoggerLayerEnum as r}from "../../utils/index.js";import{loggerLayerName as k,meetsLoggerLayerThreshold as L,normalizeLoggerLayer as v}from "../../utils/helpers/logger-layer/index.js";import{LogDTO as w}from "../../utils/index.js";import{bindLoaderTmpSync as R}from "../../utils/index.js";import{getRequestId as h}from "../../utils/index.js";class p extends u{service;constructor(e,t){super(e);this.service=t}log(e,t){setImmediate(()=>this.emit("logged",e));this.service.logToKafka(e).finally(()=>t())}}const b={critical:r.CRITICAL,error:r.ERROR,warn:r.WARN,info:r.INFO,http:r.HTTP,debug:r.DEBUG},P={critical:"red",error:"magenta",warn:"yellow",info:"green",http:"cyan",debug:"blue"};export default class Logger{serviceName="";isKafkaReady=!1;kafkaProducer=null;kafkaLogsTopic="";queueLogLevel=r.WARN;winston;#t;#e;#s;constructor({system:e,configs:t,kafkaForCore:a}){this.#t=e;this.#e=t;this.#s=a}onDispose=async()=>{await this.teardownLogger()};onInit=async()=>{await this.syncFromTmp();R(this)};syncFromTmp=async()=>{await this.teardownLogger();this.serviceName=this.#t?.tmp?.configs?.service?.name??"";this.kafkaLogsTopic=this.#e?.all?.kafkaLogsTopic;m.addColors(P);const e=this.#t?.tmp?.configs?.service?.loaders?.loggers,{kafkaBrokers:t,isKafkaPassive:a}=this.#e.all,o=t?String(t).split(",").map((d)=>d.trim()):[];if(a===!1&&o.length>0&&this.#s.instance){this.kafkaProducer=this.#s.instance.producer({createPartitioner:y.DefaultPartitioner,retry:{initialRetryTime:500,retries:5}});try{await this.kafkaProducer?.connect();this.isKafkaReady=!0}catch{this.isKafkaReady=!1}}const l=e?.loadPath||"logs",s=e?.logLevel||e?.loggerLevel||"info",c=v(e?.queueLogLevel??e?.kafkaLogLevel,r.WARN);this.queueLogLevel=c;this.winstonLoader({loadPath:g.join(this.#e.all.rootFolderPath,l),loggerLevel:s,queueLogLevel:k(c)})};teardownLogger=async()=>{if(this.kafkaProducer){try{await this.kafkaProducer.disconnect()}catch{}this.kafkaProducer=null}this.isKafkaReady=!1;if(this.winston){this.winston.clear();this.winston.close()}};winstonLoader=({loadPath:e,loggerLevel:t,queueLogLevel:a})=>{const{combine:o,timestamp:n,json:l,errors:s}=i,c=this.getTracingFormat(),d=o(c,n({format:"YYYY-MM-DD HH:mm:ss"}),s({stack:!0}),l({replacer:this.safeReplacer})),f=[new m.transports.Console({format:this.getConsoleFormat()}),new m.transports.DailyRotateFile({filename:g.resolve(e,"error","%DATE%_error.log"),level:"error",format:d,maxSize:"2mb",maxFiles:"7d"}),new m.transports.DailyRotateFile({filename:g.resolve(e,"critical","%DATE%_critical.log"),level:"critical",format:d,maxSize:"2mb",maxFiles:"14d"})];if(this.isKafkaReady&&this.kafkaProducer)f.push(new p({level:a},this));this.winston=m.createLogger({level:t,levels:b,format:c,transports:f});return this.winston};safeReplacer=(e,t)=>{if(t instanceof Headers)return Object.fromEntries(t.entries());if(t instanceof Error)return{message:t.message,stack:t.stack};return t};getTracingFormat=i((e)=>{if(e.id)return e;const t=h();if(t)e.id=t;return e});getConsoleFormat(){return i.combine(this.getTracingFormat(),i.timestamp({format:"YYYY-MM-DD HH:mm:ss"}),i.colorize({all:!0}),i.printf((e)=>{const t=typeof e.message==="object"?JSON.stringify(e.message,this.safeReplacer):e.message,a=e.id?` : id: ${e.id}`:"",o=e.payload?`
|
|
2
|
+
Payload: ${JSON.stringify(e.payload,this.safeReplacer)}`:"",n=e.code?` [Code: ${e.code}]`:"";return`${e.timestamp} [${this.serviceName}] ${e.level}${n}: ${t}${a}${o}`}))}normalizeLevel(e){return typeof e==="string"?e.toLowerCase():r[e].toLowerCase()}normalizeMessage(e){if(e===void 0||e===null)return;return typeof e==="string"?e:JSON.stringify(e,this.safeReplacer)}buildLogBody(e){return w.schema({level:this.normalizeLevel(e.level),service:this.serviceName,message:this.normalizeMessage(e.message),payload:e.payload,code:e.code,timestamp:e.timestamp??new Date().toISOString(),id:e.id??h()??void 0,env:this.#e.all.env}).build()}async logToKafka(e){if(!this.kafkaProducer||!this.isKafkaReady)return;if(!L(e.level,this.queueLogLevel))return;try{const t=this.buildLogBody({level:e.level,message:e.message,payload:e.payload,code:e.code,id:e.id,timestamp:e.timestamp});await this.kafkaProducer.send({topic:this.kafkaLogsTopic,messages:[{value:JSON.stringify(t,this.safeReplacer)}],acks:1})}catch(t){this.isKafkaReady=!1}}log(e,t,a,o){const l=typeof e==="object"&&e!==null&&"level"in e?e:{level:e,message:t,payload:a,code:o},s=this.buildLogBody(l);this.winston.log(s.level,s.message,{id:s.id,payload:s.payload,code:s.code,service:s.service,timestamp:s.timestamp,env:s.env})}}
|
|
@@ -0,0 +1,5 @@
|
|
|
1
|
+
import { LoggerLayerEnum } from '../../../utils/models/enums';
|
|
2
|
+
export declare function normalizeLoggerLayer(value?: string | null, fallback?: LoggerLayerEnum): LoggerLayerEnum;
|
|
3
|
+
export declare function loggerLayerName(layer: LoggerLayerEnum): string;
|
|
4
|
+
/** Lower enum value = higher severity. Queue when log is at least as severe as minLevel. */
|
|
5
|
+
export declare function meetsLoggerLayerThreshold(level: LoggerLayerEnum | string, minLevel: LoggerLayerEnum): boolean;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
import{LoggerLayerEnum as r}from "../../../utils/models/enums/index.js";const s={critical:r.CRITICAL,error:r.ERROR,warn:r.WARN,warning:r.WARN,info:r.INFO,http:r.HTTP,debug:r.DEBUG};export function normalizeLoggerLayer(e,n=r.WARN){const t=typeof e==="string"?e.trim().toLowerCase():"";if(!t)return n;const i=s[t];if(i!==void 0)return i;const o=Number(t);if(Number.isInteger(o)&&o in r)return o;return n}export function loggerLayerName(e){return r[e].toLowerCase()}export function meetsLoggerLayerThreshold(e,n){return(typeof e==="string"?normalizeLoggerLayer(e,r.DEBUG):e)<=n}
|