forked from vectordotdev/timber-js
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbase.ts
287 lines (241 loc) · 6.62 KB
/
base.ts
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
import {
ITimberLog,
ITimberOptions,
LogLevel,
Middleware,
Sync
} from "@timberio/types";
import { makeBatch, makeThrottle } from "@timberio/tools";
// Types
type Message = string | Error;
// Set default options for Timber
const defaultOptions: ITimberOptions = {
// Default sync endpoint:
endpoint: "https://logs.timber.io/frames",
// Maximum number of logs to sync in a single request to Timber.io
batchSize: 1000,
// Max interval (in milliseconds) before a batch of logs proceeds to syncing
batchInterval: 1000,
// Maximum number of sync requests to make concurrently
syncMax: 5
};
/**
* Timber core class for logging to the Timber.io service
*/
class Timber {
// Timber API key
protected _apiKey: string;
// Timber library options
protected _options: ITimberOptions;
// Batch function
protected _batch: any;
// Middleware
protected _middleware: Middleware[] = [];
// Sync function
protected _sync?: Sync;
// Number of logs logged
private _countLogged = 0;
// Number of logs successfully synced with Timber
private _countSynced = 0;
/* CONSTRUCTOR */
/**
* Initializes a new Timber instance
*
* @param apiKey: string - Private API key for logging to Timber.io
* @param options?: ITimberOptions - Optionally specify Timber options
*/
public constructor(apiKey: string, options?: Partial<ITimberOptions>) {
// First, check we have a valid API key
if (typeof apiKey !== "string" || apiKey === "") {
throw new Error("Timber API key missing");
}
// Store the API key, to use for syncing with Timber.io
this._apiKey = apiKey;
// Merge default and user options
this._options = { ...defaultOptions, ...options };
// Create a throttler, for sync operations
const throttle = makeThrottle(this._options.syncMax);
// Sync after throttling
const throttler = throttle((logs: any) => {
return this._sync!(logs);
});
// Create a batcher, for aggregating logs by buffer size/interval
const batcher = makeBatch(
this._options.batchSize,
this._options.batchInterval
);
this._batch = batcher((logs: any) => {
return throttler(logs);
});
}
/* PRIVATE METHODS */
private getContextFromError(e: Error) {
return {
stack: e.stack
};
}
/* PUBLIC METHODS */
/**
* Number of entries logged
*
* @returns number
*/
public get logged(): number {
return this._countLogged;
}
/**
* Number of log entries synced with Timber.io
*
* @returns number
*/
public get synced(): number {
return this._countSynced;
}
/**
* Log an entry, to be synced with Timber.io
*
* @param message: string - Log message
* @param level (LogLevel) - Level to log at (debug|info|warn|error)
* @param context: (Pick<ITimberLog, "context">) - Context (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async log(
message: Message,
level: LogLevel = LogLevel.Info,
context: Pick<ITimberLog, "context"> = {}
): Promise<ITimberLog> {
// Check that we have a sync function
if (typeof this._sync !== "function") {
throw new Error("No Timber logger sync function provided");
}
// Increment log count
this._countLogged++;
// Start building the log message
let log: Partial<ITimberLog> = {
// Implicit date timestamp
dt: new Date(),
// Explicit level
level,
// Add initial context
context
};
// Determine the type of message...
// Is this an error?
if (message instanceof Error) {
log = {
// Add stub
...log,
// Add stack trace
context: {
...log.context,
...this.getContextFromError(message)
},
// Add error message
message: message.message
};
} else {
log = {
// Add stub
...log,
// Add string message
message
};
}
// Pass the log through the middleware pipeline
const transformedLog = await this._middleware.reduceRight(
(fn, pipedLog) => fn.then(pipedLog),
Promise.resolve(log as ITimberLog)
);
// Push the log through the batcher, and sync
await this._batch(transformedLog);
// Increment sync count
this._countSynced++;
// Return the resulting log
return transformedLog;
}
/**
*
* Debug level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param context: (Pick<ITimberLog, "context">) - Context (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async debug(
message: Message,
context?: Pick<ITimberLog, "context">
): Promise<ITimberLog> {
return this.log(message, LogLevel.Debug, context);
}
/**
*
* Info level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param context: (Pick<ITimberLog, "context">) - Context (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async info(
message: Message,
context?: Pick<ITimberLog, "context">
): Promise<ITimberLog> {
return this.log(message, LogLevel.Info, context);
}
/**
*
* Warning level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param context: (Pick<ITimberLog, "context">) - Context (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async warn(
message: Message,
context?: Pick<ITimberLog, "context">
): Promise<ITimberLog> {
return this.log(message, LogLevel.Warn, context);
}
/**
*
* Warning level log, to be synced with Timber.io
*
* @param message: string - Log message
* @param context: (Pick<ITimberLog, "context">) - Context (optional)
* @returns Promise<ITimberLog> after syncing
*/
public async error(
message: Message,
context?: Pick<ITimberLog, "context">
): Promise<ITimberLog> {
return this.log(message, LogLevel.Error, context);
}
/**
* Sets the sync method - i.e. the final step in the pipeline to get logs
* over to Timber.io
*
* @param fn - Pipeline function to use as sync method
*/
public setSync(fn: Sync): void {
this._sync = fn;
}
/**
* Add a middleware function to the logging pipeline
*
* @param fn - Function to add to the log pipeline
* @returns void
*/
public use(fn: Middleware): void {
this._middleware.push(fn);
}
/**
* Remove a function from the pipeline
*
* @param fn - Pipeline function
* @returns void
*/
public remove(fn: Middleware): void {
this._middleware = this._middleware.filter(p => p !== fn);
}
}
// noinspection JSUnusedGlobalSymbols
export default Timber;