@wlix/logger 1.0.3 → 2.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,7 @@
1
+ Copyright 2026 Andrew (e60m5ss / wlix)
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the “Software”), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:
4
+
5
+ The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.
6
+
7
+ THE SOFTWARE IS PROVIDED “AS IS”, WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
package/README.md CHANGED
@@ -1,34 +1,53 @@
1
- # @wlix/logger
1
+ <h1 align="center">@wlix/logger</h1>
2
2
 
3
- A tiny file-based logger for Node.js projects. It writes logs to daily files and can also print them to stdout.
3
+ > Tiny file-based logger for Node.js projects
4
4
 
5
- ## How it works
5
+ ## Installation
6
6
 
7
- - When you create a logger instance, it makes sure the logs directory exists.
8
- - Each calendar day gets its own log file named `DD-MM-YYYY.log`.
9
- - Every log line has UTC time (or UTC offset), log type (info, warn, or error), and message.
10
- - Logs are then written to the appropriate log file.
11
-
12
- ## Usage
13
-
14
- - Use `createLogger()` to create a new logger.
15
- - Use the returned function with `"info" | "warn" | "error"` and your message.
16
- - Files are written to the `./logs` dir by default.
7
+ ```bash
8
+ npm install @wlix/logger
9
+ # or
10
+ yarn add @wlix/logger
11
+ # or
12
+ pnpm add @wlix/logger
13
+ # or
14
+ bun add @wlix/logger
15
+ ```
17
16
 
18
- ```ts
19
- import { createLogger } from "./Logger";
17
+ ## Example
18
+
19
+ ```js
20
+ import { Logger } from "@wlix/logger";
21
+
22
+ // all options are optional
23
+ const logger = new Logger({
24
+ logsPath: "./logs", // where log files will go
25
+ logToStdout: true, // log to console (default: true)
26
+ timezone: "UTC", // timezone (UTC offsets, e.g., UTC+3 or UTC-7)
27
+ });
28
+
29
+ logger.info("This is information"); // green [INFO] log
30
+ logger.warn("This is a warning"); // orange [WARN] log
31
+ logger.error("This is an error"); // red [ERROR] log
32
+
33
+ // custom logs
34
+ logger.log("This is a custom log", {
35
+ level: "example", // appears as [EXAMPLE] This is a custom log
36
+ color: "blue", // suppots multiple color presets, ...or:
37
+ hex: "#0000FF", // supports hex colors
38
+ });
39
+
40
+ logger.set({
41
+ // ...change logger config
42
+ // same options when initialising
43
+ timezone: "UTC+2",
44
+ });
45
+ ```
20
46
 
21
- const logger = createLogger();
47
+ ## Contributing
22
48
 
23
- logger("info", "Connected to server");
24
- logger("warn", "Memory is low");
25
- logger("error", "Something went wrong");
26
- ```
49
+ Pull requests are always welcomed. For more major changes, please open an issue to discuss what you wish to change.
27
50
 
28
- ## Configuration
51
+ ## License
29
52
 
