@twin.org/logging-connector-file 0.9.1-next.5
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 +201 -0
- package/README.md +23 -0
- package/dist/es/fileLoggingConnector.js +321 -0
- package/dist/es/fileLoggingConnector.js.map +1 -0
- package/dist/es/index.js +6 -0
- package/dist/es/index.js.map +1 -0
- package/dist/es/models/IFileLoggingConnectorConfig.js +2 -0
- package/dist/es/models/IFileLoggingConnectorConfig.js.map +1 -0
- package/dist/es/models/IFileLoggingConnectorConstructorOptions.js +2 -0
- package/dist/es/models/IFileLoggingConnectorConstructorOptions.js.map +1 -0
- package/dist/types/fileLoggingConnector.d.ts +72 -0
- package/dist/types/index.d.ts +3 -0
- package/dist/types/models/IFileLoggingConnectorConfig.d.ts +35 -0
- package/dist/types/models/IFileLoggingConnectorConstructorOptions.d.ts +10 -0
- package/docs/changelog.md +19 -0
- package/docs/examples.md +137 -0
- package/docs/reference/classes/FileLoggingConnector.md +173 -0
- package/docs/reference/index.md +10 -0
- package/docs/reference/interfaces/IFileLoggingConnectorConfig.md +83 -0
- package/docs/reference/interfaces/IFileLoggingConnectorConstructorOptions.md +11 -0
- package/locales/.validate-ignore +2 -0
- package/locales/en.json +7 -0
- package/package.json +55 -0
package/LICENSE
ADDED
|
@@ -0,0 +1,201 @@
|
|
|
1
|
+
Apache License
|
|
2
|
+
Version 2.0, January 2004
|
|
3
|
+
http://www.apache.org/licenses/
|
|
4
|
+
|
|
5
|
+
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
|
|
6
|
+
|
|
7
|
+
1. Definitions.
|
|
8
|
+
|
|
9
|
+
"License" shall mean the terms and conditions for use, reproduction,
|
|
10
|
+
and distribution as defined by Sections 1 through 9 of this document.
|
|
11
|
+
|
|
12
|
+
"Licensor" shall mean the copyright owner or entity authorized by
|
|
13
|
+
the copyright owner that is granting the License.
|
|
14
|
+
|
|
15
|
+
"Legal Entity" shall mean the union of the acting entity and all
|
|
16
|
+
other entities that control, are controlled by, or are under common
|
|
17
|
+
control with that entity. For the purposes of this definition,
|
|
18
|
+
"control" means (i) the power, direct or indirect, to cause the
|
|
19
|
+
direction or management of such entity, whether by contract or
|
|
20
|
+
otherwise, or (ii) ownership of fifty percent (50%) or more of the
|
|
21
|
+
outstanding shares, or (iii) beneficial ownership of such entity.
|
|
22
|
+
|
|
23
|
+
"You" (or "Your") shall mean an individual or Legal Entity
|
|
24
|
+
exercising permissions granted by this License.
|
|
25
|
+
|
|
26
|
+
"Source" form shall mean the preferred form for making modifications,
|
|
27
|
+
including but not limited to software source code, documentation
|
|
28
|
+
source, and configuration files.
|
|
29
|
+
|
|
30
|
+
"Object" form shall mean any form resulting from mechanical
|
|
31
|
+
transformation or translation of a Source form, including but
|
|
32
|
+
not limited to compiled object code, generated documentation,
|
|
33
|
+
and conversions to other media types.
|
|
34
|
+
|
|
35
|
+
"Work" shall mean the work of authorship, whether in Source or
|
|
36
|
+
Object form, made available under the License, as indicated by a
|
|
37
|
+
copyright notice that is included in or attached to the work
|
|
38
|
+
(an example is provided in the Appendix below).
|
|
39
|
+
|
|
40
|
+
"Derivative Works" shall mean any work, whether in Source or Object
|
|
41
|
+
form, that is based on (or derived from) the Work and for which the
|
|
42
|
+
editorial revisions, annotations, elaborations, or other modifications
|
|
43
|
+
represent, as a whole, an original work of authorship. For the purposes
|
|
44
|
+
of this License, Derivative Works shall not include works that remain
|
|
45
|
+
separable from, or merely link (or bind by name) to the interfaces of,
|
|
46
|
+
the Work and Derivative Works thereof.
|
|
47
|
+
|
|
48
|
+
"Contribution" shall mean any work of authorship, including
|
|
49
|
+
the original version of the Work and any modifications or additions
|
|
50
|
+
to that Work or Derivative Works thereof, that is intentionally
|
|
51
|
+
submitted to Licensor for inclusion in the Work by the copyright owner
|
|
52
|
+
or by an individual or Legal Entity authorized to submit on behalf of
|
|
53
|
+
the copyright owner. For the purposes of this definition, "submitted"
|
|
54
|
+
means any form of electronic, verbal, or written communication sent
|
|
55
|
+
to the Licensor or its representatives, including but not limited to
|
|
56
|
+
communication on electronic mailing lists, source code control systems,
|
|
57
|
+
and issue tracking systems that are managed by, or on behalf of, the
|
|
58
|
+
Licensor for the purpose of discussing and improving the Work, but
|
|
59
|
+
excluding communication that is conspicuously marked or otherwise
|
|
60
|
+
designated in writing by the copyright owner as "Not a Contribution."
|
|
61
|
+
|
|
62
|
+
"Contributor" shall mean Licensor and any individual or Legal Entity
|
|
63
|
+
on behalf of whom a Contribution has been received by Licensor and
|
|
64
|
+
subsequently incorporated within the Work.
|
|
65
|
+
|
|
66
|
+
2. Grant of Copyright License. Subject to the terms and conditions of
|
|
67
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
68
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
69
|
+
copyright license to reproduce, prepare Derivative Works of,
|
|
70
|
+
publicly display, publicly perform, sublicense, and distribute the
|
|
71
|
+
Work and such Derivative Works in Source or Object form.
|
|
72
|
+
|
|
73
|
+
3. Grant of Patent License. Subject to the terms and conditions of
|
|
74
|
+
this License, each Contributor hereby grants to You a perpetual,
|
|
75
|
+
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
|
|
76
|
+
(except as stated in this section) patent license to make, have made,
|
|
77
|
+
use, offer to sell, sell, import, and otherwise transfer the Work,
|
|
78
|
+
where such license applies only to those patent claims licensable
|
|
79
|
+
by such Contributor that are necessarily infringed by their
|
|
80
|
+
Contribution(s) alone or by combination of their Contribution(s)
|
|
81
|
+
with the Work to which such Contribution(s) was submitted. If You
|
|
82
|
+
institute patent litigation against any entity (including a
|
|
83
|
+
cross-claim or counterclaim in a lawsuit) alleging that the Work
|
|
84
|
+
or a Contribution incorporated within the Work constitutes direct
|
|
85
|
+
or contributory patent infringement, then any patent licenses
|
|
86
|
+
granted to You under this License for that Work shall terminate
|
|
87
|
+
as of the date such litigation is filed.
|
|
88
|
+
|
|
89
|
+
4. Redistribution. You may reproduce and distribute copies of the
|
|
90
|
+
Work or Derivative Works thereof in any medium, with or without
|
|
91
|
+
modifications, and in Source or Object form, provided that You
|
|
92
|
+
meet the following conditions:
|
|
93
|
+
|
|
94
|
+
(a) You must give any other recipients of the Work or
|
|
95
|
+
Derivative Works a copy of this License; and
|
|
96
|
+
|
|
97
|
+
(b) You must cause any modified files to carry prominent notices
|
|
98
|
+
stating that You changed the files; and
|
|
99
|
+
|
|
100
|
+
(c) You must retain, in the Source form of any Derivative Works
|
|
101
|
+
that You distribute, all copyright, patent, trademark, and
|
|
102
|
+
attribution notices from the Source form of the Work,
|
|
103
|
+
excluding those notices that do not pertain to any part of
|
|
104
|
+
the Derivative Works; and
|
|
105
|
+
|
|
106
|
+
(d) If the Work includes a "NOTICE" text file as part of its
|
|
107
|
+
distribution, then any Derivative Works that You distribute must
|
|
108
|
+
include a readable copy of the attribution notices contained
|
|
109
|
+
within such NOTICE file, excluding those notices that do not
|
|
110
|
+
pertain to any part of the Derivative Works, in at least one
|
|
111
|
+
of the following places: within a NOTICE text file distributed
|
|
112
|
+
as part of the Derivative Works; within the Source form or
|
|
113
|
+
documentation, if provided along with the Derivative Works; or,
|
|
114
|
+
within a display generated by the Derivative Works, if and
|
|
115
|
+
wherever such third-party notices normally appear. The contents
|
|
116
|
+
of the NOTICE file are for informational purposes only and
|
|
117
|
+
do not modify the License. You may add Your own attribution
|
|
118
|
+
notices within Derivative Works that You distribute, alongside
|
|
119
|
+
or as an addendum to the NOTICE text from the Work, provided
|
|
120
|
+
that such additional attribution notices cannot be construed
|
|
121
|
+
as modifying the License.
|
|
122
|
+
|
|
123
|
+
You may add Your own copyright statement to Your modifications and
|
|
124
|
+
may provide additional or different license terms and conditions
|
|
125
|
+
for use, reproduction, or distribution of Your modifications, or
|
|
126
|
+
for any such Derivative Works as a whole, provided Your use,
|
|
127
|
+
reproduction, and distribution of the Work otherwise complies with
|
|
128
|
+
the conditions stated in this License.
|
|
129
|
+
|
|
130
|
+
5. Submission of Contributions. Unless You explicitly state otherwise,
|
|
131
|
+
any Contribution intentionally submitted for inclusion in the Work
|
|
132
|
+
by You to the Licensor shall be under the terms and conditions of
|
|
133
|
+
this License, without any additional terms or conditions.
|
|
134
|
+
Notwithstanding the above, nothing herein shall supersede or modify
|
|
135
|
+
the terms of any separate license agreement you may have executed
|
|
136
|
+
with Licensor regarding such Contributions.
|
|
137
|
+
|
|
138
|
+
6. Trademarks. This License does not grant permission to use the trade
|
|
139
|
+
names, trademarks, service marks, or product names of the Licensor,
|
|
140
|
+
except as required for reasonable and customary use in describing the
|
|
141
|
+
origin of the Work and reproducing the content of the NOTICE file.
|
|
142
|
+
|
|
143
|
+
7. Disclaimer of Warranty. Unless required by applicable law or
|
|
144
|
+
agreed to in writing, Licensor provides the Work (and each
|
|
145
|
+
Contributor provides its Contributions) on an "AS IS" BASIS,
|
|
146
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
|
|
147
|
+
implied, including, without limitation, any warranties or conditions
|
|
148
|
+
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
|
|
149
|
+
PARTICULAR PURPOSE. You are solely responsible for determining the
|
|
150
|
+
appropriateness of using or redistributing the Work and assume any
|
|
151
|
+
risks associated with Your exercise of permissions under this License.
|
|
152
|
+
|
|
153
|
+
8. Limitation of Liability. In no event and under no legal theory,
|
|
154
|
+
whether in tort (including negligence), contract, or otherwise,
|
|
155
|
+
unless required by applicable law (such as deliberate and grossly
|
|
156
|
+
negligent acts) or agreed to in writing, shall any Contributor be
|
|
157
|
+
liable to You for damages, including any direct, indirect, special,
|
|
158
|
+
incidental, or consequential damages of any character arising as a
|
|
159
|
+
result of this License or out of the use or inability to use the
|
|
160
|
+
Work (including but not limited to damages for loss of goodwill,
|
|
161
|
+
work stoppage, computer failure or malfunction, or any and all
|
|
162
|
+
other commercial damages or losses), even if such Contributor
|
|
163
|
+
has been advised of the possibility of such damages.
|
|
164
|
+
|
|
165
|
+
9. Accepting Warranty or Additional Liability. While redistributing
|
|
166
|
+
the Work or Derivative Works thereof, You may choose to offer,
|
|
167
|
+
and charge a fee for, acceptance of support, warranty, indemnity,
|
|
168
|
+
or other liability obligations and/or rights consistent with this
|
|
169
|
+
License. However, in accepting such obligations, You may act only
|
|
170
|
+
on Your own behalf and on Your sole responsibility, not on behalf
|
|
171
|
+
of any other Contributor, and only if You agree to indemnify,
|
|
172
|
+
defend, and hold each Contributor harmless for any liability
|
|
173
|
+
incurred by, or claims asserted against, such Contributor by reason
|
|
174
|
+
of your accepting any such warranty or additional liability.
|
|
175
|
+
|
|
176
|
+
END OF TERMS AND CONDITIONS
|
|
177
|
+
|
|
178
|
+
APPENDIX: How to apply the Apache License to your work.
|
|
179
|
+
|
|
180
|
+
To apply the Apache License to your work, attach the following
|
|
181
|
+
boilerplate notice, with the fields enclosed by brackets "[]"
|
|
182
|
+
replaced with your own identifying information. (Don't include
|
|
183
|
+
the brackets!) The text should be enclosed in the appropriate
|
|
184
|
+
comment syntax for the file format. We also recommend that a
|
|
185
|
+
file or class name and description of purpose be included on the
|
|
186
|
+
same "printed page" as the copyright notice for easier
|
|
187
|
+
identification within third-party archives.
|
|
188
|
+
|
|
189
|
+
Copyright 2024 IOTA Stiftung.
|
|
190
|
+
|
|
191
|
+
Licensed under the Apache License, Version 2.0 (the "License");
|
|
192
|
+
you may not use this file except in compliance with the License.
|
|
193
|
+
You may obtain a copy of the License at
|
|
194
|
+
|
|
195
|
+
http://www.apache.org/licenses/LICENSE-2.0
|
|
196
|
+
|
|
197
|
+
Unless required by applicable law or agreed to in writing, software
|
|
198
|
+
distributed under the License is distributed on an "AS IS" BASIS,
|
|
199
|
+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
|
|
200
|
+
See the License for the specific language governing permissions and
|
|
201
|
+
limitations under the License.
|
package/README.md
ADDED
|
@@ -0,0 +1,23 @@
|
|
|
1
|
+
# TWIN Logging Connector File
|
|
2
|
+
|
|
3
|
+
File connector for persisting TWIN log events to size-limited files on disk with rotation and retention.
|
|
4
|
+
|
|
5
|
+
Entries are written as newline delimited JSON through a persistent file handle. The connector assumes a single writer per file: one owner (process) should be responsible for a given log file, as it does not coordinate rotation across separate processes.
|
|
6
|
+
|
|
7
|
+
## Installation
|
|
8
|
+
|
|
9
|
+
```shell
|
|
10
|
+
npm install @twin.org/logging-connector-file
|
|
11
|
+
```
|
|
12
|
+
|
|
13
|
+
## Examples
|
|
14
|
+
|
|
15
|
+
Usage of the APIs is shown in the examples [docs/examples.md](docs/examples.md)
|
|
16
|
+
|
|
17
|
+
## Reference
|
|
18
|
+
|
|
19
|
+
Detailed reference documentation for the API can be found in [docs/reference/index.md](docs/reference/index.md)
|
|
20
|
+
|
|
21
|
+
## Changelog
|
|
22
|
+
|
|
23
|
+
The changes between each version can be found in [docs/changelog.md](docs/changelog.md)
|
|
@@ -0,0 +1,321 @@
|
|
|
1
|
+
// Copyright 2026 IOTA Stiftung.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0.
|
|
3
|
+
import { mkdir, open, rename, rm, stat } from "node:fs/promises";
|
|
4
|
+
import path from "node:path";
|
|
5
|
+
import { BaseError, Coerce, GeneralError, Guards, Is, Mutex } from "@twin.org/core";
|
|
6
|
+
import { LogLevel } from "@twin.org/logging-models";
|
|
7
|
+
/**
|
|
8
|
+
* Class for performing logging operations to size-limited files on disk.
|
|
9
|
+
*
|
|
10
|
+
* Entries are appended to an active file as newline delimited JSON through a file handle
|
|
11
|
+
* that is opened once and kept open, avoiding an open and close on every write. Each entry
|
|
12
|
+
* is written straight through to the file so it is durable as soon as log() resolves.
|
|
13
|
+
* When the active file would exceed the configured size limit it is rotated: the active
|
|
14
|
+
* file becomes the newest numbered file and any file beyond the retained file limit is
|
|
15
|
+
* removed, keeping total on-disk usage predictable.
|
|
16
|
+
*
|
|
17
|
+
* The connector assumes a single writer per file: one instance should own a given log file.
|
|
18
|
+
* Its own writes and rotations are serialised with a mutex, but it does not coordinate with
|
|
19
|
+
* other processes or external tools rotating the same file.
|
|
20
|
+
*/
|
|
21
|
+
export class FileLoggingConnector {
|
|
22
|
+
/**
|
|
23
|
+
* The namespace for the logging connector.
|
|
24
|
+
*/
|
|
25
|
+
static NAMESPACE = "file";
|
|
26
|
+
/**
|
|
27
|
+
* Runtime name for the class.
|
|
28
|
+
*/
|
|
29
|
+
static CLASS_NAME = "FileLoggingConnector";
|
|
30
|
+
/**
|
|
31
|
+
* Default name for the active log file.
|
|
32
|
+
*/
|
|
33
|
+
static DEFAULT_FILENAME = "app.log";
|
|
34
|
+
/**
|
|
35
|
+
* Default maximum size in bytes of the active log file before rotation (10 MB).
|
|
36
|
+
*/
|
|
37
|
+
static DEFAULT_MAX_FILE_SIZE_BYTES = 10 * 1024 * 1024;
|
|
38
|
+
/**
|
|
39
|
+
* Minimum size in bytes that can be configured for the active log file before rotation (100 KB).
|
|
40
|
+
*/
|
|
41
|
+
static MIN_MAX_FILE_SIZE_BYTES = 100 * 1024;
|
|
42
|
+
/**
|
|
43
|
+
* Default number of rotated log files to retain.
|
|
44
|
+
*/
|
|
45
|
+
static DEFAULT_MAX_RETAINED_FILES = 5;
|
|
46
|
+
/**
|
|
47
|
+
* The log levels to capture, will default to all.
|
|
48
|
+
* @internal
|
|
49
|
+
*/
|
|
50
|
+
_levels;
|
|
51
|
+
/**
|
|
52
|
+
* The directory the log files are written to.
|
|
53
|
+
* @internal
|
|
54
|
+
*/
|
|
55
|
+
_directory;
|
|
56
|
+
/**
|
|
57
|
+
* The name of the active log file.
|
|
58
|
+
* @internal
|
|
59
|
+
*/
|
|
60
|
+
_filename;
|
|
61
|
+
/**
|
|
62
|
+
* Rotate the active file when it reaches this size in bytes; 0 disables size rotation.
|
|
63
|
+
* @internal
|
|
64
|
+
*/
|
|
65
|
+
_maxFileSizeBytes;
|
|
66
|
+
/**
|
|
67
|
+
* Number of rotated files to retain; 0 retains none.
|
|
68
|
+
* @internal
|
|
69
|
+
*/
|
|
70
|
+
_maxRetainedFiles;
|
|
71
|
+
/**
|
|
72
|
+
* Timeout in milliseconds passed to Mutex.lock calls.
|
|
73
|
+
* @internal
|
|
74
|
+
*/
|
|
75
|
+
_mutexTimeoutMs;
|
|
76
|
+
/**
|
|
77
|
+
* Key used to serialize concurrent writes and rotations via Mutex, the resolved active path.
|
|
78
|
+
* @internal
|
|
79
|
+
*/
|
|
80
|
+
_mutexKey;
|
|
81
|
+
/**
|
|
82
|
+
* The tracked size in bytes of the active file, avoiding a stat on every write.
|
|
83
|
+
* @internal
|
|
84
|
+
*/
|
|
85
|
+
_currentSize;
|
|
86
|
+
/**
|
|
87
|
+
* The open handle for the active file, present only while the connector is open.
|
|
88
|
+
* @internal
|
|
89
|
+
*/
|
|
90
|
+
_handle;
|
|
91
|
+
/**
|
|
92
|
+
* Create a new instance of FileLoggingConnector.
|
|
93
|
+
* @param options The options for the logging connector.
|
|
94
|
+
* @throws GeneralError if maxFileSizeBytes is a positive value below the minimum.
|
|
95
|
+
*/
|
|
96
|
+
constructor(options) {
|
|
97
|
+
Guards.object(FileLoggingConnector.CLASS_NAME, "options", options);
|
|
98
|
+
Guards.object(FileLoggingConnector.CLASS_NAME, "options.config", options.config);
|
|
99
|
+
Guards.stringValue(FileLoggingConnector.CLASS_NAME, "options.config.directory", options.config.directory);
|
|
100
|
+
this._levels = options.config.levels ?? Object.values(LogLevel);
|
|
101
|
+
this._directory = options.config.directory;
|
|
102
|
+
this._filename = Is.stringValue(options.config.filename)
|
|
103
|
+
? options.config.filename
|
|
104
|
+
: FileLoggingConnector.DEFAULT_FILENAME;
|
|
105
|
+
const cfgMaxFileSizeBytes = Coerce.integer(options.config.maxFileSizeBytes) ??
|
|
106
|
+
FileLoggingConnector.DEFAULT_MAX_FILE_SIZE_BYTES;
|
|
107
|
+
if (cfgMaxFileSizeBytes > 0 &&
|
|
108
|
+
cfgMaxFileSizeBytes < FileLoggingConnector.MIN_MAX_FILE_SIZE_BYTES) {
|
|
109
|
+
throw new GeneralError(FileLoggingConnector.CLASS_NAME, "maxFileSizeTooSmall", {
|
|
110
|
+
maxFileSizeBytes: cfgMaxFileSizeBytes,
|
|
111
|
+
minimum: FileLoggingConnector.MIN_MAX_FILE_SIZE_BYTES
|
|
112
|
+
});
|
|
113
|
+
}
|
|
114
|
+
this._maxFileSizeBytes = cfgMaxFileSizeBytes <= 0 ? 0 : cfgMaxFileSizeBytes;
|
|
115
|
+
const cfgMaxRetainedFiles = Coerce.integer(options.config.maxRetainedFiles) ??
|
|
116
|
+
FileLoggingConnector.DEFAULT_MAX_RETAINED_FILES;
|
|
117
|
+
this._maxRetainedFiles = cfgMaxRetainedFiles > 0 ? cfgMaxRetainedFiles : 0;
|
|
118
|
+
this._mutexTimeoutMs = Coerce.integer(options.config.mutexTimeoutMs);
|
|
119
|
+
this._mutexKey = path.resolve(this._directory, this._filename);
|
|
120
|
+
this._currentSize = 0;
|
|
121
|
+
}
|
|
122
|
+
/**
|
|
123
|
+
* Returns the class name of the component.
|
|
124
|
+
* @returns The class name of the component.
|
|
125
|
+
*/
|
|
126
|
+
className() {
|
|
127
|
+
return FileLoggingConnector.CLASS_NAME;
|
|
128
|
+
}
|
|
129
|
+
/**
|
|
130
|
+
* Start the connector; ensures the target directory exists and opens the file handle.
|
|
131
|
+
* @returns A promise that resolves when the connector is ready to accept log entries.
|
|
132
|
+
*/
|
|
133
|
+
async start() {
|
|
134
|
+
const locked = await Mutex.lock(this._mutexKey, {
|
|
135
|
+
throwOnTimeout: true,
|
|
136
|
+
timeoutMs: this._mutexTimeoutMs
|
|
137
|
+
});
|
|
138
|
+
if (locked) {
|
|
139
|
+
try {
|
|
140
|
+
await this.ensureOpen();
|
|
141
|
+
}
|
|
142
|
+
finally {
|
|
143
|
+
Mutex.unlock(this._mutexKey);
|
|
144
|
+
}
|
|
145
|
+
}
|
|
146
|
+
}
|
|
147
|
+
/**
|
|
148
|
+
* Stop the connector; closes the file handle, releasing the descriptor.
|
|
149
|
+
* Calling stop() on a connector that has not been opened is a no-op.
|
|
150
|
+
* @returns A promise that resolves when the handle has been closed.
|
|
151
|
+
*/
|
|
152
|
+
async stop() {
|
|
153
|
+
const locked = await Mutex.lock(this._mutexKey, {
|
|
154
|
+
throwOnTimeout: true,
|
|
155
|
+
timeoutMs: this._mutexTimeoutMs
|
|
156
|
+
});
|
|
157
|
+
if (locked) {
|
|
158
|
+
try {
|
|
159
|
+
await this.closeHandle();
|
|
160
|
+
}
|
|
161
|
+
finally {
|
|
162
|
+
Mutex.unlock(this._mutexKey);
|
|
163
|
+
}
|
|
164
|
+
}
|
|
165
|
+
}
|
|
166
|
+
/**
|
|
167
|
+
* Log an entry to the connector.
|
|
168
|
+
* The entry is appended to the active file as a single newline delimited JSON record;
|
|
169
|
+
* when the active file exceeds the configured size limit it is rotated first.
|
|
170
|
+
* @param logEntry The entry to log.
|
|
171
|
+
* @returns A promise that resolves when the entry has been written to disk.
|
|
172
|
+
*/
|
|
173
|
+
async log(logEntry) {
|
|
174
|
+
Guards.object(FileLoggingConnector.CLASS_NAME, "logEntry", logEntry);
|
|
175
|
+
if (!this._levels.includes(logEntry.level)) {
|
|
176
|
+
return;
|
|
177
|
+
}
|
|
178
|
+
const line = `${JSON.stringify(this.toRecord(logEntry))}\n`;
|
|
179
|
+
const lineBytes = Buffer.byteLength(line, "utf8");
|
|
180
|
+
const locked = await Mutex.lock(this._mutexKey, {
|
|
181
|
+
throwOnTimeout: true,
|
|
182
|
+
timeoutMs: this._mutexTimeoutMs
|
|
183
|
+
});
|
|
184
|
+
if (locked) {
|
|
185
|
+
try {
|
|
186
|
+
await this.ensureOpen();
|
|
187
|
+
if (this._maxFileSizeBytes > 0 &&
|
|
188
|
+
this._currentSize > 0 &&
|
|
189
|
+
this._currentSize + lineBytes > this._maxFileSizeBytes) {
|
|
190
|
+
await this.rotate();
|
|
191
|
+
}
|
|
192
|
+
// Read after any rotation, which reopens the handle for the fresh active file.
|
|
193
|
+
const handle = this._handle;
|
|
194
|
+
if (!Is.empty(handle)) {
|
|
195
|
+
await handle.write(line, null, "utf8");
|
|
196
|
+
this._currentSize += lineBytes;
|
|
197
|
+
}
|
|
198
|
+
}
|
|
199
|
+
finally {
|
|
200
|
+
Mutex.unlock(this._mutexKey);
|
|
201
|
+
}
|
|
202
|
+
}
|
|
203
|
+
}
|
|
204
|
+
/**
|
|
205
|
+
* Build the plain record written to disk from a log entry, defaulting the timestamp to the
|
|
206
|
+
* current time as an ISO string and flattening any error into a serialisable form.
|
|
207
|
+
* @param logEntry The entry being logged.
|
|
208
|
+
* @returns The record to serialise as a single JSON line.
|
|
209
|
+
* @internal
|
|
210
|
+
*/
|
|
211
|
+
toRecord(logEntry) {
|
|
212
|
+
return {
|
|
213
|
+
level: logEntry.level,
|
|
214
|
+
source: logEntry.source,
|
|
215
|
+
timestamp: new Date(logEntry.ts ?? Date.now()).toISOString(),
|
|
216
|
+
message: logEntry.message,
|
|
217
|
+
data: logEntry.data,
|
|
218
|
+
error: Is.object(logEntry.error) ? BaseError.flatten(logEntry.error) : undefined
|
|
219
|
+
};
|
|
220
|
+
}
|
|
221
|
+
/**
|
|
222
|
+
* Ensure the target directory exists, the tracked size matches the active file on disk and
|
|
223
|
+
* the file handle is open.
|
|
224
|
+
* @returns A promise that resolves once the handle is open.
|
|
225
|
+
* @internal
|
|
226
|
+
*/
|
|
227
|
+
async ensureOpen() {
|
|
228
|
+
if (Is.empty(this._handle)) {
|
|
229
|
+
await mkdir(this._directory, { recursive: true });
|
|
230
|
+
this._currentSize = await this.fileSize(this.activePath());
|
|
231
|
+
this._handle = await open(this.activePath(), "a");
|
|
232
|
+
}
|
|
233
|
+
}
|
|
234
|
+
/**
|
|
235
|
+
* Close the active file handle if it is open.
|
|
236
|
+
* @returns A promise that resolves once the handle has been closed.
|
|
237
|
+
* @internal
|
|
238
|
+
*/
|
|
239
|
+
async closeHandle() {
|
|
240
|
+
const handle = this._handle;
|
|
241
|
+
if (!Is.empty(handle)) {
|
|
242
|
+
this._handle = undefined;
|
|
243
|
+
await handle.close();
|
|
244
|
+
}
|
|
245
|
+
}
|
|
246
|
+
/**
|
|
247
|
+
* Rotate the active file by closing the handle, shifting the numbered files up, discarding
|
|
248
|
+
* any beyond the retained file limit, then reopening a fresh active file. When no rotated
|
|
249
|
+
* files are retained the active file is removed.
|
|
250
|
+
* @returns A promise that resolves once rotation has completed.
|
|
251
|
+
* @internal
|
|
252
|
+
*/
|
|
253
|
+
async rotate() {
|
|
254
|
+
await this.closeHandle();
|
|
255
|
+
const active = this.activePath();
|
|
256
|
+
if (this._maxRetainedFiles <= 0) {
|
|
257
|
+
await rm(active, { force: true });
|
|
258
|
+
}
|
|
259
|
+
else {
|
|
260
|
+
await rm(this.rotatedPath(this._maxRetainedFiles), { force: true });
|
|
261
|
+
for (let index = this._maxRetainedFiles - 1; index >= 1; index--) {
|
|
262
|
+
const from = this.rotatedPath(index);
|
|
263
|
+
if (await this.fileExists(from)) {
|
|
264
|
+
await rename(from, this.rotatedPath(index + 1));
|
|
265
|
+
}
|
|
266
|
+
}
|
|
267
|
+
await rename(active, this.rotatedPath(1));
|
|
268
|
+
}
|
|
269
|
+
await this.ensureOpen();
|
|
270
|
+
this._currentSize = 0;
|
|
271
|
+
}
|
|
272
|
+
/**
|
|
273
|
+
* The path to the active log file.
|
|
274
|
+
* @returns The path to the active file.
|
|
275
|
+
* @internal
|
|
276
|
+
*/
|
|
277
|
+
activePath() {
|
|
278
|
+
return path.join(this._directory, this._filename);
|
|
279
|
+
}
|
|
280
|
+
/**
|
|
281
|
+
* The path to a numbered rotated log file.
|
|
282
|
+
* @param index The rotation index.
|
|
283
|
+
* @returns The path to the rotated file, inserting the index before the file extension.
|
|
284
|
+
* @internal
|
|
285
|
+
*/
|
|
286
|
+
rotatedPath(index) {
|
|
287
|
+
const parsed = path.parse(this._filename);
|
|
288
|
+
return path.join(this._directory, `${parsed.name}.${index}${parsed.ext}`);
|
|
289
|
+
}
|
|
290
|
+
/**
|
|
291
|
+
* Get the size in bytes of a file, returning 0 when it does not exist.
|
|
292
|
+
* @param filePath The path to the file.
|
|
293
|
+
* @returns The size of the file in bytes, or 0 if it does not exist.
|
|
294
|
+
* @internal
|
|
295
|
+
*/
|
|
296
|
+
async fileSize(filePath) {
|
|
297
|
+
try {
|
|
298
|
+
const stats = await stat(filePath);
|
|
299
|
+
return stats.size;
|
|
300
|
+
}
|
|
301
|
+
catch {
|
|
302
|
+
return 0;
|
|
303
|
+
}
|
|
304
|
+
}
|
|
305
|
+
/**
|
|
306
|
+
* Determine whether a file exists.
|
|
307
|
+
* @param filePath The path to the file.
|
|
308
|
+
* @returns True if the file exists.
|
|
309
|
+
* @internal
|
|
310
|
+
*/
|
|
311
|
+
async fileExists(filePath) {
|
|
312
|
+
try {
|
|
313
|
+
await stat(filePath);
|
|
314
|
+
return true;
|
|
315
|
+
}
|
|
316
|
+
catch {
|
|
317
|
+
return false;
|
|
318
|
+
}
|
|
319
|
+
}
|
|
320
|
+
}
|
|
321
|
+
//# sourceMappingURL=fileLoggingConnector.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"fileLoggingConnector.js","sourceRoot":"","sources":["../../src/fileLoggingConnector.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,OAAO,EAAmB,KAAK,EAAE,IAAI,EAAE,MAAM,EAAE,EAAE,EAAE,IAAI,EAAE,MAAM,kBAAkB,CAAC;AAClF,OAAO,IAAI,MAAM,WAAW,CAAC;AAC7B,OAAO,EAAE,SAAS,EAAE,MAAM,EAAE,YAAY,EAAE,MAAM,EAAe,EAAE,EAAE,KAAK,EAAE,MAAM,gBAAgB,CAAC;AACjG,OAAO,EAA0C,QAAQ,EAAE,MAAM,0BAA0B,CAAC;AAI5F;;;;;;;;;;;;;GAaG;AACH,MAAM,OAAO,oBAAoB;IAChC;;OAEG;IACI,MAAM,CAAU,SAAS,GAAW,MAAM,CAAC;IAElD;;OAEG;IACI,MAAM,CAAU,UAAU,0BAA0C;IAE3E;;OAEG;IACI,MAAM,CAAU,gBAAgB,GAA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ung.\n// SPDX-License-Identifier: Apache-2.0.\nimport { type FileHandle, mkdir, open, rename, rm, stat } from \"node:fs/promises\";\nimport path from \"node:path\";\nimport { BaseError, Coerce, GeneralError, Guards, type IError, Is, Mutex } from \"@twin.org/core\";\nimport { type ILogEntry, type ILoggingConnector, LogLevel } from \"@twin.org/logging-models\";\nimport { nameof } from \"@twin.org/nameof\";\nimport type { IFileLoggingConnectorConstructorOptions } from \"./models/IFileLoggingConnectorConstructorOptions.js\";\n\n/**\n * Class for performing logging operations to size-limited files on disk.\n *\n * Entries are appended to an active file as newline delimited JSON through a file handle\n * that is opened once and kept open, avoiding an open and close on every write. Each entry\n * is written straight through to the file so it is durable as soon as log() resolves.\n * When the active file would exceed the configured size limit it is rotated: the active\n * file becomes the newest numbered file and any file beyond the retained file limit is\n * removed, keeping total on-disk usage predictable.\n *\n * The connector assumes a single writer per file: one instance should own a given log file.\n * Its own writes and rotations are serialised with a mutex, but it does not coordinate with\n * other processes or external tools rotating the same file.\n */\nexport class FileLoggingConnector implements ILoggingConnector {\n\t/**\n\t * The namespace for the logging connector.\n\t */\n\tpublic static readonly NAMESPACE: string = \"file\";\n\n\t/**\n\t * Runtime name for the class.\n\t */\n\tpublic static readonly CLASS_NAME: string = nameof<FileLoggingConnector>();\n\n\t/**\n\t * Default name for the active log file.\n\t */\n\tpublic static readonly DEFAULT_FILENAME: string = \"app.log\";\n\n\t/**\n\t * Default maximum size in bytes of the active log file before rotation (10 MB).\n\t */\n\tpublic static readonly DEFAULT_MAX_FILE_SIZE_BYTES: number = 10 * 1024 * 1024;\n\n\t/**\n\t * Minimum size in bytes that can be configured for the active log file before rotation (100 KB).\n\t */\n\tpublic static readonly MIN_MAX_FILE_SIZE_BYTES: number = 100 * 1024;\n\n\t/**\n\t * Default number of rotated log files to retain.\n\t */\n\tpublic static readonly DEFAULT_MAX_RETAINED_FILES: number = 5;\n\n\t/**\n\t * The log levels to capture, will default to all.\n\t * @internal\n\t */\n\tprivate readonly _levels: LogLevel[];\n\n\t/**\n\t * The directory the log files are written to.\n\t * @internal\n\t */\n\tprivate readonly _directory: string;\n\n\t/**\n\t * The name of the active log file.\n\t * @internal\n\t */\n\tprivate readonly _filename: string;\n\n\t/**\n\t * Rotate the active file when it reaches this size in bytes; 0 disables size rotation.\n\t * @internal\n\t */\n\tprivate readonly _maxFileSizeBytes: number;\n\n\t/**\n\t * Number of rotated files to retain; 0 retains none.\n\t * @internal\n\t */\n\tprivate readonly _maxRetainedFiles: number;\n\n\t/**\n\t * Timeout in milliseconds passed to Mutex.lock calls.\n\t * @internal\n\t */\n\tprivate readonly _mutexTimeoutMs?: number;\n\n\t/**\n\t * Key used to serialize concurrent writes and rotations via Mutex, the resolved active path.\n\t * @internal\n\t */\n\tprivate readonly _mutexKey: string;\n\n\t/**\n\t * The tracked size in bytes of the active file, avoiding a stat on every write.\n\t * @internal\n\t */\n\tprivate _currentSize: number;\n\n\t/**\n\t * The open handle for the active file, present only while the connector is open.\n\t * @internal\n\t */\n\tprivate _handle?: FileHandle;\n\n\t/**\n\t * Create a new instance of FileLoggingConnector.\n\t * @param options The options for the logging connector.\n\t * @throws GeneralError if maxFileSizeBytes is a positive value below the minimum.\n\t */\n\tconstructor(options: IFileLoggingConnectorConstructorOptions) {\n\t\tGuards.object(FileLoggingConnector.CLASS_NAME, nameof(options), options);\n\t\tGuards.object(FileLoggingConnector.CLASS_NAME, nameof(options.config), options.config);\n\t\tGuards.stringValue(\n\t\t\tFileLoggingConnector.CLASS_NAME,\n\t\t\tnameof(options.config.directory),\n\t\t\toptions.config.directory\n\t\t);\n\n\t\tthis._levels = options.config.levels ?? Object.values(LogLevel);\n\t\tthis._directory = options.config.directory;\n\t\tthis._filename = Is.stringValue(options.config.filename)\n\t\t\t? options.config.filename\n\t\t\t: FileLoggingConnector.DEFAULT_FILENAME;\n\n\t\tconst cfgMaxFileSizeBytes =\n\t\t\tCoerce.integer(options.config.maxFileSizeBytes) ??\n\t\t\tFileLoggingConnector.DEFAULT_MAX_FILE_SIZE_BYTES;\n\t\tif (\n\t\t\tcfgMaxFileSizeBytes > 0 &&\n\t\t\tcfgMaxFileSizeBytes < FileLoggingConnector.MIN_MAX_FILE_SIZE_BYTES\n\t\t) {\n\t\t\tthrow new GeneralError(FileLoggingConnector.CLASS_NAME, \"maxFileSizeTooSmall\", {\n\t\t\t\tmaxFileSizeBytes: cfgMaxFileSizeBytes,\n\t\t\t\tminimum: FileLoggingConnector.MIN_MAX_FILE_SIZE_BYTES\n\t\t\t});\n\t\t}\n\t\tthis._maxFileSizeBytes = cfgMaxFileSizeBytes <= 0 ? 0 : cfgMaxFileSizeBytes;\n\n\t\tconst cfgMaxRetainedFiles =\n\t\t\tCoerce.integer(options.config.maxRetainedFiles) ??\n\t\t\tFileLoggingConnector.DEFAULT_MAX_RETAINED_FILES;\n\t\tthis._maxRetainedFiles = cfgMaxRetainedFiles > 0 ? cfgMaxRetainedFiles : 0;\n\n\t\tthis._mutexTimeoutMs = Coerce.integer(options.config.mutexTimeoutMs);\n\t\tthis._mutexKey = path.resolve(this._directory, this._filename);\n\t\tthis._currentSize = 0;\n\t}\n\n\t/**\n\t * Returns the class name of the component.\n\t * @returns The class name of the component.\n\t */\n\tpublic className(): string {\n\t\treturn FileLoggingConnector.CLASS_NAME;\n\t}\n\n\t/**\n\t * Start the connector; ensures the target directory exists and opens the file handle.\n\t * @returns A promise that resolves when the connector is ready to accept log entries.\n\t */\n\tpublic async start(): Promise<void> {\n\t\tconst locked = await Mutex.lock(this._mutexKey, {\n\t\t\tthrowOnTimeout: true,\n\t\t\ttimeoutMs: this._mutexTimeoutMs\n\t\t});\n\t\tif (locked) {\n\t\t\ttry {\n\t\t\t\tawait this.ensureOpen();\n\t\t\t} finally {\n\t\t\t\tMutex.unlock(this._mutexKey);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Stop the connector; closes the file handle, releasing the descriptor.\n\t * Calling stop() on a connector that has not been opened is a no-op.\n\t * @returns A promise that resolves when the handle has been closed.\n\t */\n\tpublic async stop(): Promise<void> {\n\t\tconst locked = await Mutex.lock(this._mutexKey, {\n\t\t\tthrowOnTimeout: true,\n\t\t\ttimeoutMs: this._mutexTimeoutMs\n\t\t});\n\t\tif (locked) {\n\t\t\ttry {\n\t\t\t\tawait this.closeHandle();\n\t\t\t} finally {\n\t\t\t\tMutex.unlock(this._mutexKey);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Log an entry to the connector.\n\t * The entry is appended to the active file as a single newline delimited JSON record;\n\t * when the active file exceeds the configured size limit it is rotated first.\n\t * @param logEntry The entry to log.\n\t * @returns A promise that resolves when the entry has been written to disk.\n\t */\n\tpublic async log(logEntry: ILogEntry): Promise<void> {\n\t\tGuards.object<ILogEntry>(FileLoggingConnector.CLASS_NAME, nameof(logEntry), logEntry);\n\n\t\tif (!this._levels.includes(logEntry.level)) {\n\t\t\treturn;\n\t\t}\n\n\t\tconst line = `${JSON.stringify(this.toRecord(logEntry))}\\n`;\n\t\tconst lineBytes = Buffer.byteLength(line, \"utf8\");\n\n\t\tconst locked = await Mutex.lock(this._mutexKey, {\n\t\t\tthrowOnTimeout: true,\n\t\t\ttimeoutMs: this._mutexTimeoutMs\n\t\t});\n\t\tif (locked) {\n\t\t\ttry {\n\t\t\t\tawait this.ensureOpen();\n\n\t\t\t\tif (\n\t\t\t\t\tthis._maxFileSizeBytes > 0 &&\n\t\t\t\t\tthis._currentSize > 0 &&\n\t\t\t\t\tthis._currentSize + lineBytes > this._maxFileSizeBytes\n\t\t\t\t) {\n\t\t\t\t\tawait this.rotate();\n\t\t\t\t}\n\n\t\t\t\t// Read after any rotation, which reopens the handle for the fresh active file.\n\t\t\t\tconst handle = this._handle;\n\t\t\t\tif (!Is.empty(handle)) {\n\t\t\t\t\tawait handle.write(line, null, \"utf8\");\n\t\t\t\t\tthis._currentSize += lineBytes;\n\t\t\t\t}\n\t\t\t} finally {\n\t\t\t\tMutex.unlock(this._mutexKey);\n\t\t\t}\n\t\t}\n\t}\n\n\t/**\n\t * Build the plain record written to disk from a log entry, defaulting the timestamp to the\n\t * current time as an ISO string and flattening any error into a serialisable form.\n\t * @param logEntry The entry being logged.\n\t * @returns The record to serialise as a single JSON line.\n\t * @internal\n\t */\n\tprivate toRecord(logEntry: ILogEntry): { [key: string]: unknown } {\n\t\treturn {\n\t\t\tlevel: logEntry.level,\n\t\t\tsource: logEntry.source,\n\t\t\ttimestamp: new Date(logEntry.ts ?? Date.now()).toISOString(),\n\t\t\tmessage: logEntry.message,\n\t\t\tdata: logEntry.data,\n\t\t\terror: Is.object<IError>(logEntry.error) ? BaseError.flatten(logEntry.error) : undefined\n\t\t};\n\t}\n\n\t/**\n\t * Ensure the target directory exists, the tracked size matches the active file on disk and\n\t * the file handle is open.\n\t * @returns A promise that resolves once the handle is open.\n\t * @internal\n\t */\n\tprivate async ensureOpen(): Promise<void> {\n\t\tif (Is.empty(this._handle)) {\n\t\t\tawait mkdir(this._directory, { recursive: true });\n\t\t\tthis._currentSize = await this.fileSize(this.activePath());\n\t\t\tthis._handle = await open(this.activePath(), \"a\");\n\t\t}\n\t}\n\n\t/**\n\t * Close the active file handle if it is open.\n\t * @returns A promise that resolves once the handle has been closed.\n\t * @internal\n\t */\n\tprivate async closeHandle(): Promise<void> {\n\t\tconst handle = this._handle;\n\t\tif (!Is.empty(handle)) {\n\t\t\tthis._handle = undefined;\n\t\t\tawait handle.close();\n\t\t}\n\t}\n\n\t/**\n\t * Rotate the active file by closing the handle, shifting the numbered files up, discarding\n\t * any beyond the retained file limit, then reopening a fresh active file. When no rotated\n\t * files are retained the active file is removed.\n\t * @returns A promise that resolves once rotation has completed.\n\t * @internal\n\t */\n\tprivate async rotate(): Promise<void> {\n\t\tawait this.closeHandle();\n\n\t\tconst active = this.activePath();\n\n\t\tif (this._maxRetainedFiles <= 0) {\n\t\t\tawait rm(active, { force: true });\n\t\t} else {\n\t\t\tawait rm(this.rotatedPath(this._maxRetainedFiles), { force: true });\n\n\t\t\tfor (let index = this._maxRetainedFiles - 1; index >= 1; index--) {\n\t\t\t\tconst from = this.rotatedPath(index);\n\t\t\t\tif (await this.fileExists(from)) {\n\t\t\t\t\tawait rename(from, this.rotatedPath(index + 1));\n\t\t\t\t}\n\t\t\t}\n\n\t\t\tawait rename(active, this.rotatedPath(1));\n\t\t}\n\n\t\tawait this.ensureOpen();\n\t\tthis._currentSize = 0;\n\t}\n\n\t/**\n\t * The path to the active log file.\n\t * @returns The path to the active file.\n\t * @internal\n\t */\n\tprivate activePath(): string {\n\t\treturn path.join(this._directory, this._filename);\n\t}\n\n\t/**\n\t * The path to a numbered rotated log file.\n\t * @param index The rotation index.\n\t * @returns The path to the rotated file, inserting the index before the file extension.\n\t * @internal\n\t */\n\tprivate rotatedPath(index: number): string {\n\t\tconst parsed = path.parse(this._filename);\n\t\treturn path.join(this._directory, `${parsed.name}.${index}${parsed.ext}`);\n\t}\n\n\t/**\n\t * Get the size in bytes of a file, returning 0 when it does not exist.\n\t * @param filePath The path to the file.\n\t * @returns The size of the file in bytes, or 0 if it does not exist.\n\t * @internal\n\t */\n\tprivate async fileSize(filePath: string): Promise<number> {\n\t\ttry {\n\t\t\tconst stats = await stat(filePath);\n\t\t\treturn stats.size;\n\t\t} catch {\n\t\t\treturn 0;\n\t\t}\n\t}\n\n\t/**\n\t * Determine whether a file exists.\n\t * @param filePath The path to the file.\n\t * @returns True if the file exists.\n\t * @internal\n\t */\n\tprivate async fileExists(filePath: string): Promise<boolean> {\n\t\ttry {\n\t\t\tawait stat(filePath);\n\t\t\treturn true;\n\t\t} catch {\n\t\t\treturn false;\n\t\t}\n\t}\n}\n"]}
|
package/dist/es/index.js
ADDED
|
@@ -0,0 +1,6 @@
|
|
|
1
|
+
// Copyright 2026 IOTA Stiftung.
|
|
2
|
+
// SPDX-License-Identifier: Apache-2.0.
|
|
3
|
+
export * from "./fileLoggingConnector.js";
|
|
4
|
+
export * from "./models/IFileLoggingConnectorConfig.js";
|
|
5
|
+
export * from "./models/IFileLoggingConnectorConstructorOptions.js";
|
|
6
|
+
//# sourceMappingURL=index.js.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"index.js","sourceRoot":"","sources":["../../src/index.ts"],"names":[],"mappings":"AAAA,gCAAgC;AAChC,uCAAuC;AACvC,cAAc,2BAA2B,CAAC;AAC1C,cAAc,yCAAyC,CAAC;AACxD,cAAc,qDAAqD,CAAC","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nexport * from \"./fileLoggingConnector.js\";\nexport * from \"./models/IFileLoggingConnectorConfig.js\";\nexport * from \"./models/IFileLoggingConnectorConstructorOptions.js\";\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IFileLoggingConnectorConfig.js","sourceRoot":"","sources":["../../../src/models/IFileLoggingConnectorConfig.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { ILoggingLevelsConfig } from \"@twin.org/logging-models\";\n\n/**\n * Configuration for the File Logging Connector.\n */\nexport interface IFileLoggingConnectorConfig extends ILoggingLevelsConfig {\n\t/**\n\t * The directory in which the log files are written, created if it does not exist.\n\t */\n\tdirectory: string;\n\n\t/**\n\t * The name of the active log file within the directory.\n\t * @default app.log\n\t */\n\tfilename?: string;\n\n\t/**\n\t * The maximum size in bytes the active log file can reach before it is rotated.\n\t * A value of 0 or less disables size based rotation, allowing the file to grow without bound.\n\t * A positive value below the minimum of 102400 (100 KB) throws on construction, to avoid\n\t * excessive rotation.\n\t * @default 10485760\n\t */\n\tmaxFileSizeBytes?: number;\n\n\t/**\n\t * The maximum number of rotated log files to retain alongside the active file.\n\t * When the limit is reached the oldest rotated file is removed.\n\t * A value of 0 or less retains no rotated files, the active file is discarded on rotation.\n\t * @default 5\n\t */\n\tmaxRetainedFiles?: number;\n\n\t/**\n\t * The timeout in milliseconds to wait when acquiring the write lock before a log call fails.\n\t * Defaults to the Mutex default when not set.\n\t */\n\tmutexTimeoutMs?: number;\n}\n"]}
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"IFileLoggingConnectorConstructorOptions.js","sourceRoot":"","sources":["../../../src/models/IFileLoggingConnectorConstructorOptions.ts"],"names":[],"mappings":"","sourcesContent":["// Copyright 2026 IOTA Stiftung.\n// SPDX-License-Identifier: Apache-2.0.\nimport type { IFileLoggingConnectorConfig } from \"./IFileLoggingConnectorConfig.js\";\n\n/**\n * Options for the file logging connector constructor.\n */\nexport interface IFileLoggingConnectorConstructorOptions {\n\t/**\n\t * The configuration for the file logging connector.\n\t */\n\tconfig: IFileLoggingConnectorConfig;\n}\n"]}
|
|
@@ -0,0 +1,72 @@
|
|
|
1
|
+
import { type ILogEntry, type ILoggingConnector } from "@twin.org/logging-models";
|
|
2
|
+
import type { IFileLoggingConnectorConstructorOptions } from "./models/IFileLoggingConnectorConstructorOptions.js";
|
|
3
|
+
/**
|
|
4
|
+
* Class for performing logging operations to size-limited files on disk.
|
|
5
|
+
*
|
|
6
|
+
* Entries are appended to an active file as newline delimited JSON through a file handle
|
|
7
|
+
* that is opened once and kept open, avoiding an open and close on every write. Each entry
|
|
8
|
+
* is written straight through to the file so it is durable as soon as log() resolves.
|
|
9
|
+
* When the active file would exceed the configured size limit it is rotated: the active
|
|
10
|
+
* file becomes the newest numbered file and any file beyond the retained file limit is
|
|
11
|
+
* removed, keeping total on-disk usage predictable.
|
|
12
|
+
*
|
|
13
|
+
* The connector assumes a single writer per file: one instance should own a given log file.
|
|
14
|
+
* Its own writes and rotations are serialised with a mutex, but it does not coordinate with
|
|
15
|
+
* other processes or external tools rotating the same file.
|
|
16
|
+
*/
|
|
17
|
+
export declare class FileLoggingConnector implements ILoggingConnector {
|
|
18
|
+
/**
|
|
19
|
+
* The namespace for the logging connector.
|
|
20
|
+
*/
|
|
21
|
+
static readonly NAMESPACE: string;
|
|
22
|
+
/**
|
|
23
|
+
* Runtime name for the class.
|
|
24
|
+
*/
|
|
25
|
+
static readonly CLASS_NAME: string;
|
|
26
|
+
/**
|
|
27
|
+
* Default name for the active log file.
|
|
28
|
+
*/
|
|
29
|
+
static readonly DEFAULT_FILENAME: string;
|
|
30
|
+
/**
|
|
31
|
+
* Default maximum size in bytes of the active log file before rotation (10 MB).
|
|
32
|
+
*/
|
|
33
|
+
static readonly DEFAULT_MAX_FILE_SIZE_BYTES: number;
|
|
34
|
+
/**
|
|
35
|
+
* Minimum size in bytes that can be configured for the active log file before rotation (100 KB).
|
|
36
|
+
*/
|
|
37
|
+
static readonly MIN_MAX_FILE_SIZE_BYTES: number;
|
|
38
|
+
/**
|
|
39
|
+
* Default number of rotated log files to retain.
|
|
40
|
+
*/
|
|
41
|
+
static readonly DEFAULT_MAX_RETAINED_FILES: number;
|
|
42
|
+
/**
|
|
43
|
+
* Create a new instance of FileLoggingConnector.
|
|
44
|
+
* @param options The options for the logging connector.
|
|
45
|
+
* @throws GeneralError if maxFileSizeBytes is a positive value below the minimum.
|
|
46
|
+
*/
|
|
47
|
+
constructor(options: IFileLoggingConnectorConstructorOptions);
|
|
48
|
+
/**
|
|
49
|
+
* Returns the class name of the component.
|
|
50
|
+
* @returns The class name of the component.
|
|
51
|
+
*/
|
|
52
|
+
className(): string;
|
|
53
|
+
/**
|
|
54
|
+
* Start the connector; ensures the target directory exists and opens the file handle.
|
|
55
|
+
* @returns A promise that resolves when the connector is ready to accept log entries.
|
|
56
|
+
*/
|
|
57
|
+
start(): Promise<void>;
|
|
58
|
+
/**
|
|
59
|
+
* Stop the connector; closes the file handle, releasing the descriptor.
|
|
60
|
+
* Calling stop() on a connector that has not been opened is a no-op.
|
|
61
|
+
* @returns A promise that resolves when the handle has been closed.
|
|
62
|
+
*/
|
|
63
|
+
stop(): Promise<void>;
|
|
64
|
+
/**
|
|
65
|
+
* Log an entry to the connector.
|
|
66
|
+
* The entry is appended to the active file as a single newline delimited JSON record;
|
|
67
|
+
* when the active file exceeds the configured size limit it is rotated first.
|
|
68
|
+
* @param logEntry The entry to log.
|
|
69
|
+
* @returns A promise that resolves when the entry has been written to disk.
|
|
70
|
+
*/
|
|
71
|
+
log(logEntry: ILogEntry): Promise<void>;
|
|
72
|
+
}
|
|
@@ -0,0 +1,35 @@
|
|
|
1
|
+
import type { ILoggingLevelsConfig } from "@twin.org/logging-models";
|
|
2
|
+
/**
|
|
3
|
+
* Configuration for the File Logging Connector.
|
|
4
|
+
*/
|
|
5
|
+
export interface IFileLoggingConnectorConfig extends ILoggingLevelsConfig {
|
|
6
|
+
/**
|
|
7
|
+
* The directory in which the log files are written, created if it does not exist.
|
|
8
|
+
*/
|
|
9
|
+
directory: string;
|
|
10
|
+
/**
|
|
11
|
+
* The name of the active log file within the directory.
|
|
12
|
+
* @default app.log
|
|
13
|
+
*/
|
|
14
|
+
filename?: string;
|
|
15
|
+
/**
|
|
16
|
+
* The maximum size in bytes the active log file can reach before it is rotated.
|
|
17
|
+
* A value of 0 or less disables size based rotation, allowing the file to grow without bound.
|
|
18
|
+
* A positive value below the minimum of 102400 (100 KB) throws on construction, to avoid
|
|
19
|
+
* excessive rotation.
|
|
20
|
+
* @default 10485760
|
|
21
|
+
*/
|
|
22
|
+
maxFileSizeBytes?: number;
|
|
23
|
+
/**
|
|
24
|
+
* The maximum number of rotated log files to retain alongside the active file.
|
|
25
|
+
* When the limit is reached the oldest rotated file is removed.
|
|
26
|
+
* A value of 0 or less retains no rotated files, the active file is discarded on rotation.
|
|
27
|
+
* @default 5
|
|
28
|
+
*/
|
|
29
|
+
maxRetainedFiles?: number;
|
|
30
|
+
/**
|
|
31
|
+
* The timeout in milliseconds to wait when acquiring the write lock before a log call fails.
|
|
32
|
+
* Defaults to the Mutex default when not set.
|
|
33
|
+
*/
|
|
34
|
+
mutexTimeoutMs?: number;
|
|
35
|
+
}
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
import type { IFileLoggingConnectorConfig } from "./IFileLoggingConnectorConfig.js";
|
|
2
|
+
/**
|
|
3
|
+
* Options for the file logging connector constructor.
|
|
4
|
+
*/
|
|
5
|
+
export interface IFileLoggingConnectorConstructorOptions {
|
|
6
|
+
/**
|
|
7
|
+
* The configuration for the file logging connector.
|
|
8
|
+
*/
|
|
9
|
+
config: IFileLoggingConnectorConfig;
|
|
10
|
+
}
|
|
@@ -0,0 +1,19 @@
|
|
|
1
|
+
# Changelog
|
|
2
|
+
|
|
3
|
+
## [0.9.1-next.5](https://github.com/iotaledger/twin-logging/compare/logging-connector-file-v0.9.1-next.4...logging-connector-file-v0.9.1-next.5) (2026-07-20)
|
|
4
|
+
|
|
5
|
+
|
|
6
|
+
### Features
|
|
7
|
+
|
|
8
|
+
* add file logging connector with rotation and retention ([#67](https://github.com/iotaledger/twin-logging/issues/67)) ([d3ede7e](https://github.com/iotaledger/twin-logging/commit/d3ede7e7e12c765c4f8a3b5758252104ee0fe0d6))
|
|
9
|
+
|
|
10
|
+
|
|
11
|
+
### Dependencies
|
|
12
|
+
|
|
13
|
+
* The following workspace dependencies were updated
|
|
14
|
+
* dependencies
|
|
15
|
+
* @twin.org/logging-models bumped from 0.9.1-next.4 to 0.9.1-next.5
|
|
16
|
+
|
|
17
|
+
## v0.9.1-next.0
|
|
18
|
+
|
|
19
|
+
- Initial Release
|
package/docs/examples.md
ADDED
|
@@ -0,0 +1,137 @@
|
|
|
1
|
+
# Logging Connector File Examples
|
|
2
|
+
|
|
3
|
+
These examples show how to persist TWIN log events to disk. The connector appends each
|
|
4
|
+
entry to an active log file as newline delimited JSON (one JSON object per line), a format
|
|
5
|
+
that is easy to inspect, grep, and ingest with external log collection agents.
|
|
6
|
+
|
|
7
|
+
When the active file reaches the configured size limit it is rotated, and only a configured
|
|
8
|
+
number of rotated files are retained, so total on-disk usage stays predictable. This
|
|
9
|
+
connector persists entries but does not implement `query()`.
|
|
10
|
+
|
|
11
|
+
The connector assumes a single writer per file: one instance should own a given log file. It
|
|
12
|
+
does not coordinate with separate processes or external tools rotating the same file.
|
|
13
|
+
|
|
14
|
+
## Basic Setup
|
|
15
|
+
|
|
16
|
+
Pass a `directory` for the log files to the connector constructor. The directory is created
|
|
17
|
+
if it does not already exist.
|
|
18
|
+
|
|
19
|
+
```typescript
|
|
20
|
+
import { FileLoggingConnector } from '@twin.org/logging-connector-file';
|
|
21
|
+
|
|
22
|
+
const connector = new FileLoggingConnector({
|
|
23
|
+
config: {
|
|
24
|
+
directory: './logs',
|
|
25
|
+
filename: 'app.log',
|
|
26
|
+
maxFileSizeBytes: 10 * 1024 * 1024,
|
|
27
|
+
maxRetainedFiles: 5
|
|
28
|
+
}
|
|
29
|
+
});
|
|
30
|
+
|
|
31
|
+
// start() ensures the directory exists.
|
|
32
|
+
await connector.start();
|
|
33
|
+
```
|
|
34
|
+
|
|
35
|
+
## Logging Entries
|
|
36
|
+
|
|
37
|
+
```typescript
|
|
38
|
+
await connector.log({
|
|
39
|
+
level: 'info',
|
|
40
|
+
source: 'api-server',
|
|
41
|
+
message: 'startupComplete',
|
|
42
|
+
data: {
|
|
43
|
+
port: 8080,
|
|
44
|
+
environment: 'production'
|
|
45
|
+
}
|
|
46
|
+
});
|
|
47
|
+
|
|
48
|
+
await connector.log({
|
|
49
|
+
level: 'error',
|
|
50
|
+
source: 'worker',
|
|
51
|
+
message: 'jobFailed',
|
|
52
|
+
error: {
|
|
53
|
+
name: 'GeneralError',
|
|
54
|
+
message: 'queue.itemFailed'
|
|
55
|
+
},
|
|
56
|
+
data: {
|
|
57
|
+
jobId: 'job-42',
|
|
58
|
+
retries: 3
|
|
59
|
+
}
|
|
60
|
+
});
|
|
61
|
+
```
|
|
62
|
+
|
|
63
|
+
Each entry is written as a single line, for example:
|
|
64
|
+
|
|
65
|
+
```text
|
|
66
|
+
{"level":"info","source":"api-server","timestamp":"2023-11-14T22:13:20.000Z","message":"startupComplete","data":{"port":8080,"environment":"production"}}
|
|
67
|
+
```
|
|
68
|
+
|
|
69
|
+
The timestamp is populated automatically when not supplied, and an `error` is flattened
|
|
70
|
+
into a serialisable array preserving the cause chain.
|
|
71
|
+
|
|
72
|
+
## Shutting Down
|
|
73
|
+
|
|
74
|
+
The connector keeps the log file open between writes. Call `stop()` during a graceful
|
|
75
|
+
shutdown to close the file handle and release the descriptor. Entries are written straight
|
|
76
|
+
through to the file, so there is nothing buffered to lose if `stop()` is not called.
|
|
77
|
+
|
|
78
|
+
```typescript
|
|
79
|
+
await connector.stop();
|
|
80
|
+
```
|
|
81
|
+
|
|
82
|
+
## Rotation and Retention
|
|
83
|
+
|
|
84
|
+
The active file is always `<filename>`. When a write would take it past `maxFileSizeBytes`,
|
|
85
|
+
the existing files are shifted up by one and a fresh active file is started:
|
|
86
|
+
|
|
87
|
+
```text
|
|
88
|
+
app.log <- active file
|
|
89
|
+
app.1.log <- most recently rotated
|
|
90
|
+
app.2.log
|
|
91
|
+
...
|
|
92
|
+
app.5.log <- oldest retained (removed on the next rotation)
|
|
93
|
+
```
|
|
94
|
+
|
|
95
|
+
With `maxRetainedFiles` rotated files plus the active file, total on-disk usage is bounded
|
|
96
|
+
to roughly `(maxRetainedFiles + 1) * maxFileSizeBytes`. A single entry is
|
|
97
|
+
never split across files.
|
|
98
|
+
|
|
99
|
+
Set `maxFileSizeBytes` to `0` to disable size based rotation, or `maxRetainedFiles` to `0` to
|
|
100
|
+
keep no rotated files (the active file is discarded when it rotates). A positive
|
|
101
|
+
`maxFileSizeBytes` below 100 KB throws on construction to avoid excessive rotation.
|
|
102
|
+
|
|
103
|
+
## Filtering Levels
|
|
104
|
+
|
|
105
|
+
Limit which levels are written with `levels`:
|
|
106
|
+
|
|
107
|
+
```typescript
|
|
108
|
+
const connector = new FileLoggingConnector({
|
|
109
|
+
config: {
|
|
110
|
+
directory: './logs',
|
|
111
|
+
levels: ['warn', 'error']
|
|
112
|
+
}
|
|
113
|
+
});
|
|
114
|
+
```
|
|
115
|
+
|
|
116
|
+
## Composing with Other Connectors
|
|
117
|
+
|
|
118
|
+
The file connector can be combined with other connectors through `MultiLoggingConnector`,
|
|
119
|
+
for example to write to disk while also logging to the console:
|
|
120
|
+
|
|
121
|
+
```typescript
|
|
122
|
+
import { LoggingConnectorFactory, MultiLoggingConnector } from '@twin.org/logging-models';
|
|
123
|
+
import { ConsoleLoggingConnector } from '@twin.org/logging-connector-console';
|
|
124
|
+
import { FileLoggingConnector } from '@twin.org/logging-connector-file';
|
|
125
|
+
|
|
126
|
+
LoggingConnectorFactory.register('console', () => new ConsoleLoggingConnector());
|
|
127
|
+
LoggingConnectorFactory.register(
|
|
128
|
+
'file',
|
|
129
|
+
() => new FileLoggingConnector({ config: { directory: './logs' } })
|
|
130
|
+
);
|
|
131
|
+
|
|
132
|
+
const logging = new MultiLoggingConnector({
|
|
133
|
+
loggingConnectorTypes: ['console', 'file']
|
|
134
|
+
});
|
|
135
|
+
|
|
136
|
+
await logging.log({ level: 'info', source: 'api-server', message: 'ready' });
|
|
137
|
+
```
|
|
@@ -0,0 +1,173 @@
|
|
|
1
|
+
# Class: FileLoggingConnector
|
|
2
|
+
|
|
3
|
+
Class for performing logging operations to size-limited files on disk.
|
|
4
|
+
|
|
5
|
+
Entries are appended to an active file as newline delimited JSON through a file handle
|
|
6
|
+
that is opened once and kept open, avoiding an open and close on every write. Each entry
|
|
7
|
+
is written straight through to the file so it is durable as soon as log() resolves.
|
|
8
|
+
When the active file would exceed the configured size limit it is rotated: the active
|
|
9
|
+
file becomes the newest numbered file and any file beyond the retained file limit is
|
|
10
|
+
removed, keeping total on-disk usage predictable.
|
|
11
|
+
|
|
12
|
+
The connector assumes a single writer per file: one instance should own a given log file.
|
|
13
|
+
Its own writes and rotations are serialised with a mutex, but it does not coordinate with
|
|
14
|
+
other processes or external tools rotating the same file.
|
|
15
|
+
|
|
16
|
+
## Implements
|
|
17
|
+
|
|
18
|
+
- `ILoggingConnector`
|
|
19
|
+
|
|
20
|
+
## Constructors
|
|
21
|
+
|
|
22
|
+
### Constructor
|
|
23
|
+
|
|
24
|
+
> **new FileLoggingConnector**(`options`): `FileLoggingConnector`
|
|
25
|
+
|
|
26
|
+
Create a new instance of FileLoggingConnector.
|
|
27
|
+
|
|
28
|
+
#### Parameters
|
|
29
|
+
|
|
30
|
+
##### options
|
|
31
|
+
|
|
32
|
+
[`IFileLoggingConnectorConstructorOptions`](../interfaces/IFileLoggingConnectorConstructorOptions.md)
|
|
33
|
+
|
|
34
|
+
The options for the logging connector.
|
|
35
|
+
|
|
36
|
+
#### Returns
|
|
37
|
+
|
|
38
|
+
`FileLoggingConnector`
|
|
39
|
+
|
|
40
|
+
#### Throws
|
|
41
|
+
|
|
42
|
+
GeneralError if maxFileSizeBytes is a positive value below the minimum.
|
|
43
|
+
|
|
44
|
+
## Properties
|
|
45
|
+
|
|
46
|
+
### NAMESPACE {#namespace}
|
|
47
|
+
|
|
48
|
+
> `readonly` `static` **NAMESPACE**: `string` = `"file"`
|
|
49
|
+
|
|
50
|
+
The namespace for the logging connector.
|
|
51
|
+
|
|
52
|
+
***
|
|
53
|
+
|
|
54
|
+
### CLASS\_NAME {#class_name}
|
|
55
|
+
|
|
56
|
+
> `readonly` `static` **CLASS\_NAME**: `string`
|
|
57
|
+
|
|
58
|
+
Runtime name for the class.
|
|
59
|
+
|
|
60
|
+
***
|
|
61
|
+
|
|
62
|
+
### DEFAULT\_FILENAME {#default_filename}
|
|
63
|
+
|
|
64
|
+
> `readonly` `static` **DEFAULT\_FILENAME**: `string` = `"app.log"`
|
|
65
|
+
|
|
66
|
+
Default name for the active log file.
|
|
67
|
+
|
|
68
|
+
***
|
|
69
|
+
|
|
70
|
+
### DEFAULT\_MAX\_FILE\_SIZE\_BYTES {#default_max_file_size_bytes}
|
|
71
|
+
|
|
72
|
+
> `readonly` `static` **DEFAULT\_MAX\_FILE\_SIZE\_BYTES**: `number`
|
|
73
|
+
|
|
74
|
+
Default maximum size in bytes of the active log file before rotation (10 MB).
|
|
75
|
+
|
|
76
|
+
***
|
|
77
|
+
|
|
78
|
+
### MIN\_MAX\_FILE\_SIZE\_BYTES {#min_max_file_size_bytes}
|
|
79
|
+
|
|
80
|
+
> `readonly` `static` **MIN\_MAX\_FILE\_SIZE\_BYTES**: `number`
|
|
81
|
+
|
|
82
|
+
Minimum size in bytes that can be configured for the active log file before rotation (100 KB).
|
|
83
|
+
|
|
84
|
+
***
|
|
85
|
+
|
|
86
|
+
### DEFAULT\_MAX\_RETAINED\_FILES {#default_max_retained_files}
|
|
87
|
+
|
|
88
|
+
> `readonly` `static` **DEFAULT\_MAX\_RETAINED\_FILES**: `number` = `5`
|
|
89
|
+
|
|
90
|
+
Default number of rotated log files to retain.
|
|
91
|
+
|
|
92
|
+
## Methods
|
|
93
|
+
|
|
94
|
+
### className() {#classname}
|
|
95
|
+
|
|
96
|
+
> **className**(): `string`
|
|
97
|
+
|
|
98
|
+
Returns the class name of the component.
|
|
99
|
+
|
|
100
|
+
#### Returns
|
|
101
|
+
|
|
102
|
+
`string`
|
|
103
|
+
|
|
104
|
+
The class name of the component.
|
|
105
|
+
|
|
106
|
+
#### Implementation of
|
|
107
|
+
|
|
108
|
+
`ILoggingConnector.className`
|
|
109
|
+
|
|
110
|
+
***
|
|
111
|
+
|
|
112
|
+
### start() {#start}
|
|
113
|
+
|
|
114
|
+
> **start**(): `Promise`\<`void`\>
|
|
115
|
+
|
|
116
|
+
Start the connector; ensures the target directory exists and opens the file handle.
|
|
117
|
+
|
|
118
|
+
#### Returns
|
|
119
|
+
|
|
120
|
+
`Promise`\<`void`\>
|
|
121
|
+
|
|
122
|
+
A promise that resolves when the connector is ready to accept log entries.
|
|
123
|
+
|
|
124
|
+
#### Implementation of
|
|
125
|
+
|
|
126
|
+
`ILoggingConnector.start`
|
|
127
|
+
|
|
128
|
+
***
|
|
129
|
+
|
|
130
|
+
### stop() {#stop}
|
|
131
|
+
|
|
132
|
+
> **stop**(): `Promise`\<`void`\>
|
|
133
|
+
|
|
134
|
+
Stop the connector; closes the file handle, releasing the descriptor.
|
|
135
|
+
Calling stop() on a connector that has not been opened is a no-op.
|
|
136
|
+
|
|
137
|
+
#### Returns
|
|
138
|
+
|
|
139
|
+
`Promise`\<`void`\>
|
|
140
|
+
|
|
141
|
+
A promise that resolves when the handle has been closed.
|
|
142
|
+
|
|
143
|
+
#### Implementation of
|
|
144
|
+
|
|
145
|
+
`ILoggingConnector.stop`
|
|
146
|
+
|
|
147
|
+
***
|
|
148
|
+
|
|
149
|
+
### log() {#log}
|
|
150
|
+
|
|
151
|
+
> **log**(`logEntry`): `Promise`\<`void`\>
|
|
152
|
+
|
|
153
|
+
Log an entry to the connector.
|
|
154
|
+
The entry is appended to the active file as a single newline delimited JSON record;
|
|
155
|
+
when the active file exceeds the configured size limit it is rotated first.
|
|
156
|
+
|
|
157
|
+
#### Parameters
|
|
158
|
+
|
|
159
|
+
##### logEntry
|
|
160
|
+
|
|
161
|
+
`ILogEntry`
|
|
162
|
+
|
|
163
|
+
The entry to log.
|
|
164
|
+
|
|
165
|
+
#### Returns
|
|
166
|
+
|
|
167
|
+
`Promise`\<`void`\>
|
|
168
|
+
|
|
169
|
+
A promise that resolves when the entry has been written to disk.
|
|
170
|
+
|
|
171
|
+
#### Implementation of
|
|
172
|
+
|
|
173
|
+
`ILoggingConnector.log`
|
|
@@ -0,0 +1,10 @@
|
|
|
1
|
+
# @twin.org/logging-connector-file
|
|
2
|
+
|
|
3
|
+
## Classes
|
|
4
|
+
|
|
5
|
+
- [FileLoggingConnector](classes/FileLoggingConnector.md)
|
|
6
|
+
|
|
7
|
+
## Interfaces
|
|
8
|
+
|
|
9
|
+
- [IFileLoggingConnectorConfig](interfaces/IFileLoggingConnectorConfig.md)
|
|
10
|
+
- [IFileLoggingConnectorConstructorOptions](interfaces/IFileLoggingConnectorConstructorOptions.md)
|
|
@@ -0,0 +1,83 @@
|
|
|
1
|
+
# Interface: IFileLoggingConnectorConfig
|
|
2
|
+
|
|
3
|
+
Configuration for the File Logging Connector.
|
|
4
|
+
|
|
5
|
+
## Extends
|
|
6
|
+
|
|
7
|
+
- `ILoggingLevelsConfig`
|
|
8
|
+
|
|
9
|
+
## Properties
|
|
10
|
+
|
|
11
|
+
### directory {#directory}
|
|
12
|
+
|
|
13
|
+
> **directory**: `string`
|
|
14
|
+
|
|
15
|
+
The directory in which the log files are written, created if it does not exist.
|
|
16
|
+
|
|
17
|
+
***
|
|
18
|
+
|
|
19
|
+
### filename? {#filename}
|
|
20
|
+
|
|
21
|
+
> `optional` **filename?**: `string`
|
|
22
|
+
|
|
23
|
+
The name of the active log file within the directory.
|
|
24
|
+
|
|
25
|
+
#### Default
|
|
26
|
+
|
|
27
|
+
```ts
|
|
28
|
+
app.log
|
|
29
|
+
```
|
|
30
|
+
|
|
31
|
+
***
|
|
32
|
+
|
|
33
|
+
### maxFileSizeBytes? {#maxfilesizebytes}
|
|
34
|
+
|
|
35
|
+
> `optional` **maxFileSizeBytes?**: `number`
|
|
36
|
+
|
|
37
|
+
The maximum size in bytes the active log file can reach before it is rotated.
|
|
38
|
+
A value of 0 or less disables size based rotation, allowing the file to grow without bound.
|
|
39
|
+
A positive value below the minimum of 102400 (100 KB) throws on construction, to avoid
|
|
40
|
+
excessive rotation.
|
|
41
|
+
|
|
42
|
+
#### Default
|
|
43
|
+
|
|
44
|
+
```ts
|
|
45
|
+
10485760
|
|
46
|
+
```
|
|
47
|
+
|
|
48
|
+
***
|
|
49
|
+
|
|
50
|
+
### maxRetainedFiles? {#maxretainedfiles}
|
|
51
|
+
|
|
52
|
+
> `optional` **maxRetainedFiles?**: `number`
|
|
53
|
+
|
|
54
|
+
The maximum number of rotated log files to retain alongside the active file.
|
|
55
|
+
When the limit is reached the oldest rotated file is removed.
|
|
56
|
+
A value of 0 or less retains no rotated files, the active file is discarded on rotation.
|
|
57
|
+
|
|
58
|
+
#### Default
|
|
59
|
+
|
|
60
|
+
```ts
|
|
61
|
+
5
|
|
62
|
+
```
|
|
63
|
+
|
|
64
|
+
***
|
|
65
|
+
|
|
66
|
+
### mutexTimeoutMs? {#mutextimeoutms}
|
|
67
|
+
|
|
68
|
+
> `optional` **mutexTimeoutMs?**: `number`
|
|
69
|
+
|
|
70
|
+
The timeout in milliseconds to wait when acquiring the write lock before a log call fails.
|
|
71
|
+
Defaults to the Mutex default when not set.
|
|
72
|
+
|
|
73
|
+
***
|
|
74
|
+
|
|
75
|
+
### levels? {#levels}
|
|
76
|
+
|
|
77
|
+
> `optional` **levels?**: `LogLevel`[]
|
|
78
|
+
|
|
79
|
+
The log levels to display, will default to all.
|
|
80
|
+
|
|
81
|
+
#### Inherited from
|
|
82
|
+
|
|
83
|
+
`ILoggingLevelsConfig.levels`
|
|
@@ -0,0 +1,11 @@
|
|
|
1
|
+
# Interface: IFileLoggingConnectorConstructorOptions
|
|
2
|
+
|
|
3
|
+
Options for the file logging connector constructor.
|
|
4
|
+
|
|
5
|
+
## Properties
|
|
6
|
+
|
|
7
|
+
### config {#config}
|
|
8
|
+
|
|
9
|
+
> **config**: [`IFileLoggingConnectorConfig`](IFileLoggingConnectorConfig.md)
|
|
10
|
+
|
|
11
|
+
The configuration for the file logging connector.
|
package/locales/en.json
ADDED
package/package.json
ADDED
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
{
|
|
2
|
+
"name": "@twin.org/logging-connector-file",
|
|
3
|
+
"version": "0.9.1-next.5",
|
|
4
|
+
"description": "Writes log events to size-limited files on disk with rotation and retention for local log persistence.",
|
|
5
|
+
"repository": {
|
|
6
|
+
"type": "git",
|
|
7
|
+
"url": "git+https://github.com/iotaledger/twin-logging.git",
|
|
8
|
+
"directory": "packages/logging-connector-file"
|
|
9
|
+
},
|
|
10
|
+
"author": "vitaliy@iota.org",
|
|
11
|
+
"license": "Apache-2.0",
|
|
12
|
+
"type": "module",
|
|
13
|
+
"engines": {
|
|
14
|
+
"node": ">=20.0.0"
|
|
15
|
+
},
|
|
16
|
+
"dependencies": {
|
|
17
|
+
"@twin.org/core": "next",
|
|
18
|
+
"@twin.org/logging-models": "0.9.1-next.5",
|
|
19
|
+
"@twin.org/nameof": "next"
|
|
20
|
+
},
|
|
21
|
+
"main": "./dist/es/index.js",
|
|
22
|
+
"types": "./dist/types/index.d.ts",
|
|
23
|
+
"exports": {
|
|
24
|
+
".": {
|
|
25
|
+
"types": "./dist/types/index.d.ts",
|
|
26
|
+
"import": "./dist/es/index.js",
|
|
27
|
+
"default": "./dist/es/index.js"
|
|
28
|
+
},
|
|
29
|
+
"./locales/*.json": "./locales/*.json"
|
|
30
|
+
},
|
|
31
|
+
"files": [
|
|
32
|
+
"dist/es",
|
|
33
|
+
"dist/types",
|
|
34
|
+
"locales",
|
|
35
|
+
"docs"
|
|
36
|
+
],
|
|
37
|
+
"keywords": [
|
|
38
|
+
"twin",
|
|
39
|
+
"trade",
|
|
40
|
+
"iota",
|
|
41
|
+
"framework",
|
|
42
|
+
"blockchain",
|
|
43
|
+
"logging",
|
|
44
|
+
"file",
|
|
45
|
+
"rotation",
|
|
46
|
+
"retention",
|
|
47
|
+
"connector",
|
|
48
|
+
"adapter",
|
|
49
|
+
"integration"
|
|
50
|
+
],
|
|
51
|
+
"bugs": {
|
|
52
|
+
"url": "git+https://github.com/iotaledger/twin-logging/issues"
|
|
53
|
+
},
|
|
54
|
+
"homepage": "https://twindev.org"
|
|
55
|
+
}
|