@push.rocks/smartlog 3.1.8 → 3.1.10
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/dist_bundle/bundle.js +76 -0
- package/dist_bundle/bundle.js.map +4 -4
- package/dist_ts/00_commitinfo_data.js +2 -2
- package/package.json +7 -7
- package/readme.md +612 -164
- package/ts/00_commitinfo_data.ts +1 -1
package/dist_bundle/bundle.js
CHANGED
|
@@ -7,6 +7,10 @@ var __hasOwnProp = Object.prototype.hasOwnProperty;
|
|
|
7
7
|
var __commonJS = (cb, mod) => function __require() {
|
|
8
8
|
return mod || (0, cb[__getOwnPropNames(cb)[0]])((mod = { exports: {} }).exports, mod), mod.exports;
|
|
9
9
|
};
|
|
10
|
+
var __export = (target, all) => {
|
|
11
|
+
for (var name in all)
|
|
12
|
+
__defProp(target, name, { get: all[name], enumerable: true });
|
|
13
|
+
};
|
|
10
14
|
var __copyProps = (to, from, except, desc) => {
|
|
11
15
|
if (from && typeof from === "object" || typeof from === "function") {
|
|
12
16
|
for (let key of __getOwnPropNames(from))
|
|
@@ -41,6 +45,78 @@ var require_dist_ts = __commonJS({
|
|
|
41
45
|
}
|
|
42
46
|
});
|
|
43
47
|
|
|
48
|
+
// dist_ts_interfaces/index.js
|
|
49
|
+
var dist_ts_interfaces_exports = {};
|
|
50
|
+
__export(dist_ts_interfaces_exports, {
|
|
51
|
+
request: () => smartlog_interfaces_requests_exports
|
|
52
|
+
});
|
|
53
|
+
|
|
54
|
+
// node_modules/.pnpm/@api.global+typedrequest-interfaces@3.0.19/node_modules/@api.global/typedrequest-interfaces/dist_ts/index.js
|
|
55
|
+
var dist_ts_exports = {};
|
|
56
|
+
|
|
57
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/index.js
|
|
58
|
+
var dist_ts_exports2 = {};
|
|
59
|
+
__export(dist_ts_exports2, {
|
|
60
|
+
business: () => business_exports,
|
|
61
|
+
code: () => code_exports,
|
|
62
|
+
container: () => container_exports,
|
|
63
|
+
content: () => content_exports,
|
|
64
|
+
database: () => database_exports,
|
|
65
|
+
descriptors: () => descriptors_exports,
|
|
66
|
+
finance: () => finance_exports,
|
|
67
|
+
general: () => general_exports,
|
|
68
|
+
network: () => network_exports,
|
|
69
|
+
saas: () => saas_exports,
|
|
70
|
+
storage: () => storage_exports,
|
|
71
|
+
website: () => website_exports
|
|
72
|
+
});
|
|
73
|
+
|
|
74
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/business/index.js
|
|
75
|
+
var business_exports = {};
|
|
76
|
+
|
|
77
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/database/index.js
|
|
78
|
+
var database_exports = {};
|
|
79
|
+
|
|
80
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/finance/index.js
|
|
81
|
+
var finance_exports = {};
|
|
82
|
+
|
|
83
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/code/index.js
|
|
84
|
+
var code_exports = {};
|
|
85
|
+
|
|
86
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/container/index.js
|
|
87
|
+
var container_exports = {};
|
|
88
|
+
|
|
89
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/descriptors/index.js
|
|
90
|
+
var descriptors_exports = {};
|
|
91
|
+
|
|
92
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/content/index.js
|
|
93
|
+
var content_exports = {};
|
|
94
|
+
|
|
95
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/general/index.js
|
|
96
|
+
var general_exports = {};
|
|
97
|
+
|
|
98
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/network/index.js
|
|
99
|
+
var network_exports = {};
|
|
100
|
+
__export(network_exports, {
|
|
101
|
+
ICnameDescriptor: () => ICnameDescriptor
|
|
102
|
+
});
|
|
103
|
+
|
|
104
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/network/cname.js
|
|
105
|
+
var ICnameDescriptor = class {
|
|
106
|
+
};
|
|
107
|
+
|
|
108
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/saas/index.js
|
|
109
|
+
var saas_exports = {};
|
|
110
|
+
|
|
111
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/storage/index.js
|
|
112
|
+
var storage_exports = {};
|
|
113
|
+
|
|
114
|
+
// node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/website/index.js
|
|
115
|
+
var website_exports = {};
|
|
116
|
+
|
|
117
|
+
// dist_ts_interfaces/smartlog-interfaces.requests.js
|
|
118
|
+
var smartlog_interfaces_requests_exports = {};
|
|
119
|
+
|
|
44
120
|
// ts/smartlog.plugins.ts
|
|
45
121
|
var isounique = __toESM(require_dist_ts(), 1);
|
|
46
122
|
|
|
@@ -1,7 +1,7 @@
|
|
|
1
1
|
{
|
|
2
2
|
"version": 3,
|
|
3
|
-
"sources": ["../node_modules/.pnpm/@push.rocks+isounique@1.0.5/node_modules/@push.rocks/isounique/ts/index.ts", "../ts/smartlog.plugins.ts", "../ts/smartlog.classes.consolelog.ts", "../ts/smartlog.classes.logrouter.ts", "../ts/smartlog.classes.smartlog.ts", "../ts/smartlog.classes.loggroup.ts"],
|
|
4
|
-
"sourcesContent": [null, "import * as isounique from '@push.rocks/isounique';\nimport * as smartlogInterfaces from '../dist_ts_interfaces/index.js';\n\nexport { isounique, smartlogInterfaces };\n", "import * as plugins from './smartlog.plugins.js';\n\n/**\n * a console log optimized for smartlog\n */\nexport class ConsoleLog {\n public log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n dataArg?: any,\n correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,\n ) {\n console.log(`__# ${logLevelArg}: ${logMessageArg}`);\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\n\nexport class LogRouter {\n /**\n * all log destinations\n */\n private logDestinations: plugins.smartlogInterfaces.ILogDestination[] = [];\n\n constructor() {}\n\n public addLogDestination(logDestination: plugins.smartlogInterfaces.ILogDestination) {\n this.logDestinations.push(logDestination);\n }\n\n // routes the log according to added logDestinations\n public async routeLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {\n for (const logDestination of this.logDestinations) {\n await logDestination.handleLog(logPackageArg);\n }\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\n\nimport { LogRouter } from './smartlog.classes.logrouter.js';\nimport { LogGroup } from './smartlog.classes.loggroup.js';\n\nexport interface ISmartlogContructorOptions {\n logContext: plugins.smartlogInterfaces.ILogContext;\n minimumLogLevel?: plugins.smartlogInterfaces.TLogLevel;\n}\n\nexport class Smartlog implements plugins.smartlogInterfaces.ILogDestination {\n // STATIC\n public static createForCommitinfo(\n commitinfo: plugins.smartlogInterfaces.ILogContext['commitinfo'],\n ) {\n return new Smartlog({\n logContext: {\n commitinfo,\n },\n });\n }\n\n // INSTANCE\n public logContext: plugins.smartlogInterfaces.ILogContext;\n public minimumLogLevel: plugins.smartlogInterfaces.TLogLevel;\n\n public uniInstanceId: string = plugins.isounique.uni();\n\n private consoleEnabled: boolean;\n\n private logRouter = new LogRouter();\n\n public addLogDestination(logDestinationArg: plugins.smartlogInterfaces.ILogDestination) {\n this.logRouter.addLogDestination(logDestinationArg);\n }\n\n constructor(optionsArg: ISmartlogContructorOptions) {\n this.logContext = optionsArg.logContext;\n this.minimumLogLevel = optionsArg.minimumLogLevel || 'silly';\n }\n\n // ============\n // Logger Setup\n // ============\n\n /**\n * enables console logging\n */\n public enableConsole(optionsArg?: { captureAll: boolean }) {\n if (globalThis.process && optionsArg && optionsArg.captureAll) {\n const process = globalThis.process;\n const originalStdoutWrite = process.stdout.write.bind(process.stdout);\n const originalStderrWrite = process.stderr.write.bind(process.stderr);\n\n process.stdout.write = (...args: any) => {\n const logString: string = args[0];\n if (!logString || typeof logString !== 'string') {\n // continue as planned\n return originalStdoutWrite(...args);\n }\n\n if (!logString.startsWith('LOG')) {\n if (logString.includes('Error:')) {\n this.log('error', logString);\n } else {\n this.log('info', logString);\n }\n return true;\n }\n\n return originalStdoutWrite(...args);\n };\n\n process.stderr.write = (...args: any) => {\n const logString: string = args[0];\n if (!logString || typeof logString !== 'string' || !logString.startsWith('LOG')) {\n this.log('error', logString);\n return true;\n }\n return originalStderrWrite(...args);\n };\n }\n this.consoleEnabled = true;\n }\n\n // =============\n // log functions\n // =============\n /**\n * main log method\n * @param logLevelArg - the log level\n * @param logMessageArg - the log message\n * @param logDataArg - any additional log data\n * @param correlationArg - info about corrleations\n */\n public async log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,\n ) {\n correlationArg = {\n ...{\n id: plugins.isounique.uni(),\n type: 'none',\n instance: this.uniInstanceId,\n },\n ...correlationArg,\n };\n\n if (this.consoleEnabled) {\n this.safeConsoleLog(`${logLevelArg}: ${logMessageArg}`);\n }\n\n const logPackage: plugins.smartlogInterfaces.ILogPackage = {\n timestamp: Date.now(),\n type: 'log',\n context: this.logContext,\n level: logLevelArg,\n correlation: correlationArg,\n message: logMessageArg,\n };\n if (logDataArg) {\n logPackage.data = logDataArg;\n }\n await this.logRouter.routeLog(logPackage);\n }\n\n public increment(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n correlationArg: plugins.smartlogInterfaces.ILogCorrelation = {\n id: plugins.isounique.uni(),\n type: 'none',\n },\n ) {\n if (this.consoleEnabled) {\n this.safeConsoleLog(`INCREMENT: ${logLevelArg}: ${logMessageArg}`);\n }\n this.logRouter.routeLog({\n timestamp: Date.now(),\n type: 'increment',\n context: this.logContext,\n level: logLevelArg,\n message: logMessageArg,\n correlation: correlationArg,\n });\n }\n\n public async handleLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {\n await this.logRouter.routeLog(logPackageArg);\n }\n\n private safeConsoleLog(logLine: string) {\n console.log(\n `LOG => ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} => ${logLine}`,\n );\n }\n\n public createLogGroup(transactionId: string = 'none') {\n return new LogGroup(this, transactionId);\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\nimport { Smartlog } from './smartlog.classes.smartlog.js';\n\nexport class LogGroup {\n public smartlogRef: Smartlog;\n public transactionId: string;\n public groupId = plugins.isounique.uni();\n\n constructor(smartlogInstance: Smartlog, transactionIdArg: string) {\n this.smartlogRef = smartlogInstance;\n this.transactionId = transactionIdArg;\n }\n\n public log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n ) {\n this.smartlogRef.log(logLevelArg, logMessageArg, logDataArg, {\n id: plugins.isounique.uni(),\n type: 'none',\n group: this.groupId,\n instance: this.smartlogRef.uniInstanceId,\n transaction: this.transactionId,\n });\n }\n}\n"],
|
|
5
|
-
"mappings": "
|
|
6
|
-
"names": []
|
|
3
|
+
"sources": ["../node_modules/.pnpm/@push.rocks+isounique@1.0.5/node_modules/@push.rocks/isounique/ts/index.ts", "../ts_interfaces/index.ts", "../node_modules/.pnpm/@api.global+typedrequest-interfaces@3.0.19/node_modules/@api.global/typedrequest-interfaces/dist_ts/index.js", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/business/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/database/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/finance/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/code/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/container/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/descriptors/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/content/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/general/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/network/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/network/cname.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/saas/index.ts", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/dist_ts/storage/index.js", "../node_modules/.pnpm/@tsclass+tsclass@9.2.0/node_modules/@tsclass/tsclass/ts/website/index.ts", "../ts_interfaces/smartlog-interfaces.requests.ts", "../ts/smartlog.plugins.ts", "../ts/smartlog.classes.consolelog.ts", "../ts/smartlog.classes.logrouter.ts", "../ts/smartlog.classes.smartlog.ts", "../ts/smartlog.classes.loggroup.ts"],
|
|
4
|
+
"sourcesContent": ["export const uni = (prefix: string = 'uni') => {\n return `${prefix}_${`xxxxxxxxxxxxxxxxxxxxxxxx`.replace(/[xy]/g, (c) => {\n const r = (Math.random() * 16) | 0;\n const v = c === 'x' ? r : (r & 0x3) | 0x8;\n return v.toString(16);\n })}`;\n};\n", "import * as plugins from './smartlog-interfaces.plugins.js';\n\nimport * as requestInterfaces from './smartlog-interfaces.requests.js';\n\nexport { requestInterfaces as request };\n\n/**\n * the different available log types\n */\nexport type TLogType =\n | 'log'\n | 'increment'\n | 'gauge'\n | 'error'\n | 'success'\n | 'value'\n | 'finance'\n | 'compliance';\n\n/**\n * the available log levels\n */\nexport type TLogLevel =\n | 'silly'\n | 'info'\n | 'debug'\n | 'note'\n | 'ok'\n | 'success'\n | 'warn'\n | 'error'\n | 'lifecycle';\n\n/**\n * the available environments\n */\nexport type TEnvironment = 'local' | 'test' | 'staging' | 'production';\n\n/**\n * the available runtimes\n */\nexport type TRuntime = 'node' | 'chrome' | 'rust' | 'deno' | 'cloudflare_workers';\n\n/**\n * the log context e.g. what app in what version on what server\n */\nexport interface ILogContext {\n commitinfo?: plugins.tsclass.code.ICommitInfo;\n company?: string;\n companyunit?: string;\n containerName?: string;\n environment?: TEnvironment;\n runtime?: TRuntime;\n zone?: string;\n}\n\nexport interface ILogCorrelation {\n /**\n * a unique id for this log\n */\n id: string;\n /**\n * the type of this log\n */\n type: 'none' | 'service' | 'build' | 'infrastructure' | 'cdn';\n /**\n * the instance on which the log is created\n * use it for pinning logs to a certain instance in a cluster\n */\n instance?: string;\n /**\n * a series of logs\n */\n group?: string;\n /**\n * a log that belongs to a transaction. E.g. a Payment or a request traveling through multiple backend instances\n */\n transaction?: string;\n}\n\n/**\n * the main logpackage\n */\nexport interface ILogPackage<T = unknown> {\n /**\n * a unix timestamp in milliseconds\n */\n timestamp: number;\n type: TLogType;\n context: ILogContext;\n level: TLogLevel;\n /**\n * allows grouping of log messages\n */\n correlation: ILogCorrelation;\n /**\n * the message to log\n */\n message: string;\n data?: T;\n}\n\nexport interface ILogPackageDataRequest {\n requestCorrelationId: string;\n url: string;\n pathname: string;\n method: string;\n status: string;\n}\n\nexport interface ILogPackageAuthenticated {\n auth: string;\n logPackage: ILogPackage;\n}\n\nexport interface ILogPackageArrayAuthenticated {\n auth: string;\n logPackages: ILogPackage[];\n}\n\n/**\n * a destination interface for extending smartlog modules\n */\nexport interface ILogDestination {\n handleLog: (logPackage: ILogPackage) => Promise<void>;\n}\n", "export {};\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi90cy9pbmRleC50cyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiIn0=", "// Business\nimport * as business from './business/index.js';\n\n// Code\nimport * as code from './code/index.js';\n\n// Container\nimport * as container from './container/index.js';\n\n// Database\nimport * as database from './database/index.js';\n\n// Descriptors \nimport * as descriptors from './descriptors/index.js';\n\n// Finance\nimport * as finance from './finance/index.js';\n\n// Content\nimport * as content from './content/index.js';\n\n// General\nimport * as general from './general/index.js';\n\n// Network\nimport * as network from './network/index.js';\n\n// SaaS\nimport * as saas from './saas/index.js';\n\n// Storage\nimport * as storage from './storage/index.js';\n\n// Website\nimport * as website from './website/index.js';\n\nexport {\n business,\n container,\n code,\n database,\n descriptors,\n finance,\n content,\n general,\n network,\n saas,\n storage,\n website,\n};\n\nimport type * as typeFest from 'type-fest';\nimport * as typeFestOwn from './typefest.own.js';\n\nexport { type typeFest, type typeFestOwn };\n", "export * from './address.js';\nexport * from './contact.js';\nexport * from './document.js';\nexport * from './job.js';\nexport * from './letter.js';\nexport * from './pdf.js';\nexport * from './project.js';\n", "export * from './mongodescriptor.js';\nexport * from './objectaction.js';\nexport * from './objectstatus.js';\nexport * from './wrappeddata.js';\n", "export * from './checkingaccount.js';\nexport * from './currency.js';\nexport * from './expense.js';\nexport * from './accountingdoc.js';\nexport * from './payment.js';\nexport * from './transaction.js';\n", "export * from './commitinfo.js';\nexport * from './statusobject.js';", "export * from './container.js';\nexport * from './volumemount.js';\n", "export type { IMongoDescriptor } from '../database/index.js';\n\nexport interface ICloudflareDescriptor {\n authToken: string;\n};\n\nexport interface ILetterExpressDescriptor {\n email: string,\n apiToken: string,\n}\n", "export * from './article.js';\nexport * from './author.js';\nexport * from './documentationset.js';\n", "export * from './date.js';\nexport * from './time.js';\n", "export * from './cert.js';\nexport * from './cname.js';\nexport * from './device.js';\nexport * from './dns.js';\nexport * from './dnschallenge.js';\nexport * from './dnsconvenience.js';\nexport * from './domaindelegation.js';\nexport * from './jwt.js';\nexport * from './networknode.js';\nexport * from './request.js';\nexport * from './reverseproxy.js';\nexport * from './ssh.js';\n", "import { type ICert } from './cert.js';\n\nexport class ICnameDescriptor {\n /**\n * the original domain that is being cnamed\n */\n cnamedDomain: string;\n\n /**\n * the cname proxy domain\n * the domain that is used for the cname dns entry\n */\n cnameProxyDomain: string;\n\n /**\n * the internal target url\n */\n targetUrl: string;\n\n /**\n * a description\n */\n description: string;\n\n /**\n * the ssl certificate\n */\n sslCertificate?: ICert;\n}\n", "export * from './subscriptionplan.js';\nexport * from './product.js';\n", "export {};\n//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiaW5kZXguanMiLCJzb3VyY2VSb290IjoiIiwic291cmNlcyI6WyIuLi8uLi90cy9zdG9yYWdlL2luZGV4LnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiIifQ==", "export * from './link.js';\nexport * from './menuitem.js';\nexport * from './linkblock.js';\n", "import { type ILogPackageAuthenticated } from './index.js';\n\nexport interface IRequest_SmartlogDestinationReceiver_Any_PostLogPackages {\n method: 'postLogPackages';\n request: {\n logPackages: ILogPackageAuthenticated[];\n };\n response: {};\n}\n", "import * as isounique from '@push.rocks/isounique';\nimport * as smartlogInterfaces from '../dist_ts_interfaces/index.js';\n\nexport { isounique, smartlogInterfaces };\n", "import * as plugins from './smartlog.plugins.js';\n\n/**\n * a console log optimized for smartlog\n */\nexport class ConsoleLog {\n public log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n dataArg?: any,\n correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,\n ) {\n console.log(`__# ${logLevelArg}: ${logMessageArg}`);\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\n\nexport class LogRouter {\n /**\n * all log destinations\n */\n private logDestinations: plugins.smartlogInterfaces.ILogDestination[] = [];\n\n constructor() {}\n\n public addLogDestination(logDestination: plugins.smartlogInterfaces.ILogDestination) {\n this.logDestinations.push(logDestination);\n }\n\n // routes the log according to added logDestinations\n public async routeLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {\n for (const logDestination of this.logDestinations) {\n await logDestination.handleLog(logPackageArg);\n }\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\n\nimport { LogRouter } from './smartlog.classes.logrouter.js';\nimport { LogGroup } from './smartlog.classes.loggroup.js';\n\nexport interface ISmartlogContructorOptions {\n logContext: plugins.smartlogInterfaces.ILogContext;\n minimumLogLevel?: plugins.smartlogInterfaces.TLogLevel;\n}\n\nexport class Smartlog implements plugins.smartlogInterfaces.ILogDestination {\n // STATIC\n public static createForCommitinfo(\n commitinfo: plugins.smartlogInterfaces.ILogContext['commitinfo'],\n ) {\n return new Smartlog({\n logContext: {\n commitinfo,\n },\n });\n }\n\n // INSTANCE\n public logContext: plugins.smartlogInterfaces.ILogContext;\n public minimumLogLevel: plugins.smartlogInterfaces.TLogLevel;\n\n public uniInstanceId: string = plugins.isounique.uni();\n\n private consoleEnabled: boolean;\n\n private logRouter = new LogRouter();\n\n public addLogDestination(logDestinationArg: plugins.smartlogInterfaces.ILogDestination) {\n this.logRouter.addLogDestination(logDestinationArg);\n }\n\n constructor(optionsArg: ISmartlogContructorOptions) {\n this.logContext = optionsArg.logContext;\n this.minimumLogLevel = optionsArg.minimumLogLevel || 'silly';\n }\n\n // ============\n // Logger Setup\n // ============\n\n /**\n * enables console logging\n */\n public enableConsole(optionsArg?: { captureAll: boolean }) {\n if (globalThis.process && optionsArg && optionsArg.captureAll) {\n const process = globalThis.process;\n const originalStdoutWrite = process.stdout.write.bind(process.stdout);\n const originalStderrWrite = process.stderr.write.bind(process.stderr);\n\n process.stdout.write = (...args: any) => {\n const logString: string = args[0];\n if (!logString || typeof logString !== 'string') {\n // continue as planned\n return originalStdoutWrite(...args);\n }\n\n if (!logString.startsWith('LOG')) {\n if (logString.includes('Error:')) {\n this.log('error', logString);\n } else {\n this.log('info', logString);\n }\n return true;\n }\n\n return originalStdoutWrite(...args);\n };\n\n process.stderr.write = (...args: any) => {\n const logString: string = args[0];\n if (!logString || typeof logString !== 'string' || !logString.startsWith('LOG')) {\n this.log('error', logString);\n return true;\n }\n return originalStderrWrite(...args);\n };\n }\n this.consoleEnabled = true;\n }\n\n // =============\n // log functions\n // =============\n /**\n * main log method\n * @param logLevelArg - the log level\n * @param logMessageArg - the log message\n * @param logDataArg - any additional log data\n * @param correlationArg - info about corrleations\n */\n public async log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n correlationArg?: plugins.smartlogInterfaces.ILogCorrelation,\n ) {\n correlationArg = {\n ...{\n id: plugins.isounique.uni(),\n type: 'none',\n instance: this.uniInstanceId,\n },\n ...correlationArg,\n };\n\n if (this.consoleEnabled) {\n this.safeConsoleLog(`${logLevelArg}: ${logMessageArg}`);\n }\n\n const logPackage: plugins.smartlogInterfaces.ILogPackage = {\n timestamp: Date.now(),\n type: 'log',\n context: this.logContext,\n level: logLevelArg,\n correlation: correlationArg,\n message: logMessageArg,\n };\n if (logDataArg) {\n logPackage.data = logDataArg;\n }\n await this.logRouter.routeLog(logPackage);\n }\n\n public increment(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n correlationArg: plugins.smartlogInterfaces.ILogCorrelation = {\n id: plugins.isounique.uni(),\n type: 'none',\n },\n ) {\n if (this.consoleEnabled) {\n this.safeConsoleLog(`INCREMENT: ${logLevelArg}: ${logMessageArg}`);\n }\n this.logRouter.routeLog({\n timestamp: Date.now(),\n type: 'increment',\n context: this.logContext,\n level: logLevelArg,\n message: logMessageArg,\n correlation: correlationArg,\n });\n }\n\n public async handleLog(logPackageArg: plugins.smartlogInterfaces.ILogPackage) {\n await this.logRouter.routeLog(logPackageArg);\n }\n\n private safeConsoleLog(logLine: string) {\n console.log(\n `LOG => ${new Date().getHours()}:${new Date().getMinutes()}:${new Date().getSeconds()} => ${logLine}`,\n );\n }\n\n public createLogGroup(transactionId: string = 'none') {\n return new LogGroup(this, transactionId);\n }\n}\n", "import * as plugins from './smartlog.plugins.js';\nimport { Smartlog } from './smartlog.classes.smartlog.js';\n\nexport class LogGroup {\n public smartlogRef: Smartlog;\n public transactionId: string;\n public groupId = plugins.isounique.uni();\n\n constructor(smartlogInstance: Smartlog, transactionIdArg: string) {\n this.smartlogRef = smartlogInstance;\n this.transactionId = transactionIdArg;\n }\n\n public log(\n logLevelArg: plugins.smartlogInterfaces.TLogLevel,\n logMessageArg: string,\n logDataArg?: any,\n ) {\n this.smartlogRef.log(logLevelArg, logMessageArg, logDataArg, {\n id: plugins.isounique.uni(),\n type: 'none',\n group: this.groupId,\n instance: this.smartlogRef.uniInstanceId,\n transaction: this.transactionId,\n });\n }\n}\n"],
|
|
5
|
+
"mappings": "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",
|
|
6
|
+
"names": ["dist_ts_exports"]
|
|
7
7
|
}
|
|
@@ -3,7 +3,7 @@
|
|
|
3
3
|
*/
|
|
4
4
|
export const commitinfo = {
|
|
5
5
|
name: '@push.rocks/smartlog',
|
|
6
|
-
version: '3.1.
|
|
6
|
+
version: '3.1.10',
|
|
7
7
|
description: 'A minimalistic, distributed, and extensible logging tool supporting centralized log management.'
|
|
8
8
|
};
|
|
9
|
-
//# sourceMappingURL=data:application/json;base64,
|
|
9
|
+
//# sourceMappingURL=data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiMDBfY29tbWl0aW5mb19kYXRhLmpzIiwic291cmNlUm9vdCI6IiIsInNvdXJjZXMiOlsiLi4vdHMvMDBfY29tbWl0aW5mb19kYXRhLnRzIl0sIm5hbWVzIjpbXSwibWFwcGluZ3MiOiJBQUFBOztHQUVHO0FBQ0gsTUFBTSxDQUFDLE1BQU0sVUFBVSxHQUFHO0lBQ3hCLElBQUksRUFBRSxzQkFBc0I7SUFDNUIsT0FBTyxFQUFFLFFBQVE7SUFDakIsV0FBVyxFQUFFLGlHQUFpRztDQUMvRyxDQUFBIn0=
|
package/package.json
CHANGED
|
@@ -1,6 +1,6 @@
|
|
|
1
1
|
{
|
|
2
2
|
"name": "@push.rocks/smartlog",
|
|
3
|
-
"version": "3.1.
|
|
3
|
+
"version": "3.1.10",
|
|
4
4
|
"private": false,
|
|
5
5
|
"description": "A minimalistic, distributed, and extensible logging tool supporting centralized log management.",
|
|
6
6
|
"keywords": [
|
|
@@ -36,19 +36,19 @@
|
|
|
36
36
|
"author": "Lossless GmbH",
|
|
37
37
|
"license": "MIT",
|
|
38
38
|
"devDependencies": {
|
|
39
|
-
"@git.zone/tsbuild": "^2.
|
|
40
|
-
"@git.zone/tsbundle": "^2.
|
|
39
|
+
"@git.zone/tsbuild": "^2.6.8",
|
|
40
|
+
"@git.zone/tsbundle": "^2.5.1",
|
|
41
41
|
"@git.zone/tsrun": "^1.3.3",
|
|
42
|
-
"@git.zone/tstest": "^
|
|
42
|
+
"@git.zone/tstest": "^2.3.6",
|
|
43
43
|
"@types/node": "^22.15.20"
|
|
44
44
|
},
|
|
45
45
|
"dependencies": {
|
|
46
46
|
"@api.global/typedrequest-interfaces": "^3.0.19",
|
|
47
|
-
"@push.rocks/consolecolor": "^2.0.
|
|
47
|
+
"@push.rocks/consolecolor": "^2.0.3",
|
|
48
48
|
"@push.rocks/isounique": "^1.0.4",
|
|
49
49
|
"@push.rocks/smartclickhouse": "^2.0.17",
|
|
50
|
-
"@push.rocks/smartfile": "^11.2.
|
|
51
|
-
"@push.rocks/smarthash": "^3.
|
|
50
|
+
"@push.rocks/smartfile": "^11.2.7",
|
|
51
|
+
"@push.rocks/smarthash": "^3.2.3",
|
|
52
52
|
"@push.rocks/smartpromise": "^4.2.3",
|
|
53
53
|
"@push.rocks/smarttime": "^4.1.1",
|
|
54
54
|
"@push.rocks/webrequest": "^3.0.37",
|
package/readme.md
CHANGED
|
@@ -1,288 +1,736 @@
|
|
|
1
|
-
# @push.rocks/smartlog
|
|
1
|
+
# @push.rocks/smartlog 🚀
|
|
2
|
+
*The ultimate TypeScript logging solution for modern applications*
|
|
2
3
|
|
|
3
|
-
|
|
4
|
+
[](https://www.npmjs.com/package/@push.rocks/smartlog)
|
|
5
|
+
[](https://opensource.org/licenses/MIT)
|
|
4
6
|
|
|
5
|
-
|
|
7
|
+
> **smartlog** is a powerful, distributed, and extensible logging system designed for the cloud-native era. Whether you're debugging locally, monitoring production systems, or building complex microservices, smartlog adapts to your needs with style. 🎯
|
|
6
8
|
|
|
7
|
-
|
|
9
|
+
## 🌟 Why smartlog?
|
|
8
10
|
|
|
9
|
-
|
|
11
|
+
- **🎨 Beautiful Console Output**: Color-coded, formatted logs that are actually readable
|
|
12
|
+
- **🔌 Extensible Architecture**: Plug in any destination - databases, files, remote servers
|
|
13
|
+
- **🌍 Distributed by Design**: Built for microservices with correlation and context tracking
|
|
14
|
+
- **⚡ Zero-Config Start**: Works out of the box, scales when you need it
|
|
15
|
+
- **🎭 Interactive CLI Tools**: Spinners and progress bars that handle non-TTY environments gracefully
|
|
16
|
+
- **📊 Structured Logging**: JSON-based for easy parsing and analysis
|
|
17
|
+
- **🔍 Smart Filtering**: Log levels and context-based filtering
|
|
18
|
+
|
|
19
|
+
## 📦 Installation
|
|
20
|
+
|
|
21
|
+
```bash
|
|
10
22
|
# Using pnpm (recommended)
|
|
11
23
|
pnpm add @push.rocks/smartlog
|
|
12
24
|
|
|
13
25
|
# Using npm
|
|
14
|
-
npm install @push.rocks/smartlog
|
|
26
|
+
npm install @push.rocks/smartlog
|
|
15
27
|
|
|
16
28
|
# Using yarn
|
|
17
29
|
yarn add @push.rocks/smartlog
|
|
18
30
|
```
|
|
19
31
|
|
|
20
|
-
|
|
32
|
+
## 🚀 Quick Start
|
|
21
33
|
|
|
22
|
-
|
|
34
|
+
### Your First Logger
|
|
23
35
|
|
|
24
|
-
|
|
36
|
+
```typescript
|
|
37
|
+
import { Smartlog } from '@push.rocks/smartlog';
|
|
25
38
|
|
|
26
|
-
|
|
27
|
-
|
|
28
|
-
|
|
39
|
+
// Create a logger with context
|
|
40
|
+
const logger = new Smartlog({
|
|
41
|
+
logContext: {
|
|
42
|
+
company: 'MyStartup',
|
|
43
|
+
companyunit: 'Backend Team',
|
|
44
|
+
containerName: 'api-gateway',
|
|
45
|
+
environment: 'production',
|
|
46
|
+
runtime: 'node',
|
|
47
|
+
zone: 'eu-central'
|
|
48
|
+
}
|
|
49
|
+
});
|
|
29
50
|
|
|
30
|
-
//
|
|
31
|
-
|
|
51
|
+
// Enable beautiful console output
|
|
52
|
+
logger.enableConsole();
|
|
32
53
|
|
|
33
|
-
//
|
|
34
|
-
|
|
54
|
+
// Start logging!
|
|
55
|
+
logger.log('info', '🎉 Application started successfully');
|
|
56
|
+
logger.log('error', '💥 Database connection failed', {
|
|
57
|
+
errorCode: 'DB_TIMEOUT',
|
|
58
|
+
attemptCount: 3
|
|
59
|
+
});
|
|
60
|
+
```
|
|
35
61
|
|
|
36
|
-
|
|
37
|
-
import { ... } from '@push.rocks/smartlog/context';
|
|
62
|
+
### Using the Default Logger
|
|
38
63
|
|
|
39
|
-
|
|
40
|
-
|
|
41
|
-
|
|
42
|
-
import {
|
|
43
|
-
|
|
44
|
-
|
|
64
|
+
For quick prototyping and simple applications:
|
|
65
|
+
|
|
66
|
+
```typescript
|
|
67
|
+
import { defaultLogger } from '@push.rocks/smartlog';
|
|
68
|
+
|
|
69
|
+
defaultLogger.log('info', 'This is so easy!');
|
|
70
|
+
```
|
|
71
|
+
|
|
72
|
+
## 📚 Core Concepts
|
|
73
|
+
|
|
74
|
+
### Log Levels
|
|
75
|
+
|
|
76
|
+
smartlog supports semantic log levels for different scenarios:
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
// Lifecycle events
|
|
80
|
+
logger.log('lifecycle', '🔄 Container starting up...');
|
|
45
81
|
|
|
46
|
-
//
|
|
47
|
-
|
|
82
|
+
// Success states
|
|
83
|
+
logger.log('success', '✅ Payment processed');
|
|
84
|
+
logger.log('ok', '👍 Health check passed');
|
|
85
|
+
|
|
86
|
+
// Information and debugging
|
|
87
|
+
logger.log('info', '📋 User profile updated');
|
|
88
|
+
logger.log('note', '📌 Cache invalidated');
|
|
89
|
+
logger.log('debug', '🔍 Query execution plan', { sql: 'SELECT * FROM users' });
|
|
90
|
+
|
|
91
|
+
// Warnings and errors
|
|
92
|
+
logger.log('warn', '⚠️ Memory usage above 80%');
|
|
93
|
+
logger.log('error', '❌ Failed to send email');
|
|
94
|
+
|
|
95
|
+
// Verbose output
|
|
96
|
+
logger.log('silly', '🔬 Entering function processPayment()');
|
|
97
|
+
```
|
|
98
|
+
|
|
99
|
+
### Log Groups for Correlation
|
|
100
|
+
|
|
101
|
+
Perfect for tracking request flows through your system:
|
|
102
|
+
|
|
103
|
+
```typescript
|
|
104
|
+
// Track a user request through multiple operations
|
|
105
|
+
const requestGroup = logger.createLogGroup('req-7f3a2b');
|
|
106
|
+
|
|
107
|
+
requestGroup.log('info', 'Received POST /api/users');
|
|
108
|
+
requestGroup.log('debug', 'Validating request body');
|
|
109
|
+
requestGroup.log('info', 'Creating user in database');
|
|
110
|
+
requestGroup.log('success', 'User created successfully', { userId: 'usr_123' });
|
|
111
|
+
|
|
112
|
+
// All logs in the group share the same correlation ID
|
|
48
113
|
```
|
|
49
114
|
|
|
50
|
-
##
|
|
115
|
+
## 🎯 Log Destinations
|
|
51
116
|
|
|
52
|
-
|
|
117
|
+
### Built-in Destinations
|
|
53
118
|
|
|
54
|
-
|
|
119
|
+
#### 🖥️ Local Console (Enhanced)
|
|
55
120
|
|
|
56
|
-
|
|
121
|
+
Beautiful, colored output for local development:
|
|
57
122
|
|
|
58
123
|
```typescript
|
|
59
|
-
import {
|
|
124
|
+
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
|
|
60
125
|
|
|
61
|
-
const
|
|
62
|
-
|
|
63
|
-
company: 'My Company',
|
|
64
|
-
companyunit: 'Cloud Team',
|
|
65
|
-
containerName: 'api-service',
|
|
66
|
-
environment: 'production', // 'local', 'test', 'staging', 'production'
|
|
67
|
-
runtime: 'node', // 'node', 'chrome', 'rust', 'deno', 'cloudflare_workers'
|
|
68
|
-
zone: 'us-west',
|
|
69
|
-
},
|
|
70
|
-
minimumLogLevel: 'info', // Optional, defaults to 'silly'
|
|
126
|
+
const localDestination = new DestinationLocal({
|
|
127
|
+
logLevel: 'debug' // Optional: filter by minimum log level
|
|
71
128
|
});
|
|
72
129
|
|
|
73
|
-
|
|
74
|
-
logger.enableConsole();
|
|
130
|
+
logger.addLogDestination(localDestination);
|
|
75
131
|
```
|
|
76
132
|
|
|
77
|
-
|
|
133
|
+
#### 📁 File Logging
|
|
78
134
|
|
|
79
|
-
|
|
135
|
+
Persist logs to files with automatic rotation support:
|
|
80
136
|
|
|
81
137
|
```typescript
|
|
82
|
-
|
|
83
|
-
logger.log('info', 'User authenticated successfully');
|
|
84
|
-
logger.log('error', 'Database connection failed', { errorCode: 'DB_CONN_ERR', retryCount: 3 });
|
|
85
|
-
logger.log('warn', 'Rate limit approaching', { currentRate: 95, limit: 100 });
|
|
138
|
+
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
|
|
86
139
|
|
|
87
|
-
|
|
140
|
+
const fileDestination = new SmartlogDestinationFile('./logs/app.log');
|
|
141
|
+
logger.addLogDestination(fileDestination);
|
|
88
142
|
```
|
|
89
143
|
|
|
90
|
-
|
|
144
|
+
#### 🌐 Browser DevTools
|
|
91
145
|
|
|
92
|
-
|
|
146
|
+
Optimized for browser environments with styled console output:
|
|
93
147
|
|
|
94
|
-
|
|
148
|
+
```typescript
|
|
149
|
+
import { SmartlogDestinationDevtools } from '@push.rocks/smartlog/destination-devtools';
|
|
150
|
+
|
|
151
|
+
const devtools = new SmartlogDestinationDevtools();
|
|
152
|
+
logger.addLogDestination(devtools);
|
|
153
|
+
```
|
|
154
|
+
|
|
155
|
+
#### 📊 ClickHouse Analytics
|
|
156
|
+
|
|
157
|
+
Store logs in ClickHouse for powerful analytics:
|
|
95
158
|
|
|
96
159
|
```typescript
|
|
97
|
-
import {
|
|
160
|
+
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
|
|
161
|
+
|
|
162
|
+
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
|
|
163
|
+
host: 'analytics.example.com',
|
|
164
|
+
port: 8123,
|
|
165
|
+
database: 'logs',
|
|
166
|
+
user: 'logger',
|
|
167
|
+
password: process.env.CLICKHOUSE_PASSWORD
|
|
168
|
+
});
|
|
98
169
|
|
|
99
|
-
|
|
170
|
+
logger.addLogDestination(clickhouse);
|
|
171
|
+
|
|
172
|
+
// Query your logs with SQL!
|
|
173
|
+
// SELECT * FROM logs WHERE level = 'error' AND timestamp > now() - INTERVAL 1 HOUR
|
|
100
174
|
```
|
|
101
175
|
|
|
102
|
-
|
|
176
|
+
#### 🔗 Remote Receiver
|
|
103
177
|
|
|
104
|
-
|
|
178
|
+
Send logs to a centralized logging service:
|
|
105
179
|
|
|
106
180
|
```typescript
|
|
107
|
-
|
|
108
|
-
|
|
181
|
+
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
|
|
182
|
+
|
|
183
|
+
const receiver = new SmartlogDestinationReceiver({
|
|
184
|
+
endpoint: 'https://logs.mycompany.com/ingest',
|
|
185
|
+
apiKey: process.env.LOG_API_KEY,
|
|
186
|
+
batchSize: 100, // Send logs in batches
|
|
187
|
+
flushInterval: 5000 // Flush every 5 seconds
|
|
188
|
+
});
|
|
109
189
|
|
|
110
|
-
|
|
111
|
-
requestGroup.log('info', 'Processing payment request');
|
|
112
|
-
requestGroup.log('debug', 'Validating payment details');
|
|
113
|
-
requestGroup.log('success', 'Payment processed successfully');
|
|
190
|
+
logger.addLogDestination(receiver);
|
|
114
191
|
```
|
|
115
192
|
|
|
116
|
-
### Custom
|
|
193
|
+
### 🛠️ Custom Destinations
|
|
117
194
|
|
|
118
|
-
|
|
195
|
+
Build your own destination for any logging backend:
|
|
119
196
|
|
|
120
197
|
```typescript
|
|
121
|
-
import {
|
|
198
|
+
import { ILogDestination, ILogPackage } from '@push.rocks/smartlog/interfaces';
|
|
122
199
|
|
|
123
|
-
class
|
|
124
|
-
|
|
125
|
-
|
|
126
|
-
|
|
127
|
-
|
|
128
|
-
|
|
129
|
-
|
|
130
|
-
|
|
131
|
-
|
|
200
|
+
class ElasticsearchDestination implements ILogDestination {
|
|
201
|
+
private client: ElasticsearchClient;
|
|
202
|
+
|
|
203
|
+
constructor(config: ElasticsearchConfig) {
|
|
204
|
+
this.client = new ElasticsearchClient(config);
|
|
205
|
+
}
|
|
206
|
+
|
|
207
|
+
async handleLog(logPackage: ILogPackage): Promise<void> {
|
|
208
|
+
await this.client.index({
|
|
209
|
+
index: `logs-${new Date().toISOString().split('T')[0]}`,
|
|
210
|
+
body: {
|
|
211
|
+
'@timestamp': logPackage.timestamp,
|
|
212
|
+
level: logPackage.level,
|
|
213
|
+
message: logPackage.message,
|
|
214
|
+
context: logPackage.context,
|
|
215
|
+
data: logPackage.data,
|
|
216
|
+
correlation: logPackage.correlation
|
|
217
|
+
}
|
|
132
218
|
});
|
|
133
219
|
}
|
|
134
220
|
}
|
|
135
221
|
|
|
136
|
-
//
|
|
137
|
-
logger.addLogDestination(new
|
|
222
|
+
// Use your custom destination
|
|
223
|
+
logger.addLogDestination(new ElasticsearchDestination({
|
|
224
|
+
node: 'https://elasticsearch.example.com'
|
|
225
|
+
}));
|
|
138
226
|
```
|
|
139
227
|
|
|
140
|
-
|
|
228
|
+
## 🎨 Interactive Console Features
|
|
141
229
|
|
|
142
|
-
|
|
230
|
+
### Spinners
|
|
231
|
+
|
|
232
|
+
Create beautiful loading animations that degrade gracefully in CI/CD:
|
|
143
233
|
|
|
144
234
|
```typescript
|
|
145
|
-
|
|
146
|
-
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
|
|
147
|
-
logger.addLogDestination(new SmartlogDestinationFile('/path/to/logfile.log'));
|
|
235
|
+
import { SmartlogSourceInteractive } from '@push.rocks/smartlog/source-interactive';
|
|
148
236
|
|
|
149
|
-
|
|
150
|
-
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
|
|
151
|
-
logger.addLogDestination(new DestinationLocal());
|
|
237
|
+
const spinner = new SmartlogSourceInteractive();
|
|
152
238
|
|
|
153
|
-
//
|
|
154
|
-
|
|
155
|
-
|
|
239
|
+
// Basic usage
|
|
240
|
+
spinner.text('🔄 Fetching data from API...');
|
|
241
|
+
// ... perform async operation
|
|
242
|
+
spinner.finishSuccess('✅ Data fetched successfully!');
|
|
243
|
+
|
|
244
|
+
// Chained operations
|
|
245
|
+
spinner
|
|
246
|
+
.text('📡 Connecting to database')
|
|
247
|
+
.successAndNext('🔍 Running migrations')
|
|
248
|
+
.successAndNext('🌱 Seeding data')
|
|
249
|
+
.finishSuccess('🎉 Database ready!');
|
|
250
|
+
|
|
251
|
+
// Customize appearance
|
|
252
|
+
spinner
|
|
253
|
+
.setSpinnerStyle('dots') // dots, line, star, simple
|
|
254
|
+
.setColor('cyan') // any terminal color
|
|
255
|
+
.setSpeed(80) // animation speed in ms
|
|
256
|
+
.text('🚀 Deploying application...');
|
|
257
|
+
|
|
258
|
+
// Handle failures
|
|
259
|
+
try {
|
|
260
|
+
await deployApp();
|
|
261
|
+
spinner.finishSuccess('✅ Deployed!');
|
|
262
|
+
} catch (error) {
|
|
263
|
+
spinner.finishFail('❌ Deployment failed');
|
|
264
|
+
}
|
|
265
|
+
```
|
|
266
|
+
|
|
267
|
+
### Progress Bars
|
|
268
|
+
|
|
269
|
+
Track long-running operations with style:
|
|
270
|
+
|
|
271
|
+
```typescript
|
|
272
|
+
import { SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
|
|
273
|
+
|
|
274
|
+
// Create a progress bar
|
|
275
|
+
const progress = new SmartlogProgressBar({
|
|
276
|
+
total: 100,
|
|
277
|
+
width: 40,
|
|
278
|
+
complete: '█',
|
|
279
|
+
incomplete: '░',
|
|
280
|
+
showEta: true,
|
|
281
|
+
showPercent: true,
|
|
282
|
+
showCount: true
|
|
283
|
+
});
|
|
284
|
+
|
|
285
|
+
// Update progress
|
|
286
|
+
for (let i = 0; i <= 100; i++) {
|
|
287
|
+
progress.update(i);
|
|
288
|
+
await someAsyncWork();
|
|
289
|
+
}
|
|
290
|
+
|
|
291
|
+
progress.complete();
|
|
292
|
+
|
|
293
|
+
// Real-world example: Processing files
|
|
294
|
+
const files = await getFiles();
|
|
295
|
+
const progress = new SmartlogProgressBar({
|
|
296
|
+
total: files.length,
|
|
297
|
+
width: 50
|
|
298
|
+
});
|
|
299
|
+
|
|
300
|
+
for (const [index, file] of files.entries()) {
|
|
301
|
+
await processFile(file);
|
|
302
|
+
progress.increment(); // or progress.update(index + 1)
|
|
303
|
+
}
|
|
304
|
+
```
|
|
305
|
+
|
|
306
|
+
### Non-Interactive Fallback
|
|
307
|
+
|
|
308
|
+
Both spinners and progress bars automatically detect non-interactive environments (CI/CD, Docker logs, piped output) and fallback to simple text output:
|
|
309
|
+
|
|
310
|
+
```
|
|
311
|
+
[Loading] Connecting to database
|
|
312
|
+
[Success] Connected to database
|
|
313
|
+
[Loading] Running migrations
|
|
314
|
+
Progress: 25% (25/100)
|
|
315
|
+
Progress: 50% (50/100)
|
|
316
|
+
Progress: 100% (100/100)
|
|
317
|
+
[Success] Migrations complete
|
|
318
|
+
```
|
|
319
|
+
|
|
320
|
+
## 🔧 Advanced Features
|
|
321
|
+
|
|
322
|
+
### Context Management
|
|
323
|
+
|
|
324
|
+
Add context that flows through your entire application:
|
|
325
|
+
|
|
326
|
+
```typescript
|
|
327
|
+
// Set global context
|
|
328
|
+
logger.addLogContext({
|
|
329
|
+
requestId: 'req-123',
|
|
330
|
+
userId: 'user-456',
|
|
331
|
+
feature: 'payment-processing'
|
|
332
|
+
});
|
|
333
|
+
|
|
334
|
+
// All subsequent logs include this context
|
|
335
|
+
logger.log('info', 'Processing payment');
|
|
336
|
+
// Output includes: { ...context, message: 'Processing payment' }
|
|
337
|
+
```
|
|
156
338
|
|
|
157
|
-
|
|
339
|
+
### Scoped Logging
|
|
340
|
+
|
|
341
|
+
Create scoped loggers for different components:
|
|
342
|
+
|
|
343
|
+
```typescript
|
|
344
|
+
const dbLogger = logger.createScope('database');
|
|
345
|
+
const apiLogger = logger.createScope('api');
|
|
346
|
+
|
|
347
|
+
dbLogger.log('info', 'Executing query');
|
|
348
|
+
apiLogger.log('info', 'Handling request');
|
|
349
|
+
// Logs include scope information for filtering
|
|
350
|
+
```
|
|
351
|
+
|
|
352
|
+
### Minimum Log Levels
|
|
353
|
+
|
|
354
|
+
Control log verbosity per environment:
|
|
355
|
+
|
|
356
|
+
```typescript
|
|
357
|
+
const logger = new Smartlog({
|
|
358
|
+
logContext: { environment: 'production' },
|
|
359
|
+
minimumLogLevel: 'warn' // Only warn and above in production
|
|
360
|
+
});
|
|
361
|
+
|
|
362
|
+
// These won't be logged in production
|
|
363
|
+
logger.log('debug', 'Detailed debug info');
|
|
364
|
+
logger.log('info', 'Regular info');
|
|
365
|
+
|
|
366
|
+
// These will be logged
|
|
367
|
+
logger.log('warn', 'Warning message');
|
|
368
|
+
logger.log('error', 'Error message');
|
|
369
|
+
```
|
|
370
|
+
|
|
371
|
+
### Increment Logging
|
|
372
|
+
|
|
373
|
+
Perfect for metrics and counters:
|
|
374
|
+
|
|
375
|
+
```typescript
|
|
376
|
+
// Track API calls
|
|
377
|
+
logger.increment('info', 'api.requests', { endpoint: '/users', method: 'GET' });
|
|
378
|
+
logger.increment('info', 'api.requests', { endpoint: '/users', method: 'POST' });
|
|
379
|
+
|
|
380
|
+
// Track errors by type
|
|
381
|
+
logger.increment('error', 'payment.failed', { reason: 'insufficient_funds' });
|
|
382
|
+
logger.increment('error', 'payment.failed', { reason: 'card_declined' });
|
|
383
|
+
```
|
|
384
|
+
|
|
385
|
+
### Capture All Console Output
|
|
386
|
+
|
|
387
|
+
Redirect all console.log and console.error through smartlog:
|
|
388
|
+
|
|
389
|
+
```typescript
|
|
390
|
+
logger.enableConsole({
|
|
391
|
+
captureAll: true // Capture all console.* methods
|
|
392
|
+
});
|
|
393
|
+
|
|
394
|
+
console.log('This goes through smartlog!');
|
|
395
|
+
console.error('This too!');
|
|
396
|
+
// All console output is now structured and routed through your destinations
|
|
397
|
+
```
|
|
398
|
+
|
|
399
|
+
## 🏗️ Real-World Examples
|
|
400
|
+
|
|
401
|
+
### Microservice with Distributed Tracing
|
|
402
|
+
|
|
403
|
+
```typescript
|
|
404
|
+
import { Smartlog } from '@push.rocks/smartlog';
|
|
158
405
|
import { SmartlogDestinationClickhouse } from '@push.rocks/smartlog/destination-clickhouse';
|
|
406
|
+
|
|
407
|
+
// Initialize logger with service context
|
|
408
|
+
const logger = new Smartlog({
|
|
409
|
+
logContext: {
|
|
410
|
+
company: 'TechCorp',
|
|
411
|
+
companyunit: 'Platform',
|
|
412
|
+
containerName: 'user-service',
|
|
413
|
+
environment: process.env.NODE_ENV,
|
|
414
|
+
runtime: 'node',
|
|
415
|
+
zone: process.env.CLOUD_ZONE
|
|
416
|
+
}
|
|
417
|
+
});
|
|
418
|
+
|
|
419
|
+
// Add ClickHouse for analytics
|
|
159
420
|
const clickhouse = await SmartlogDestinationClickhouse.createAndStart({
|
|
160
|
-
host:
|
|
161
|
-
|
|
162
|
-
user: 'username',
|
|
163
|
-
password: 'password',
|
|
164
|
-
database: 'logs_db'
|
|
421
|
+
host: process.env.CLICKHOUSE_HOST,
|
|
422
|
+
database: 'microservices_logs'
|
|
165
423
|
});
|
|
166
424
|
logger.addLogDestination(clickhouse);
|
|
167
425
|
|
|
168
|
-
//
|
|
169
|
-
|
|
170
|
-
logger.
|
|
171
|
-
|
|
172
|
-
}));
|
|
173
|
-
```
|
|
426
|
+
// Enable local console for development
|
|
427
|
+
if (process.env.NODE_ENV === 'development') {
|
|
428
|
+
logger.enableConsole();
|
|
429
|
+
}
|
|
174
430
|
|
|
175
|
-
|
|
431
|
+
// Express middleware for request tracking
|
|
432
|
+
app.use((req, res, next) => {
|
|
433
|
+
const requestId = generateRequestId();
|
|
434
|
+
const logGroup = logger.createLogGroup(requestId);
|
|
435
|
+
|
|
436
|
+
// Attach logger to request
|
|
437
|
+
req.logger = logGroup;
|
|
438
|
+
|
|
439
|
+
// Log request
|
|
440
|
+
logGroup.log('info', 'Incoming request', {
|
|
441
|
+
method: req.method,
|
|
442
|
+
path: req.path,
|
|
443
|
+
ip: req.ip
|
|
444
|
+
});
|
|
445
|
+
|
|
446
|
+
// Track response
|
|
447
|
+
res.on('finish', () => {
|
|
448
|
+
logGroup.log('info', 'Request completed', {
|
|
449
|
+
statusCode: res.statusCode,
|
|
450
|
+
duration: Date.now() - req.startTime
|
|
451
|
+
});
|
|
452
|
+
});
|
|
453
|
+
|
|
454
|
+
next();
|
|
455
|
+
});
|
|
456
|
+
```
|
|
176
457
|
|
|
177
|
-
|
|
458
|
+
### CLI Tool with Progress Tracking
|
|
178
459
|
|
|
179
460
|
```typescript
|
|
461
|
+
import { Smartlog } from '@push.rocks/smartlog';
|
|
180
462
|
import { SmartlogSourceInteractive, SmartlogProgressBar } from '@push.rocks/smartlog/source-interactive';
|
|
463
|
+
|
|
464
|
+
const logger = new Smartlog({
|
|
465
|
+
logContext: {
|
|
466
|
+
containerName: 'migration-tool',
|
|
467
|
+
environment: 'cli'
|
|
468
|
+
}
|
|
469
|
+
});
|
|
470
|
+
|
|
471
|
+
logger.enableConsole();
|
|
472
|
+
|
|
473
|
+
async function migrateDatabase() {
|
|
474
|
+
const spinner = new SmartlogSourceInteractive();
|
|
475
|
+
|
|
476
|
+
// Connect to database
|
|
477
|
+
spinner.text('🔌 Connecting to database...');
|
|
478
|
+
await connectDB();
|
|
479
|
+
spinner.finishSuccess('✅ Connected to database');
|
|
480
|
+
|
|
481
|
+
// Get migrations
|
|
482
|
+
spinner.text('📋 Loading migrations...');
|
|
483
|
+
const migrations = await getMigrations();
|
|
484
|
+
spinner.finishSuccess(`✅ Found ${migrations.length} migrations`);
|
|
485
|
+
|
|
486
|
+
// Run migrations with progress bar
|
|
487
|
+
const progress = new SmartlogProgressBar({
|
|
488
|
+
total: migrations.length,
|
|
489
|
+
width: 40,
|
|
490
|
+
showEta: true
|
|
491
|
+
});
|
|
492
|
+
|
|
493
|
+
for (const [index, migration] of migrations.entries()) {
|
|
494
|
+
logger.log('info', `Running migration: ${migration.name}`);
|
|
495
|
+
await runMigration(migration);
|
|
496
|
+
progress.update(index + 1);
|
|
497
|
+
}
|
|
498
|
+
|
|
499
|
+
progress.complete();
|
|
500
|
+
logger.log('success', '🎉 All migrations completed successfully!');
|
|
501
|
+
}
|
|
181
502
|
```
|
|
182
503
|
|
|
183
|
-
|
|
504
|
+
### Production Logging with Multiple Destinations
|
|
184
505
|
|
|
185
506
|
```typescript
|
|
186
|
-
|
|
507
|
+
import { Smartlog } from '@push.rocks/smartlog';
|
|
508
|
+
import { DestinationLocal } from '@push.rocks/smartlog/destination-local';
|
|
509
|
+
import { SmartlogDestinationFile } from '@push.rocks/smartlog/destination-file';
|
|
510
|
+
import { SmartlogDestinationReceiver } from '@push.rocks/smartlog/destination-receiver';
|
|
187
511
|
|
|
188
|
-
|
|
189
|
-
|
|
512
|
+
const logger = new Smartlog({
|
|
513
|
+
logContext: {
|
|
514
|
+
company: 'Enterprise Corp',
|
|
515
|
+
containerName: 'payment-processor',
|
|
516
|
+
environment: 'production',
|
|
517
|
+
runtime: 'node',
|
|
518
|
+
zone: 'us-east-1'
|
|
519
|
+
},
|
|
520
|
+
minimumLogLevel: 'info' // No debug logs in production
|
|
521
|
+
});
|
|
190
522
|
|
|
191
|
-
//
|
|
192
|
-
|
|
193
|
-
spinner.setColor('blue'); // 'red', 'green', 'yellow', 'blue', etc.
|
|
194
|
-
spinner.setSpeed(80); // Animation speed in milliseconds
|
|
523
|
+
// Console for container logs (structured for log aggregators)
|
|
524
|
+
logger.addLogDestination(new DestinationLocal());
|
|
195
525
|
|
|
196
|
-
//
|
|
197
|
-
|
|
526
|
+
// File for audit trail
|
|
527
|
+
logger.addLogDestination(new SmartlogDestinationFile('/var/log/app/audit.log'));
|
|
198
528
|
|
|
199
|
-
//
|
|
200
|
-
|
|
201
|
-
|
|
529
|
+
// Central logging service
|
|
530
|
+
logger.addLogDestination(new SmartlogDestinationReceiver({
|
|
531
|
+
endpoint: 'https://logs.enterprise.com/ingest',
|
|
532
|
+
apiKey: process.env.LOG_API_KEY,
|
|
533
|
+
batchSize: 100,
|
|
534
|
+
flushInterval: 5000
|
|
535
|
+
}));
|
|
202
536
|
|
|
203
|
-
//
|
|
204
|
-
|
|
205
|
-
|
|
206
|
-
|
|
207
|
-
|
|
537
|
+
// Critical error alerts
|
|
538
|
+
logger.addLogDestination({
|
|
539
|
+
async handleLog(logPackage) {
|
|
540
|
+
if (logPackage.level === 'error' && logPackage.data?.critical) {
|
|
541
|
+
await sendAlert({
|
|
542
|
+
channel: 'ops-team',
|
|
543
|
+
message: `🚨 Critical error: ${logPackage.message}`,
|
|
544
|
+
data: logPackage
|
|
545
|
+
});
|
|
546
|
+
}
|
|
547
|
+
}
|
|
548
|
+
});
|
|
208
549
|
```
|
|
209
550
|
|
|
210
|
-
|
|
551
|
+
## 🔌 Integration with Other Tools
|
|
552
|
+
|
|
553
|
+
### PM2 Integration
|
|
211
554
|
|
|
212
555
|
```typescript
|
|
213
|
-
|
|
214
|
-
|
|
215
|
-
|
|
216
|
-
|
|
217
|
-
|
|
218
|
-
|
|
219
|
-
|
|
220
|
-
|
|
221
|
-
|
|
556
|
+
// ecosystem.config.js
|
|
557
|
+
module.exports = {
|
|
558
|
+
apps: [{
|
|
559
|
+
name: 'api',
|
|
560
|
+
script: './dist/index.js',
|
|
561
|
+
error_file: '/dev/null', // Disable PM2 error log
|
|
562
|
+
out_file: '/dev/null', // Disable PM2 out log
|
|
563
|
+
merge_logs: true,
|
|
564
|
+
env: {
|
|
565
|
+
NODE_ENV: 'production',
|
|
566
|
+
// smartlog handles all logging
|
|
567
|
+
}
|
|
568
|
+
}]
|
|
569
|
+
};
|
|
570
|
+
```
|
|
222
571
|
|
|
223
|
-
|
|
224
|
-
progressBar.update(25); // Set to 25% progress
|
|
572
|
+
### Docker Integration
|
|
225
573
|
|
|
226
|
-
|
|
227
|
-
|
|
574
|
+
```dockerfile
|
|
575
|
+
FROM node:18-alpine
|
|
576
|
+
WORKDIR /app
|
|
577
|
+
COPY . .
|
|
578
|
+
RUN pnpm install --production
|
|
228
579
|
|
|
229
|
-
|
|
230
|
-
|
|
580
|
+
# smartlog handles structured logging
|
|
581
|
+
# No need for special log drivers
|
|
582
|
+
CMD ["node", "dist/index.js"]
|
|
583
|
+
```
|
|
231
584
|
|
|
232
|
-
|
|
233
|
-
|
|
585
|
+
```yaml
|
|
586
|
+
# docker-compose.yml
|
|
587
|
+
services:
|
|
588
|
+
app:
|
|
589
|
+
build: .
|
|
590
|
+
environment:
|
|
591
|
+
- NODE_ENV=production
|
|
592
|
+
# Logs are structured JSON, perfect for log aggregators
|
|
593
|
+
logging:
|
|
594
|
+
driver: "json-file"
|
|
595
|
+
options:
|
|
596
|
+
max-size: "10m"
|
|
597
|
+
max-file: "3"
|
|
234
598
|
```
|
|
235
599
|
|
|
236
|
-
|
|
600
|
+
## 🏆 Best Practices
|
|
237
601
|
|
|
238
|
-
|
|
602
|
+
### 1. Use Semantic Log Levels
|
|
239
603
|
|
|
604
|
+
```typescript
|
|
605
|
+
// ✅ Good - semantic and meaningful
|
|
606
|
+
logger.log('lifecycle', 'Server starting on port 3000');
|
|
607
|
+
logger.log('success', 'Database connection established');
|
|
608
|
+
logger.log('error', 'Failed to process payment', { orderId, error });
|
|
609
|
+
|
|
610
|
+
// ❌ Bad - everything is 'info'
|
|
611
|
+
logger.log('info', 'Server starting');
|
|
612
|
+
logger.log('info', 'Database connected');
|
|
613
|
+
logger.log('info', 'Error: payment failed');
|
|
240
614
|
```
|
|
241
|
-
|
|
242
|
-
|
|
243
|
-
|
|
244
|
-
|
|
245
|
-
|
|
246
|
-
|
|
615
|
+
|
|
616
|
+
### 2. Include Structured Data
|
|
617
|
+
|
|
618
|
+
```typescript
|
|
619
|
+
// ✅ Good - structured data for analysis
|
|
620
|
+
logger.log('error', 'API request failed', {
|
|
621
|
+
endpoint: '/api/users',
|
|
622
|
+
statusCode: 500,
|
|
623
|
+
duration: 1234,
|
|
624
|
+
userId: 'usr_123',
|
|
625
|
+
errorCode: 'INTERNAL_ERROR'
|
|
626
|
+
});
|
|
627
|
+
|
|
628
|
+
// ❌ Bad - data embedded in message
|
|
629
|
+
logger.log('error', `API request to /api/users failed with 500 in 1234ms for user usr_123`);
|
|
247
630
|
```
|
|
248
631
|
|
|
249
|
-
|
|
632
|
+
### 3. Use Log Groups for Correlation
|
|
250
633
|
|
|
251
|
-
|
|
634
|
+
```typescript
|
|
635
|
+
// ✅ Good - correlated logs
|
|
636
|
+
async function processOrder(orderId: string) {
|
|
637
|
+
const logGroup = logger.createLogGroup(orderId);
|
|
638
|
+
|
|
639
|
+
logGroup.log('info', 'Processing order');
|
|
640
|
+
logGroup.log('debug', 'Validating items');
|
|
641
|
+
logGroup.log('info', 'Charging payment');
|
|
642
|
+
logGroup.log('success', 'Order processed');
|
|
643
|
+
}
|
|
644
|
+
|
|
645
|
+
// ❌ Bad - no correlation
|
|
646
|
+
async function processOrder(orderId: string) {
|
|
647
|
+
logger.log('info', `Processing order ${orderId}`);
|
|
648
|
+
logger.log('debug', `Validating items for ${orderId}`);
|
|
649
|
+
logger.log('info', `Charging payment for ${orderId}`);
|
|
650
|
+
}
|
|
651
|
+
```
|
|
252
652
|
|
|
253
|
-
|
|
653
|
+
### 4. Environment-Specific Configuration
|
|
254
654
|
|
|
255
655
|
```typescript
|
|
256
|
-
|
|
656
|
+
// ✅ Good - different configs per environment
|
|
657
|
+
const logger = new Smartlog({
|
|
658
|
+
logContext: {
|
|
659
|
+
environment: process.env.NODE_ENV,
|
|
660
|
+
// ... other context
|
|
661
|
+
},
|
|
662
|
+
minimumLogLevel: process.env.NODE_ENV === 'production' ? 'info' : 'silly'
|
|
663
|
+
});
|
|
664
|
+
|
|
665
|
+
// Add destinations based on environment
|
|
666
|
+
if (process.env.NODE_ENV === 'production') {
|
|
667
|
+
logger.addLogDestination(clickhouseDestination);
|
|
668
|
+
logger.addLogDestination(alertingDestination);
|
|
669
|
+
} else {
|
|
670
|
+
logger.enableConsole();
|
|
671
|
+
}
|
|
257
672
|
```
|
|
258
673
|
|
|
259
|
-
|
|
674
|
+
## 📖 API Reference
|
|
260
675
|
|
|
261
|
-
|
|
676
|
+
### Smartlog Class
|
|
262
677
|
|
|
263
678
|
```typescript
|
|
264
|
-
|
|
679
|
+
class Smartlog {
|
|
680
|
+
constructor(options?: ISmartlogOptions)
|
|
681
|
+
|
|
682
|
+
// Logging methods
|
|
683
|
+
log(level: TLogLevel, message: string, data?: any, correlation?: ILogCorrelation): void
|
|
684
|
+
increment(level: TLogLevel, key: string, data?: any): void
|
|
685
|
+
|
|
686
|
+
// Configuration
|
|
687
|
+
enableConsole(options?: IConsoleOptions): void
|
|
688
|
+
addLogDestination(destination: ILogDestination): void
|
|
689
|
+
addLogContext(context: Partial<ILogContext>): void
|
|
690
|
+
|
|
691
|
+
// Log groups
|
|
692
|
+
createLogGroup(transactionId?: string): LogGroup
|
|
693
|
+
createScope(scopeName: string): Smartlog
|
|
694
|
+
}
|
|
265
695
|
```
|
|
266
696
|
|
|
267
|
-
### Log
|
|
697
|
+
### Log Levels
|
|
268
698
|
|
|
269
|
-
|
|
699
|
+
```typescript
|
|
700
|
+
type TLogLevel =
|
|
701
|
+
| 'silly' // Very verbose debugging
|
|
702
|
+
| 'debug' // Debug information
|
|
703
|
+
| 'info' // Informational messages
|
|
704
|
+
| 'note' // Notable events
|
|
705
|
+
| 'ok' // Success confirmation
|
|
706
|
+
| 'success' // Major success
|
|
707
|
+
| 'warn' // Warning messages
|
|
708
|
+
| 'error' // Error messages
|
|
709
|
+
| 'lifecycle' // Application lifecycle events
|
|
710
|
+
```
|
|
711
|
+
|
|
712
|
+
### Log Package Structure
|
|
270
713
|
|
|
271
714
|
```typescript
|
|
272
|
-
|
|
273
|
-
|
|
274
|
-
|
|
275
|
-
|
|
276
|
-
|
|
715
|
+
interface ILogPackage {
|
|
716
|
+
timestamp: number;
|
|
717
|
+
level: TLogLevel;
|
|
718
|
+
message: string;
|
|
719
|
+
data?: any;
|
|
720
|
+
context: ILogContext;
|
|
721
|
+
correlation?: ILogCorrelation;
|
|
722
|
+
}
|
|
277
723
|
```
|
|
278
724
|
|
|
279
|
-
|
|
725
|
+
For complete API documentation, see [API.md](API.md).
|
|
726
|
+
|
|
727
|
+
## 🤝 Contributing
|
|
280
728
|
|
|
281
|
-
|
|
729
|
+
We welcome contributions! Please see our [Contributing Guide](CONTRIBUTING.md) for details.
|
|
282
730
|
|
|
283
|
-
## License and Legal Information
|
|
731
|
+
## 📄 License and Legal Information
|
|
284
732
|
|
|
285
|
-
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|
733
|
+
This repository contains open-source code that is licensed under the MIT License. A copy of the MIT License can be found in the [license](license) file within this repository.
|
|
286
734
|
|
|
287
735
|
**Please note:** The MIT License does not grant permission to use the trade names, trademarks, service marks, or product names of the project, except as required for reasonable and customary use in describing the origin of the work and reproducing the content of the NOTICE file.
|
|
288
736
|
|