@egi/smart-log 1.0.0

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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Marcel Egloff
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md ADDED
@@ -0,0 +1,206 @@
1
+ # smart-log
2
+
3
+ A TypeScript logging library with severity levels, flexible formatting, stack trace integration, and optional persistence via a pluggable db writer.
4
+
5
+ ## Installation
6
+
7
+ ```bash
8
+ npm install @egi/smart-log
9
+ ```
10
+
11
+ ## Quick Start
12
+
13
+ ```typescript
14
+ import { smartLog, SmartSeverityLevel } from "@egi/smart-log";
15
+
16
+ smartLog.info("Application started");
17
+ smartLog.warning("Low disk space");
18
+ smartLog.error(new Error("Something went wrong"));
19
+ ```
20
+
21
+ A singleton instance `smartLog` is exported for convenience. Create additional instances as needed:
22
+
23
+ ```typescript
24
+ import { SmartLog } from "@egi/smart-log";
25
+
26
+ const log = new SmartLog({ logLevel: SmartSeverityLevel.Debug });
27
+ log.debug("detailed trace");
28
+ ```
29
+
30
+ ## Severity Levels
31
+
32
+ ```typescript
33
+ enum SmartSeverityLevel {
34
+ None = 0, Fatal = 1, Error = 2, Warning = 3,
35
+ Info = 4, Verbose = 5, Debug = 6, All = 9
36
+ }
37
+ ```
38
+
39
+ Methods: `fatal()`, `error()`, `warning()`, `info()`, `verbose()`, `debug()`, `write()` (no severity).
40
+
41
+ Each method accepts a string, an `Error`, or a string + `SmartMessageOptions`:
42
+
43
+ ```typescript
44
+ log.error("fetch failed", { data: err, location: "api.ts:42" });
45
+ log.info("user logged in", { type: "BACKEND", timestamp: new Date() });
46
+ log.debug("internal detail", { skipConsole: true }); // db writer only
47
+ log.info("console only", { skipDatabase: true }); // console only
48
+ ```
49
+
50
+ ## Options
51
+
52
+ ```typescript
53
+ const log = new SmartLog({
54
+ logLevel: SmartSeverityLevel.Info, // minimum level to process
55
+ logChannels: true, // route to console.error/warn/info/debug by level
56
+ location: true, // include caller location in output
57
+ leading: "[APP]", // prefix every line
58
+ separator: " | ", // separator between format elements
59
+ lowerCase: false, // lowercase severity codes
60
+ user: "admin", // user id stamped on each log entry
61
+ dbWriter: myWriter, // persist entries (see below)
62
+ outputHook: (text, msg) => {}, // side-effect hook; return { suppress: true } to skip console
63
+ formatHook: (text, msg) => text, // transform output text before console
64
+ stackProvider: () => new Error(), // custom stack source for caller detection
65
+ });
66
+ ```
67
+
68
+ ## Log Format
69
+
70
+ The output format is fully configurable via `sequence`. Elements can be enum values, fixed strings, or functions:
71
+
72
+ ```typescript
73
+ import { SmartLog, SmartLogFormatElement } from "@egi/smart-log";
74
+
75
+ const log = new SmartLog({
76
+ leading: "%",
77
+ lowerCase: true,
78
+ location: true,
79
+ sequence: [
80
+ SmartLogFormatElement.Severity,
81
+ "myapp",
82
+ SmartLogFormatElement.Timestamp,
83
+ SmartLogFormatElement.Message,
84
+ SmartLogFormatElement.Location,
85
+ () => process.pid.toString()
86
+ ]
87
+ });
88
+ ```
89
+
90
+ | Element | Output |
91
+ |---|---|
92
+ | `Severity` | Single letter code: `F E W I I D` |
93
+ | `Type` | First letter of the location type (App → `A`) |
94
+ | `Timestamp` | `2024-03-15 14:30:00.000` |
95
+ | `Message` | The log message text |
96
+ | `Location` | `[file.ts:42 (functionName)]` |
97
+
98
+ Default sequence: `Severity - Type - Timestamp: Message [Location]`
99
+
100
+ ## Output Hook
101
+
102
+ `outputHook` is called after formatting and before console output. Use it for side effects — writing to a file, sending to a remote service, emitting events — without needing to implement a full `ISmartLogDbWriter`.
103
+
104
+ Return `false` to prevent the entry from appearing on the console. Both sync and async hooks are supported.
105
+
106
+ ```typescript
107
+ import { SmartLog, LogMessage } from "@egi/smart-log";
108
+
109
+ const log = new SmartLog({
110
+ outputHook: (text: string, message: LogMessage) => {
111
+ fs.appendFileSync("app.log", text + "\n");
112
+ // return false to hide from console as well
113
+ }
114
+ });
115
+
116
+ // or set it later:
117
+ log.setOutputHook(async (text, message) => {
118
+ await sendToSlack(text);
119
+ return false; // already sent, no need to also print
120
+ });
121
+
122
+ // transform text only:
123
+ log.setFormatHook((text) => `[MyApp] ${text}`);
124
+ ```
125
+
126
+ `formatHook` and `outputHook` serve different purposes:
127
+
128
+ | Hook | Purpose | Must return |
129
+ |---|---|---|
130
+ | `formatHook` | Transform the formatted text | Modified string |
131
+ | `outputHook` | Side effects / suppress console | `void` or `false` |
132
+
133
+ ## Database Persistence
134
+
135
+ Implement `ISmartLogDbWriter` to persist log entries:
136
+
137
+ ```typescript
138
+ import { ISmartLogDbWriter, LogMessage } from "@egi/smart-log";
139
+
140
+ class MyDbWriter implements ISmartLogDbWriter {
141
+ write(entry: LogMessage): Promise<void> | void {
142
+ // entry contains: severityLevel, type, location, message, data, timestamp, user
143
+ return db.insert("logs", entry);
144
+ }
145
+ }
146
+
147
+ const log = new SmartLog({ dbWriter: new MyDbWriter() });
148
+
149
+ // change or disable the writer at runtime:
150
+ log.setDbWriter(null);
151
+ ```
152
+
153
+ The writer receives the raw `LogMessage` object — sync or async writers are both supported.
154
+
155
+ ## Location Types
156
+
157
+ ```typescript
158
+ enum SmartLocation {
159
+ App = "APP",
160
+ Frontend = "FRONTEND",
161
+ Backend = "BACKEND",
162
+ Database = "DATABASE",
163
+ UpgradeManager = "UPGRADE-MANAGER"
164
+ }
165
+ ```
166
+
167
+ ## Date Utilities
168
+
169
+ ```typescript
170
+ import { toSmartDbDate, toSmartDbTimestamp, smartDbToDate, smartDbToDateTime } from "@egi/smart-log";
171
+
172
+ toSmartDbDate(new Date()) // "2024-03-15 14:30:00"
173
+ toSmartDbTimestamp(new Date()) // "2024-03-15 14:30:00.000"
174
+ smartDbToDate("2024-03-15 14:30:00") // Date object
175
+ smartDbToDateTime(1710508200000) // Luxon DateTime object
176
+ ```
177
+
178
+ ## SmartError
179
+
180
+ A structured error class for use throughout the stack:
181
+
182
+ ```typescript
183
+ import { SmartError, SmartSeverityLevel, SmartLocation } from "@egi/smart-log";
184
+
185
+ throw new SmartError({
186
+ message: "Record not found",
187
+ code: 404,
188
+ type: SmartSeverityLevel.Error,
189
+ location: SmartLocation.Backend
190
+ });
191
+ ```
192
+
193
+ ## SmartTools
194
+
195
+ Utility singleton for string conversions and stack inspection:
196
+
197
+ ```typescript
198
+ import { tools } from "@egi/smart-log";
199
+
200
+ tools.camelCase("my_field_name") // "myFieldName"
201
+ tools.snakeCase("myFieldName") // "my_field_name"
202
+ tools.kebabCase("MyComponent") // "my-component"
203
+ tools.pascalCase("my_model") // "MyModel"
204
+
205
+ tools.getCallerFromStack() // "src/app.ts:42 (doSomething)"
206
+ ```
package/package.json ADDED
@@ -0,0 +1,29 @@
1
+ {
2
+ "name": "@egi/smart-log",
3
+ "version": "1.0.0",
4
+ "description": "Smart logging library with severity levels, flexible formatting, and optional DB persistence",
5
+ "author": "Marcel Egloff",
6
+ "main": "./smart-log-api.js",
7
+ "repository": {
8
+ "type": "git",
9
+ "url": "https://vault.pegasus-consulting.ch/smart-log"
10
+ },
11
+ "keywords": [
12
+ "logging",
13
+ "smart",
14
+ "log",
15
+ "typescript",
16
+ "severity",
17
+ "logger"
18
+ ],
19
+ "exports": {
20
+ ".": {
21
+ "default": "./smart-log-api.js"
22
+ }
23
+ },
24
+ "types": "./smart-log-api.d.ts",
25
+ "dependencies": {
26
+ "luxon": "^3.5.0"
27
+ },
28
+ "license": "MIT"
29
+ }
@@ -0,0 +1,22 @@
1
+ import { SmartLocation, SmartSeverityLevel } from "./smart-log";
2
+ export type SmartErrorLocation = SmartLocation;
3
+ export interface SmartErrorData {
4
+ code?: number | string;
5
+ info?: Record<string, any>;
6
+ location?: SmartLocation;
7
+ message: string;
8
+ name: string;
9
+ timestamp?: Date | string | number;
10
+ type?: SmartSeverityLevel;
11
+ }
12
+ export declare class SmartError extends Error implements SmartErrorData {
13
+ code: number | string;
14
+ info: Record<string, any>;
15
+ location: SmartLocation;
16
+ timestamp: Date | string | number;
17
+ type: SmartSeverityLevel;
18
+ private smartErrorKeys;
19
+ constructor(message: any);
20
+ toObject(): SmartErrorData;
21
+ toString(): string;
22
+ }
package/smart-error.js ADDED
@@ -0,0 +1,123 @@
1
+ "use strict";
2
+ // noinspection JSUnusedGlobalSymbols
3
+ var __extends = (this && this.__extends) || (function () {
4
+ var extendStatics = function (d, b) {
5
+ extendStatics = Object.setPrototypeOf ||
6
+ ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) ||
7
+ function (d, b) { for (var p in b) if (Object.prototype.hasOwnProperty.call(b, p)) d[p] = b[p]; };
8
+ return extendStatics(d, b);
9
+ };
10
+ return function (d, b) {
11
+ if (typeof b !== "function" && b !== null)
12
+ throw new TypeError("Class extends value " + String(b) + " is not a constructor or null");
13
+ extendStatics(d, b);
14
+ function __() { this.constructor = d; }
15
+ d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __());
16
+ };
17
+ })();
18
+ Object.defineProperty(exports, "__esModule", { value: true });
19
+ exports.SmartError = void 0;
20
+ var smart_log_1 = require("./smart-log");
21
+ var SmartError = /** @class */ (function (_super) {
22
+ __extends(SmartError, _super);
23
+ function SmartError(message) {
24
+ var _this = this;
25
+ var errorKeys = ["message", "name", "code", "type", "location", "timestamp", "info"];
26
+ var newMessage;
27
+ var code;
28
+ var type;
29
+ var location;
30
+ var name;
31
+ var timestamp;
32
+ var info;
33
+ if (message === undefined || typeof message == "string") {
34
+ newMessage = message;
35
+ }
36
+ else if (typeof message == "object") {
37
+ if (typeof message.message == "string") {
38
+ newMessage = message.message;
39
+ }
40
+ else if (typeof message.text == "string") {
41
+ newMessage = message.text;
42
+ }
43
+ else if (typeof message.error == "string") {
44
+ newMessage = message.error;
45
+ }
46
+ else {
47
+ newMessage = "Error";
48
+ }
49
+ name = message.name;
50
+ code = message.code;
51
+ type = message.type;
52
+ location = message.location;
53
+ timestamp = message.timestamp;
54
+ if (!message.constructor) {
55
+ var keys = Object.keys(message).filter(function (key) { return !errorKeys.includes(key); });
56
+ if (keys.length > 0) {
57
+ info = {};
58
+ keys.forEach(function (key) {
59
+ info[key] = message[key];
60
+ });
61
+ }
62
+ }
63
+ }
64
+ else if (typeof message.toString == "function") {
65
+ newMessage = message.toString();
66
+ }
67
+ else {
68
+ newMessage = message;
69
+ }
70
+ _this = _super.call(this, newMessage) || this;
71
+ _this.name = name !== null && name !== void 0 ? name : "";
72
+ _this.code = code !== null && code !== void 0 ? code : -1;
73
+ _this.type = type !== null && type !== void 0 ? type : smart_log_1.SmartSeverityLevel.Error;
74
+ if (location) {
75
+ _this.location = location;
76
+ }
77
+ if (timestamp) {
78
+ _this.timestamp = timestamp;
79
+ }
80
+ if (info) {
81
+ _this.info = info;
82
+ }
83
+ _this.smartErrorKeys = errorKeys;
84
+ return _this;
85
+ }
86
+ SmartError.prototype.toObject = function () {
87
+ var _this = this;
88
+ var obj = {
89
+ name: this.name,
90
+ message: this.message
91
+ };
92
+ this.smartErrorKeys.forEach(function (key) {
93
+ if (key != "name" && key != "message") {
94
+ if (_this[key]) {
95
+ obj[key] = _this[key];
96
+ }
97
+ }
98
+ });
99
+ return obj;
100
+ };
101
+ SmartError.prototype.toString = function () {
102
+ var output = _super.prototype.toString.call(this);
103
+ var addition = "";
104
+ if (this.type) {
105
+ addition += this.type;
106
+ }
107
+ if (this.location) {
108
+ if (addition !== "") {
109
+ addition += "-";
110
+ }
111
+ addition += this.location;
112
+ }
113
+ if (this.code) {
114
+ if (addition !== "") {
115
+ addition += " #";
116
+ }
117
+ addition += this.code;
118
+ }
119
+ return output + " (" + addition + ")";
120
+ };
121
+ return SmartError;
122
+ }(Error));
123
+ exports.SmartError = SmartError;
@@ -0,0 +1,4 @@
1
+ export * from "./smart-error";
2
+ export * from "./smart-tools";
3
+ export * from "./smart-log";
4
+ export * from "./smart-log-date-utils";
@@ -0,0 +1,21 @@
1
+ "use strict";
2
+ // noinspection JSUnusedGlobalSymbols
3
+ var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
4
+ if (k2 === undefined) k2 = k;
5
+ var desc = Object.getOwnPropertyDescriptor(m, k);
6
+ if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
7
+ desc = { enumerable: true, get: function() { return m[k]; } };
8
+ }
9
+ Object.defineProperty(o, k2, desc);
10
+ }) : (function(o, m, k, k2) {
11
+ if (k2 === undefined) k2 = k;
12
+ o[k2] = m[k];
13
+ }));
14
+ var __exportStar = (this && this.__exportStar) || function(m, exports) {
15
+ for (var p in m) if (p !== "default" && !Object.prototype.hasOwnProperty.call(exports, p)) __createBinding(exports, m, p);
16
+ };
17
+ Object.defineProperty(exports, "__esModule", { value: true });
18
+ __exportStar(require("./smart-error"), exports);
19
+ __exportStar(require("./smart-tools"), exports);
20
+ __exportStar(require("./smart-log"), exports);
21
+ __exportStar(require("./smart-log-date-utils"), exports);
@@ -0,0 +1,24 @@
1
+ import { DateTime } from "luxon";
2
+ export declare const SmartLogDateRegexp: RegExp;
3
+ export declare const SmartLogTimestampRegexp: RegExp;
4
+ export declare const validDateTimeFormats: string[];
5
+ /**
6
+ * Returns a DB date string for a given timezone (local timezone if 'zone' omitted).
7
+ */
8
+ export declare function toSmartDbDate(date: Date | number | DateTime, zone?: string, addZone?: boolean): string | null;
9
+ /**
10
+ * Returns a DB timestamp string for a given timezone (local timezone if 'zone' omitted).
11
+ */
12
+ export declare function toSmartDbTimestamp(date: string | number | Date | DateTime, timezone?: string): string | null;
13
+ /**
14
+ * Returns a timestamp string for a given timezone (local timezone if 'zone' omitted).
15
+ */
16
+ export declare function toSmartZoneTimestamp(date: Date | number | DateTime, zone?: string, omitZone?: boolean): string | null;
17
+ /**
18
+ * Converts a date value to a JavaScript Date object.
19
+ */
20
+ export declare function smartDbToDate(date: Date | number | string | DateTime, zone?: string): Date | null;
21
+ /**
22
+ * Converts a date value to a Luxon DateTime object in the given zone (local timezone if 'zone' omitted).
23
+ */
24
+ export declare function smartDbToDateTime(date: Date | number | string | DateTime, zone?: string): DateTime | null;
@@ -0,0 +1,129 @@
1
+ "use strict";
2
+ Object.defineProperty(exports, "__esModule", { value: true });
3
+ exports.validDateTimeFormats = exports.SmartLogTimestampRegexp = exports.SmartLogDateRegexp = void 0;
4
+ exports.toSmartDbDate = toSmartDbDate;
5
+ exports.toSmartDbTimestamp = toSmartDbTimestamp;
6
+ exports.toSmartZoneTimestamp = toSmartZoneTimestamp;
7
+ exports.smartDbToDate = smartDbToDate;
8
+ exports.smartDbToDateTime = smartDbToDateTime;
9
+ var luxon_1 = require("luxon");
10
+ exports.SmartLogDateRegexp = /^(\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d)(Z|[+-]\d\d:\d\d)?$/;
11
+ exports.SmartLogTimestampRegexp = /^(\d{4}-[01]\d-[0-3]\d [0-2]\d:[0-5]\d:[0-5]\d\.\d{3})(Z|[+-]\d\d:\d\d)?$/;
12
+ exports.validDateTimeFormats = [
13
+ "yyyy-MM-dd",
14
+ "yyyy-MM-ddZZ",
15
+ "yyyy-MM-dd HH:mm:ss",
16
+ "yyyy-MM-dd HH:mm:ssZZ",
17
+ "yyyy-MM-dd HH:mm:ss.u",
18
+ "yyyy-MM-dd HH:mm:ss.uZZ",
19
+ "yyyy-MM-dd'T'HH:mm:ss",
20
+ "yyyy-MM-dd'T'HH:mm:ssZZ",
21
+ "yyyy-MM-dd'T'HH:mm:ss.u",
22
+ "yyyy-MM-dd'T'HH:mm:ss.uZZ"
23
+ ];
24
+ /**
25
+ * Returns a DB date string for a given timezone (local timezone if 'zone' omitted).
26
+ */
27
+ function toSmartDbDate(date, zone, addZone) {
28
+ var timestampString = null;
29
+ if (date) {
30
+ var dt = void 0;
31
+ if (typeof date == "number") {
32
+ dt = luxon_1.DateTime.fromMillis(date, { zone: zone });
33
+ }
34
+ else if (date instanceof Date) {
35
+ dt = luxon_1.DateTime.fromJSDate(date, { zone: zone });
36
+ }
37
+ else {
38
+ dt = date;
39
+ }
40
+ if (zone && addZone) {
41
+ if (zone.toUpperCase() == "UTC" || zone.toUpperCase() == "GMT") {
42
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ss") + "Z";
43
+ }
44
+ else {
45
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ssZZ");
46
+ }
47
+ }
48
+ else {
49
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ss");
50
+ }
51
+ }
52
+ else {
53
+ throw "no date given to toSmartDbDate()";
54
+ }
55
+ return timestampString;
56
+ }
57
+ /**
58
+ * Returns a DB timestamp string for a given timezone (local timezone if 'zone' omitted).
59
+ */
60
+ function toSmartDbTimestamp(date, timezone) {
61
+ var timestampString = null;
62
+ var dt = smartDbToDateTime(date !== null && date !== void 0 ? date : new Date());
63
+ if (timezone) {
64
+ timestampString = dt.setZone(timezone).toFormat("yyyy-MM-dd HH:mm:ss.uZZ").replace("+00:00", "Z");
65
+ }
66
+ else {
67
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ss.u");
68
+ }
69
+ return timestampString;
70
+ }
71
+ /**
72
+ * Returns a timestamp string for a given timezone (local timezone if 'zone' omitted).
73
+ */
74
+ function toSmartZoneTimestamp(date, zone, omitZone) {
75
+ var timestampString = null;
76
+ if (date) {
77
+ var dt = void 0;
78
+ if (typeof date == "number") {
79
+ dt = luxon_1.DateTime.fromMillis(date, { zone: zone });
80
+ }
81
+ else if (date instanceof Date) {
82
+ dt = luxon_1.DateTime.fromJSDate(date, { zone: zone });
83
+ }
84
+ else {
85
+ dt = date.setZone(zone);
86
+ }
87
+ if (omitZone) {
88
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ss.u");
89
+ }
90
+ else {
91
+ timestampString = dt.toFormat("yyyy-MM-dd HH:mm:ss.uZZ").replace("+00:00", "Z");
92
+ }
93
+ }
94
+ return timestampString;
95
+ }
96
+ /**
97
+ * Converts a date value to a JavaScript Date object.
98
+ */
99
+ function smartDbToDate(date, zone) {
100
+ var dt = smartDbToDateTime(date, zone);
101
+ return dt && dt.isValid ? dt.toJSDate() : null;
102
+ }
103
+ /**
104
+ * Converts a date value to a Luxon DateTime object in the given zone (local timezone if 'zone' omitted).
105
+ */
106
+ function smartDbToDateTime(date, zone) {
107
+ var dt = null;
108
+ if (date) {
109
+ if (typeof date == "number") {
110
+ dt = luxon_1.DateTime.fromMillis(date, { zone: zone });
111
+ }
112
+ else if (typeof date == "string") {
113
+ var pattern = exports.validDateTimeFormats.find(function (format) {
114
+ var d = luxon_1.DateTime.fromFormat(date, format);
115
+ return d.isValid;
116
+ });
117
+ if (pattern) {
118
+ dt = luxon_1.DateTime.fromFormat(date, pattern, { zone: zone });
119
+ }
120
+ }
121
+ else if (date instanceof Date) {
122
+ dt = luxon_1.DateTime.fromJSDate(date, { zone: zone });
123
+ }
124
+ else {
125
+ dt = date.setZone(zone);
126
+ }
127
+ }
128
+ return dt;
129
+ }