30
- | Option | Type | Default | Description |
31
- | ------------- | ----------------------- | ---------- | ---------------------------------------------------------------- |
32
- | `logsPath` | `string` | `"./logs"` | Path of the directory where log files are stored |
33
- | `logToStdout` | `boolean` | `true` | Whether to print logs to the console |
34
- | `timezone` | `"UTC"` \| `UTC±number` | `"UTC"` | Timezone for log timestamps, e.g., `"UTC"`, `"UTC+3"`, `"UTC-6"` |
53
+ [MIT](LICENSE)
@@ -0,0 +1,60 @@
1
+ declare const colors: {
2
+ readonly beige: "#eab28c";
3
+ readonly black: "#000000";
4
+ readonly blue: "#3b79de";
5
+ readonly brown: "#8e7867";
6
+ readonly cyan: "#4cb2d7";
7
+ readonly green: "#87c54e";
8
+ readonly orange: "#e5822f";
9
+ readonly pink: "#f480ff";
10
+ readonly purple: "#b860db";
11
+ readonly red: "#F14746";
12
+ readonly white: "#ffffff";
13
+ readonly yellow: "#d3ba57";
14
+ };
15
+
16
+ interface LoggerOptions {
17
+ /**
18
+ * Path of directory to write log files to
19
+ * @default null
20
+ */
21
+ logsPath?: string;
22
+
23
+ /**
24
+ * Whether to log to stdout
25
+ * @default true
26
+ */
27
+ logToStdout?: boolean;
28
+
29
+ /**
30
+ * Timezone in UTC offsets
31
+ * @example UTC
32
+ * @example UTC+2
33
+ * @example UTC-5
34
+ * @default UTC
35
+ */
36
+ timezone?: Timezone;
37
+ }
38
+
39
+ type Timezone = "UTC" | `UTC${"" | "+" | "-"}${number}`;
40
+
41
+ interface WriteOptions {
42
+ level: string;
43
+ message: string;
44
+ color?: keyof typeof colors;
45
+ hex?: string;
46
+ }
47
+
48
+ declare class Logger {
49
+ #private;
50
+ constructor(options: LoggerOptions);
51
+ set(options?: LoggerOptions): void;
52
+ info(message: string, options?: LoggerOptions): Logger;
53
+ warn(message: string, options?: LoggerOptions): Logger;
54
+ error(message: string, options?: LoggerOptions): Logger;
55
+ log(message: string, options?: Omit<WriteOptions, "message"> & {
56
+ level?: string;
57
+ }): Logger;
58
+ }
59
+
60
+ export { Logger, type LoggerOptions, type Timezone };
@@ -0,0 +1,60 @@
1
+ declare const colors: {
2
+ readonly beige: "#eab28c";
3
+ readonly black: "#000000";
4
+ readonly blue: "#3b79de";
5
+ readonly brown: "#8e7867";
6
+ readonly cyan: "#4cb2d7";
7
+ readonly green: "#87c54e";
8
+ readonly orange: "#e5822f";
9
+ readonly pink: "#f480ff";
10
+ readonly purple: "#b860db";
11
+ readonly red: "#F14746";
12
+ readonly white: "#ffffff";
13
+ readonly yellow: "#d3ba57";
14
+ };
15
+
16
+ interface LoggerOptions {
17
+ /**
18
+ * Path of directory to write log files to
19
+ * @default null
20
+ */
21
+ logsPath?: string;
22
+
23
+ /**
24
+ * Whether to log to stdout
25
+ * @default true
26
+ */
27
+ logToStdout?: boolean;
28
+
29
+ /**
30
+ * Timezone in UTC offsets
31
+ * @example UTC
32
+ * @example UTC+2
33
+ * @example UTC-5
34
+ * @default UTC
35
+ */
36
+ timezone?: Timezone;
37
+ }
38
+
39
+ type Timezone = "UTC" | `UTC${"" | "+" | "-"}${number}`;
40
+
41
+ interface WriteOptions {
42
+ level: string;
43
+ message: string;
44
+ color?: keyof typeof colors;
45
+ hex?: string;
46
+ }
47
+
48
+ declare class Logger {
49
+ #private;
50
+ constructor(options: LoggerOptions);
51
+ set(options?: LoggerOptions): void;
52
+ info(message: string, options?: LoggerOptions): Logger;
53
+ warn(message: string, options?: LoggerOptions): Logger;
54
+ error(message: string, options?: LoggerOptions): Logger;
55
+ log(message: string, options?: Omit<WriteOptions, "message"> & {
56
+ level?: string;
57
+ }): Logger;
58
+ }
59
+
60
+ export { Logger, type LoggerOptions, type Timezone };
package/dist/index.js ADDED
@@ -0,0 +1,185 @@
1
+ "use strict";
2
+ var __create = Object.create;
3
+ var __defProp = Object.defineProperty;
4
+ var __getOwnPropDesc = Object.getOwnPropertyDescriptor;
5
+ var __getOwnPropNames = Object.getOwnPropertyNames;
6
+ var __getProtoOf = Object.getPrototypeOf;
7
+ var __hasOwnProp = Object.prototype.hasOwnProperty;
8
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
9
+ var __export = (target, all) => {
10
+ for (var name in all)
11
+ __defProp(target, name, { get: all[name], enumerable: true });
12
+ };
13
+ var __copyProps = (to, from, except, desc) => {
14
+ if (from && typeof from === "object" || typeof from === "function") {
15
+ for (let key of __getOwnPropNames(from))
16
+ if (!__hasOwnProp.call(to, key) && key !== except)
17
+ __defProp(to, key, { get: () => from[key], enumerable: !(desc = __getOwnPropDesc(from, key)) || desc.enumerable });
18
+ }
19
+ return to;
20
+ };
21
+ var __toESM = (mod, isNodeMode, target) => (target = mod != null ? __create(__getProtoOf(mod)) : {}, __copyProps(
22
+ // If the importer is in node compatibility mode or this is not an ESM
23
+ // file that has been converted to a CommonJS file using a Babel-
24
+ // compatible transform (i.e. "__esModule" has not been set), then set
25
+ // "default" to the CommonJS "module.exports" for node compatibility.
26
+ isNodeMode || !mod || !mod.__esModule ? __defProp(target, "default", { value: mod, enumerable: true }) : target,
27
+ mod
28
+ ));
29
+ var __toCommonJS = (mod) => __copyProps(__defProp({}, "__esModule", { value: true }), mod);
30
+
31
+ // src/index.ts
32
+ var index_exports = {};
33
+ __export(index_exports, {
34
+ Logger: () => Logger
35
+ });
36
+ module.exports = __toCommonJS(index_exports);
37
+
38
+ // src/logger.ts
39
+ var import_node_fs = __toESM(require("fs"));
40
+ var import_node_path = __toESM(require("path"));
41
+
42
+ // src/colors.ts
43
+ var colors = {
44
+ beige: "#eab28c",
45
+ black: "#000000",
46
+ blue: "#3b79de",
47
+ brown: "#8e7867",
48
+ cyan: "#4cb2d7",
49
+ green: "#87c54e",
50
+ orange: "#e5822f",
51
+ pink: "#f480ff",
52
+ purple: "#b860db",
53
+ red: "#F14746",
54
+ white: "#ffffff",
55
+ yellow: "#d3ba57"
56
+ };
57
+
58
+ // src/logger.ts
59
+ var Logger = class {
60
+ static {
61
+ __name(this, "Logger");
62
+ }
63
+ #options = {
64
+ logToStdout: true,
65
+ timezone: "UTC"
66
+ };
67
+ /**
68
+ * Instantiate a new logger
69
+ * @param options Logger config
70
+ */
71
+ constructor(options) {
72
+ this.#options = { ...this.#options, ...options };
73
+ }
74
+ #color(input, hex) {
75
+ return `\x1B[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m${input}\x1B[0m`;
76
+ }
77
+ #getDate(date, timezone = "UTC") {
78
+ if (timezone === "UTC") {
79
+ return date;
80
+ }
81
+ const match = timezone.match(/^UTC([+-]\d{1,2})$/);
82
+ if (!match || !match[1]) {
83
+ return date;
84
+ }
85
+ return new Date(
86
+ date.getTime() + date.getTimezoneOffset() * 6e4 + parseInt(match[1], 10) * 36e5
87
+ );
88
+ }
89
+ #write(options) {
90
+ const now = this.#getDate(/* @__PURE__ */ new Date(), this.#options.timezone);
91
+ const time = `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
92
+ const line = `[${time} ${this.#options.timezone}] [${options.level.toUpperCase()}] ${options.message.trim()}`;
93
+ if (this.#options.logsPath) {
94
+ const fileName = `${now.getDate().toString().padStart(2, "0")}-${(now.getMonth() + 1).toString().padStart(2, "0")}-${now.getFullYear()}.log`;
95
+ import_node_fs.default.mkdirSync(this.#options.logsPath, { recursive: true });
96
+ import_node_fs.default.appendFileSync(
97
+ import_node_path.default.join(this.#options.logsPath, fileName),
98
+ line + "\n"
99
+ );
100
+ }
101
+ if (this.#options.logToStdout) {
102
+ if (options.hex || options.color) {
103
+ const hex = options.hex ? options.hex.startsWith("#") ? options.hex : `#${options.hex}` : colors[options.color];
104
+ console.log(this.#color(line, hex));
105
+ } else {
106
+ console.log(line);
107
+ }
108
+ }
109
+ }
110
+ /**
111
+ * Update the logger's options
112
+ * @param options New config
113
+ */
114
+ set(options = {}) {
115
+ this.#options = { ...this.#options, ...options };
116
+ }
117
+ /**
118
+ * Info log
119
+ * Green text, INFO level
120
+ * @param message Log message
121
+ * @param options Optional log options
122
+ * @returns
123
+ */
124
+ info(message, options) {
125
+ this.#write({
126
+ level: "info",
127
+ color: "green",
128
+ message,
129
+ ...options
130
+ });
131
+ return this;
132
+ }
133
+ /**
134
+ * Warning log
135
+ * Orange text, WARN level
136
+ * @param message Log message
137
+ * @param options Optional log options
138
+ * @returns
139
+ */
140
+ warn(message, options) {
141
+ this.#write({
142
+ level: "warn",
143
+ message,
144
+ color: "orange",
145
+ ...options
146
+ });
147
+ return this;
148
+ }
149
+ /**
150
+ * Error log
151
+ * Red text, ERROR level
152
+ * @param message Log message
153
+ * @param options Optional log options
154
+ * @returns
155
+ */
156
+ error(message, options) {
157
+ this.#write({
158
+ level: "error",
159
+ message,
160
+ color: "red",
161
+ ...options
162
+ });
163
+ return this;
164
+ }
165
+ /**
166
+ * Custom logs
167
+ * @param message Log message
168
+ * @param options Log options
169
+ */
170
+ log(message, options) {
171
+ if (!message) {
172
+ throw new Error("Logging requires a message");
173
+ }
174
+ this.#write({
175
+ ...options,
176
+ message,
177
+ level: options?.level ?? "log"
178
+ });
179
+ return this;
180
+ }
181
+ };
182
+ // Annotate the CommonJS export names for ESM import in node:
183
+ 0 && (module.exports = {
184
+ Logger
185
+ });
package/dist/index.mjs ADDED
@@ -0,0 +1,150 @@
1
+ var __defProp = Object.defineProperty;
2
+ var __name = (target, value) => __defProp(target, "name", { value, configurable: true });
3
+
4
+ // src/logger.ts
5
+ import fs from "fs";
6
+ import path from "path";
7
+
8
+ // src/colors.ts
9
+ var colors = {
10
+ beige: "#eab28c",
11
+ black: "#000000",
12
+ blue: "#3b79de",
13
+ brown: "#8e7867",
14
+ cyan: "#4cb2d7",
15
+ green: "#87c54e",
16
+ orange: "#e5822f",
17
+ pink: "#f480ff",
18
+ purple: "#b860db",
19
+ red: "#F14746",
20
+ white: "#ffffff",
21
+ yellow: "#d3ba57"
22
+ };
23
+
24
+ // src/logger.ts
25
+ var Logger = class {
26
+ static {
27
+ __name(this, "Logger");
28
+ }
29
+ #options = {
30
+ logToStdout: true,
31
+ timezone: "UTC"
32
+ };
33
+ /**
34
+ * Instantiate a new logger
35
+ * @param options Logger config
36
+ */
37
+ constructor(options) {
38
+ this.#options = { ...this.#options, ...options };
39
+ }
40
+ #color(input, hex) {
41
+ return `\x1B[38;2;${parseInt(hex.slice(1, 3), 16)};${parseInt(hex.slice(3, 5), 16)};${parseInt(hex.slice(5, 7), 16)}m${input}\x1B[0m`;
42
+ }
43
+ #getDate(date, timezone = "UTC") {
44
+ if (timezone === "UTC") {
45
+ return date;
46
+ }
47
+ const match = timezone.match(/^UTC([+-]\d{1,2})$/);
48
+ if (!match || !match[1]) {
49
+ return date;
50
+ }
51
+ return new Date(
52
+ date.getTime() + date.getTimezoneOffset() * 6e4 + parseInt(match[1], 10) * 36e5
53
+ );
54
+ }
55
+ #write(options) {
56
+ const now = this.#getDate(/* @__PURE__ */ new Date(), this.#options.timezone);
57
+ const time = `${now.getHours().toString().padStart(2, "0")}:${now.getMinutes().toString().padStart(2, "0")}:${now.getSeconds().toString().padStart(2, "0")}`;
58
+ const line = `[${time} ${this.#options.timezone}] [${options.level.toUpperCase()}] ${options.message.trim()}`;
59
+ if (this.#options.logsPath) {
60
+ const fileName = `${now.getDate().toString().padStart(2, "0")}-${(now.getMonth() + 1).toString().padStart(2, "0")}-${now.getFullYear()}.log`;
61
+ fs.mkdirSync(this.#options.logsPath, { recursive: true });
62
+ fs.appendFileSync(
63
+ path.join(this.#options.logsPath, fileName),
64
+ line + "\n"
65
+ );
66
+ }
67
+ if (this.#options.logToStdout) {
68
+ if (options.hex || options.color) {
69
+ const hex = options.hex ? options.hex.startsWith("#") ? options.hex : `#${options.hex}` : colors[options.color];
70
+ console.log(this.#color(line, hex));
71
+ } else {
72
+ console.log(line);
73
+ }
74
+ }
75
+ }
76
+ /**
77
+ * Update the logger's options
78
+ * @param options New config
79
+ */
80
+ set(options = {}) {
81
+ this.#options = { ...this.#options, ...options };
82
+ }
83
+ /**
84
+ * Info log
85
+ * Green text, INFO level
86
+ * @param message Log message
87
+ * @param options Optional log options
88
+ * @returns
89
+ */
90
+ info(message, options) {
91
+ this.#write({
92
+ level: "info",
93
+ color: "green",
94
+ message,
95
+ ...options
96
+ });
97
+ return this;
98
+ }
99
+ /**
100
+ * Warning log
101
+ * Orange text, WARN level
102
+ * @param message Log message
103
+ * @param options Optional log options
104
+ * @returns
105
+ */
106
+ warn(message, options) {
107
+ this.#write({
108
+ level: "warn",
109
+ message,
110
+ color: "orange",
111
+ ...options
112
+ });
113
+ return this;
114
+ }
115
+ /**
116
+ * Error log
117
+ * Red text, ERROR level
118
+ * @param message Log message
119
+ * @param options Optional log options
120
+ * @returns
121
+ */
122
+ error(message, options) {
123
+ this.#write({
124
+ level: "error",
125
+ message,
126
+ color: "red",
127
+ ...options
128
+ });
129
+ return this;
130
+ }
131
+ /**
132
+ * Custom logs
133
+ * @param message Log message
134
+ * @param options Log options
135
+ */
136
+ log(message, options) {
137
+ if (!message) {
138
+ throw new Error("Logging requires a message");
139
+ }
140
+ this.#write({
141
+ ...options,
142
+ message,
143
+ level: options?.level ?? "log"
144
+ });
145
+ return this;
146
+ }
147
+ };
148
+ export {
149
+ Logger
150
+ };
package/package.json CHANGED
@@ -1,21 +1,40 @@
1
1
  {
2
2
  "name": "@wlix/logger",
3
- "version": "1.0.3",
4
- "description": "A simple logger.",
5
- "main": "index.js",
6
- "types": "index.d.ts",
7
- "private": false,
3
+ "description": "Tiny file-based logging for Node.js projects",
4
+ "version": "2.0.0",
5
+ "author": {
6
+ "name": "e60m5ss",
7
+ "url": "https://github.com/e60m5ss"
8
+ },
9
+ "main": "./dist/index.js",
10
+ "module": "./dist/index.mjs",
11
+ "types": "./dist/index.d.ts",
8
12
  "files": [
9
- "index.js",
10
- "index.d.ts",
13
+ "dist",
14
+ "LICENSE",
15
+ "package.json",
11
16
  "README.md"
12
17
  ],
13
- "publishConfig": {
14
- "access": "public"
18
+ "prettier": {
19
+ "filepath": "src/**/*.ts",
20
+ "jsxSingleQuote": false,
21
+ "printWidth": 85,
22
+ "semi": true,
23
+ "singleQuote": false,
24
+ "tabWidth": 4,
25
+ "trailingComma": "es5",
26
+ "useTabs": false
27
+ },
28
+ "devDependencies": {
29
+ "@types/node": "^25.1.0",
30
+ "prettier": "^3.8.1",
31
+ "tsup": "^8.5.1",
32
+ "typescript": "^5.9.3"
15
33
  },
16
- "author": "wlix",
17
- "license": "MIT",
18
34
  "scripts": {
19
- "test": "echo \"Error: no test specified\" && exit 1"
35
+ "build": "tsup",
36
+ "format": "prettier ./src --write --ignore-path=.prettierignore",
37
+ "lint": "tsc --noEmit; prettier ./src --check --ignore-path=.prettierignore",
38
+ "prepublish": "tsup"
20
39
  }
21
40
  }
package/index.d.ts DELETED
@@ -1,32 +0,0 @@
1
- export type Timezone = "UTC" | `UTC${"" | "+" | "-"}${number}`;
2
- export interface LoggerConfig {
3
- /**
4
- * Path of the directory with log files.
5
- * @default "./logs"
6
- */
7
- logsPath?: string;
8
-
9
- /**
10
- * Whether to log to stdout.
11
- * @default true
12
- */
13
- logToStdout?: boolean;
14
-
15
- /**
16
- * UTC, or UTC offsets only.
17
- * @example "UTC"
18
- * @example "UTC-6"
19
- * @example "UTC+7"
20
- * @default "UTC"
21
- */
22
- timezone?: Timezone;
23
- }
24
-
25
- /**
26
- * Creates a logger function.
27
- * @param config Optional logger configuration.
28
- * @returns A function to log messages: log(type, message)
29
- */
30
- export declare function createLogger(
31
- config?: LoggerConfig
32
- ): (type: "info" | "warn" | "error", message: string) => void;
package/index.js DELETED
@@ -1,76 +0,0 @@
1
- const { existsSync, mkdirSync, appendFileSync } = require("fs");
2
- const { join } = require("path");
3
-
4
- /**
5
- * @typedef {"UTC" | `UTC${"" | "+" | "-"}${number}`} Timezone
6
- * @typedef {Object} LoggerConfig
7
- * @property {string} [logsPath] Path of the directory with log files. Default: "./logs"
8
- * @property {boolean} [logToStdout] Whether to log to stdout. Default: true
9
- * @property {Timezone} [timezone] UTC, or UTC offsets only. Default: "UTC"
10
- */
11
-
12
- /**
13
- * Creates a logger function.
14
- * @param {LoggerConfig} config Optional logger configuration.
15
- * @returns {(type: "info" | "warn" | "error", message: string) => void} Function to log messages
16
- */
17
- function createLogger(config = {}) {
18
- const logsPath = config.logsPath ?? "./logs";
19
- const logToStdout = config.logToStdout ?? true;
20
- const timezone = config.timezone ?? "UTC";
21
-
22
- if (!existsSync(logsPath)) {
23
- mkdirSync(logsPath, { recursive: true });
24
- }
25
-
26
- /**
27
- * Returns a Date object adjusted for the given timezone.
28
- * @param {Date} date
29
- * @param {Timezone} tz
30
- * @returns {Date}
31
- */
32
- function getOffsetDate(date, tz) {
33
- if (tz === "UTC") return date;
34
-
35
- const match = tz.match(/^UTC([+-]\d{1,2})$/);
36
- if (!match) return date;
37
-
38
- const offsetHours = parseInt(match[1], 10);
39
- const utc = date.getTime() + date.getTimezoneOffset() * 60000;
40
- return new Date(utc + offsetHours * 3600000);
41
- }
42
-
43
- /**
44
- * Logs a message to a file and optionally to stdout.
45
- * @param {"info" | "warn" | "error"} type
46
- * @param {string} message
47
- */
48
- function log(type, message) {
49
- const now = getOffsetDate(new Date(), timezone);
50
-
51
- const fileName = [
52
- String(now.getDate()).padStart(2, "0"),
53
- String(now.getMonth() + 1).padStart(2, "0"),
54
- now.getFullYear(),
55
- ].join("-");
56
-
57
- const time = [
58
- String(now.getHours()).padStart(2, "0"),
59
- String(now.getMinutes()).padStart(2, "0"),
60
- String(now.getSeconds()).padStart(2, "0"),
61
- ].join(":");
62
-
63
- const line = `[${time} ${timezone}] [${type.toUpperCase()}] ${message}\n`;
64
- const filePath = join(logsPath, `${fileName}.log`);
65
-
66
- appendFileSync(filePath, line);
67
-
68
- if (logToStdout) {
69
- console.log(line.trim());
70
- }
71
- }
72
-
73
- return log;
74
- }
75
-
76
- module.exports = { createLogger };