Compare commits
11 Commits
331169c925
...
alpha
Author | SHA1 | Date | |
---|---|---|---|
0dbd8e9c40 | |||
27da76c1b0 | |||
096c5910c3 | |||
2aaee1be89 | |||
0b75f8ddf8 | |||
03cc58d3e1 | |||
72f06a88d6 | |||
9417264850 | |||
58ff2fd2ea | |||
dec35001e3 | |||
fbb55fa158 |
@ -1,5 +0,0 @@
|
|||||||
charset = utf-8
|
|
||||||
indent_style = space
|
|
||||||
indent_size = 3
|
|
||||||
trim_trailing_whitespace = true
|
|
||||||
end_of_line = lf
|
|
3
.gitignore
vendored
3
.gitignore
vendored
@ -1,4 +1,5 @@
|
|||||||
node_modules/
|
node_modules/
|
||||||
logs/
|
logs/
|
||||||
yarn.lock
|
yarn.lock
|
||||||
out/
|
out/
|
||||||
|
.history/
|
3110
package-lock.json
generated
Normal file
3110
package-lock.json
generated
Normal file
File diff suppressed because it is too large
Load Diff
17
package.json
17
package.json
@ -1,25 +1,32 @@
|
|||||||
{
|
{
|
||||||
"name": "@hibas123/nodelogging",
|
"name": "@hibas123/nodelogging",
|
||||||
"version": "1.3.21",
|
"version": "2.0.1",
|
||||||
"description": "",
|
"description": "",
|
||||||
"main": "out/index.js",
|
"main": "out/index.js",
|
||||||
"types": "out/index.d.ts",
|
"types": "out/index.d.ts",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
"prepublish": "tsc",
|
"prepublish": "tsc",
|
||||||
"build": "tsc",
|
"build": "tsc",
|
||||||
"watch": "tsc --watch",
|
"watch-ts": "tsc --watch",
|
||||||
|
"watch-js": "nodemon out/test.js",
|
||||||
|
"watch": "concurrently npm:watch-*",
|
||||||
"test": "node out/test.js",
|
"test": "node out/test.js",
|
||||||
"live": "nodemon out/test.js"
|
"live": "nodemon out/test.js"
|
||||||
},
|
},
|
||||||
"repository": {
|
"repository": {
|
||||||
"type": "git",
|
"type": "git",
|
||||||
"url": "https://git.stamm.me/PerfCloud/nodelogging.git"
|
"url": "https://git.stamm.me/OpenServer/NodeLogging.git"
|
||||||
},
|
},
|
||||||
"author": "Fabian Stamm",
|
"author": "Fabian Stamm",
|
||||||
"license": "MIT",
|
"license": "MIT",
|
||||||
"devDependencies": {
|
"devDependencies": {
|
||||||
"@types/node": "^8.0.24",
|
"@types/node": "^11.13.0",
|
||||||
|
"concurrently": "^4.1.0",
|
||||||
"nodemon": "^1.17.4",
|
"nodemon": "^1.17.4",
|
||||||
"typescript": "^2.4.2"
|
"typescript": "^3.4.1"
|
||||||
|
},
|
||||||
|
"dependencies": {
|
||||||
|
"@hibas123/logging": "^2.0.0",
|
||||||
|
"@hibas123/utils": "^2.0.5"
|
||||||
}
|
}
|
||||||
}
|
}
|
68
readme.md
68
readme.md
@ -1,4 +1,8 @@
|
|||||||
Simple node logging module, that supports terminal coloring and writing to files
|
Simple logging module, that supports terminal coloring and writing to files.
|
||||||
|
|
||||||
|
This module build ontop of [@hibas123/logging](https://www.npmjs.com/package/@hibas123/utils).
|
||||||
|
|
||||||
|
It extends the default behavior to support Logging to Files out of the Box.
|
||||||
|
|
||||||
# Getting Started
|
# Getting Started
|
||||||
|
|
||||||
@ -30,20 +34,66 @@ NodeLogging can work without any configuration, but it may be useful to change t
|
|||||||
Todo so you are capable of creating own instances of the LoggingBase class
|
Todo so you are capable of creating own instances of the LoggingBase class
|
||||||
|
|
||||||
``` javascript
|
``` javascript
|
||||||
const CustomLogging = new LoggingBase({
|
const CustomLogging = new LoggingBase(name | {
|
||||||
name: "custom",
|
name: "custom", // default undefined
|
||||||
logfile: "./logs/test.log",
|
files: true | false | { //default true
|
||||||
errorfile: "/var/log/custom.err",
|
logfile: "./logs/test.log",
|
||||||
console_out: false
|
errorfile: "/var/log/custom.err",
|
||||||
|
}
|
||||||
|
console: false // default true
|
||||||
});
|
});
|
||||||
```
|
```
|
||||||
|
|
||||||
The name property prefixes the console output with the name. Also if no logfile or errorfile is created the following standard values are used:
|
The name property prefixes the console output with the name. Also if no logfile or errorfile is created the following standard values are used:
|
||||||
|
|
||||||
./logs/all.{name}.log
|
- ./logs/all.{name}.log
|
||||||
./logs/error.{name}.log
|
- ./logs/error.{name}.log
|
||||||
|
|
||||||
|
To not use any logfiles just set files to false.
|
||||||
|
|
||||||
|
# Plugins
|
||||||
|
|
||||||
|
There is a new Plugin API available, that makes is possible to add custom Logging Adapter.
|
||||||
|
|
||||||
|
``` javascript
|
||||||
|
const Demo = new LoggingExtended("Demo");
|
||||||
|
Demo.addAdapter(new DemoAdapter({ color: "rainbow" }));
|
||||||
|
```
|
||||||
|
|
||||||
|
The adapters need to provide a very simple Interface:
|
||||||
|
|
||||||
|
``` typescript
|
||||||
|
interface Adapter {
|
||||||
|
init(observable: ObservableInterface<Message>, name?: string): void | Promise<void>;
|
||||||
|
|
||||||
|
flush(sync: true): void;
|
||||||
|
flush(sync: false): void | Promise<void>;
|
||||||
|
}
|
||||||
|
|
||||||
|
interface Message {
|
||||||
|
type: LoggingTypes;
|
||||||
|
name?:string;
|
||||||
|
text: {
|
||||||
|
raw: string[],
|
||||||
|
formatted: string[]
|
||||||
|
};
|
||||||
|
date: Date;
|
||||||
|
file: string;
|
||||||
|
customColors?:string;
|
||||||
|
}
|
||||||
|
|
||||||
|
enum LoggingTypes {
|
||||||
|
Log,
|
||||||
|
Warning,
|
||||||
|
Error,
|
||||||
|
Debug
|
||||||
|
}
|
||||||
|
```
|
||||||
|
|
||||||
|
The `ObservableInterface` comes from `@hibas123/utils`. It provides a very simple api for subscribing and unsubscribing from the message events.
|
||||||
|
|
||||||
|
More Details on Observable [here](https://git.stamm.me/OpenServer/Utils)
|
||||||
|
|
||||||
To not use any logfiles just set the values to null.
|
|
||||||
# License
|
# License
|
||||||
MIT
|
MIT
|
||||||
|
|
||||||
|
226
src/filewriter.ts
Normal file
226
src/filewriter.ts
Normal file
@ -0,0 +1,226 @@
|
|||||||
|
import { Lock, ObservableInterface } from "@hibas123/utils";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import * as path from "path";
|
||||||
|
import { Adapter, Message, LoggingTypes } from "@hibas123/logging";
|
||||||
|
|
||||||
|
|
||||||
|
const MAX_FILE_SIZE = 500000000;
|
||||||
|
|
||||||
|
export class LoggingFiles implements Adapter {
|
||||||
|
file: Files;
|
||||||
|
constructor(filename: string, private error = false, private maxFileSize = MAX_FILE_SIZE) {
|
||||||
|
this.file = Files.getFile(filename);
|
||||||
|
}
|
||||||
|
|
||||||
|
|
||||||
|
init(observable: ObservableInterface<Message>) {
|
||||||
|
observable.subscribe(this.onMessage.bind(this));
|
||||||
|
return this.file.init(this.maxFileSize);
|
||||||
|
}
|
||||||
|
|
||||||
|
flush(sync: boolean) {
|
||||||
|
this.file.flush(sync);
|
||||||
|
}
|
||||||
|
|
||||||
|
onMessage(message: Message) {
|
||||||
|
// Just ignore all non error messages, if this.error is set
|
||||||
|
if (this.error && message.type !== LoggingTypes.Error)
|
||||||
|
return;
|
||||||
|
|
||||||
|
let txt = message.text.formatted.map(fmt => fmt.map(f => f.text).join("") + "\n").join("");
|
||||||
|
|
||||||
|
let msg = Buffer.from(txt);
|
||||||
|
this.file.write(msg);
|
||||||
|
}
|
||||||
|
|
||||||
|
close() {
|
||||||
|
this.file.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
export class Files {
|
||||||
|
private open = 0;
|
||||||
|
|
||||||
|
private static files = new Map<string, Files>();
|
||||||
|
static getFile(filename: string): Files {
|
||||||
|
filename = path.resolve(filename);
|
||||||
|
let file = this.files.get(filename);
|
||||||
|
if (!file) {
|
||||||
|
file = new Files(filename);
|
||||||
|
this.files.set(filename, file);
|
||||||
|
}
|
||||||
|
file.open++;
|
||||||
|
return file;
|
||||||
|
}
|
||||||
|
|
||||||
|
private maxFileSize = MAX_FILE_SIZE;
|
||||||
|
private size: number = 0;
|
||||||
|
private stream: fs.WriteStream = undefined;
|
||||||
|
private lock = new Lock();
|
||||||
|
|
||||||
|
public initialized = false;
|
||||||
|
|
||||||
|
private constructor(private file: string) { }
|
||||||
|
|
||||||
|
public async init(maxFileSize: number) {
|
||||||
|
if (this.initialized)
|
||||||
|
return;
|
||||||
|
let lock = await this.lock.getLock();
|
||||||
|
this.maxFileSize == maxFileSize;
|
||||||
|
await this.initializeFile()
|
||||||
|
this.initialized = true;
|
||||||
|
lock.release();
|
||||||
|
this.checkQueue()
|
||||||
|
}
|
||||||
|
|
||||||
|
private async initializeFile(new_file = false) {
|
||||||
|
try {
|
||||||
|
if (this.stream) {
|
||||||
|
this.stream.close();
|
||||||
|
}
|
||||||
|
const folder = path.dirname(this.file);
|
||||||
|
if (folder) {
|
||||||
|
if (!await fsExists(folder)) {
|
||||||
|
await fsMkDir(folder).catch(() => { }); //Could happen, if two seperate instances want to create the same folder so ignoring
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
let size = 0;
|
||||||
|
if (await fsExists(this.file)) {
|
||||||
|
let stats = await fsStat(this.file);
|
||||||
|
if (new_file || stats.size >= this.maxFileSize) {
|
||||||
|
if (await fsExists(this.file + ".old"))
|
||||||
|
await fsUnlink(this.file + ".old");
|
||||||
|
await fsMove(this.file, this.file + ".old")
|
||||||
|
} else {
|
||||||
|
size = stats.size;
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
this.stream = fs.createWriteStream(this.file, { flags: "a" })
|
||||||
|
this.size = size;
|
||||||
|
} catch (e) {
|
||||||
|
console.log(e);
|
||||||
|
//ToDo is this the right behavior?
|
||||||
|
process.exit(1);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private queue: Buffer[] = [];
|
||||||
|
|
||||||
|
async checkQueue() {
|
||||||
|
if (this.lock.locked) return;
|
||||||
|
let lock = await this.lock.getLock();
|
||||||
|
let msg: Buffer;
|
||||||
|
while (msg = this.queue.shift()) {
|
||||||
|
await this.write_to_file(msg);
|
||||||
|
}
|
||||||
|
lock.release();
|
||||||
|
}
|
||||||
|
|
||||||
|
public async close() {
|
||||||
|
await this.flush(false);
|
||||||
|
this.open--;
|
||||||
|
if (this.open <= 0) {
|
||||||
|
this.stream.close()
|
||||||
|
Files.files.delete(this.file);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
public flush(sync: boolean) {
|
||||||
|
if (sync) {
|
||||||
|
// if sync flush, the process most likely is in failstate, so checkQueue stopped its work.
|
||||||
|
let msg: Buffer;
|
||||||
|
while (msg = this.queue.shift()) {
|
||||||
|
this.stream.write(msg);
|
||||||
|
}
|
||||||
|
} else {
|
||||||
|
return Promise.resolve().then(async () => {
|
||||||
|
const lock = await this.lock.getLock();
|
||||||
|
lock.release();
|
||||||
|
await this.checkQueue();
|
||||||
|
})
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
private async write_to_file(data: Buffer) {
|
||||||
|
try {
|
||||||
|
if (data.byteLength < this.maxFileSize && this.size + data.byteLength > this.maxFileSize) {
|
||||||
|
await this.initializeFile(true)
|
||||||
|
}
|
||||||
|
this.size += data.byteLength;
|
||||||
|
this.stream.write(data);
|
||||||
|
} catch (err) {
|
||||||
|
// TODO: Better error handling!
|
||||||
|
console.error(err);
|
||||||
|
this.initializeFile(false);
|
||||||
|
this.write_to_file(data);
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
public write(data: Buffer) {
|
||||||
|
this.queue.push(data);
|
||||||
|
this.checkQueue()
|
||||||
|
}
|
||||||
|
|
||||||
|
public dispose() {
|
||||||
|
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|
||||||
|
function fsUnlink(path) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
fs.unlink(path, (err) => {
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolve();
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fsStat(path: string) {
|
||||||
|
return new Promise<fs.Stats>((resolve, reject) => {
|
||||||
|
fs.stat(path, (err, stats) => {
|
||||||
|
if (err) reject(err);
|
||||||
|
else resolve(stats);
|
||||||
|
})
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fsMove(oldPath: string, newPath: string) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
let callback = (err?) => {
|
||||||
|
if (err) reject(err)
|
||||||
|
else resolve()
|
||||||
|
}
|
||||||
|
|
||||||
|
fs.rename(oldPath, newPath, function (err) {
|
||||||
|
if (err) {
|
||||||
|
if (err.code === 'EXDEV') {
|
||||||
|
copy();
|
||||||
|
} else {
|
||||||
|
callback(err)
|
||||||
|
}
|
||||||
|
return;
|
||||||
|
}
|
||||||
|
callback()
|
||||||
|
});
|
||||||
|
|
||||||
|
function copy() {
|
||||||
|
fs.copyFile(oldPath, newPath, (err) => {
|
||||||
|
if (err) callback(err)
|
||||||
|
else fs.unlink(oldPath, callback);
|
||||||
|
})
|
||||||
|
}
|
||||||
|
})
|
||||||
|
}
|
||||||
|
|
||||||
|
function fsExists(path: string) {
|
||||||
|
return new Promise<boolean>((resolve, reject) => {
|
||||||
|
fs.exists(path, resolve);
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
function fsMkDir(path: string) {
|
||||||
|
return new Promise((resolve, reject) => {
|
||||||
|
fs.mkdir(path, (err) => err ? reject(err) : resolve());
|
||||||
|
});
|
||||||
|
}
|
470
src/index.ts
470
src/index.ts
@ -1,309 +1,50 @@
|
|||||||
import * as util from "util";
|
export { LoggingFiles } from "./filewriter";
|
||||||
import * as fs from "fs";
|
import { LoggingFiles } from "./filewriter";
|
||||||
import { EventEmitter } from "events";
|
import { LoggingBase as LoggingBaseOriginal, LoggingBaseOptions } from "@hibas123/logging";
|
||||||
import * as path from "path";
|
|
||||||
import Lock from "./lock";
|
|
||||||
|
|
||||||
export const Colors = {
|
|
||||||
Reset: "\x1b[0m",
|
|
||||||
Bright: "\x1b[1m",
|
|
||||||
Dim: "\x1b[2m",
|
|
||||||
Underscore: "\x1b[4m",
|
|
||||||
Blink: "\x1b[5m",
|
|
||||||
Reverse: "\x1b[7m",
|
|
||||||
Hidden: "\x1b[8m",
|
|
||||||
|
|
||||||
FgBlack: "\x1b[30m",
|
export interface LoggingOptions extends LoggingBaseOptions {
|
||||||
FgRed: "\x1b[31m",
|
files: boolean | {
|
||||||
FgGreen: "\x1b[32m",
|
/**
|
||||||
FgYellow: "\x1b[33m",
|
* Filename/path of the logfile. Skip if generated with name.
|
||||||
FgBlue: "\x1b[34m",
|
*
|
||||||
FgMagenta: "\x1b[35m",
|
* If not wanted pass null
|
||||||
FgCyan: "\x1b[36m",
|
*/
|
||||||
FgWhite: "\x1b[37m",
|
logfile?: string | null;
|
||||||
|
/**
|
||||||
BgBlack: "\x1b[40m",
|
* Filename/path of the logfile. Skip if generated with name.
|
||||||
BgRed: "\x1b[41m",
|
*
|
||||||
BgGreen: "\x1b[42m",
|
* If not wanted pass null
|
||||||
BgYellow: "\x1b[43m",
|
*/
|
||||||
BgBlue: "\x1b[44m",
|
errorfile?: string | null;
|
||||||
BgMagenta: "\x1b[45m",
|
|
||||||
BgCyan: "\x1b[46m",
|
|
||||||
BgWhite: "\x1b[47m"
|
|
||||||
}
|
|
||||||
|
|
||||||
const maxFileSize = 500000000;
|
|
||||||
|
|
||||||
const OriginalErrorStackFunction = (<any>Error.prototype).prepareStackTrace
|
|
||||||
|
|
||||||
export interface LoggingBaseOptions {
|
|
||||||
/**
|
|
||||||
* Name will be prefixed on Console output and added to logfiles, if not specified here
|
|
||||||
*/
|
|
||||||
name: string,
|
|
||||||
/**
|
|
||||||
* Filename/path of the logfile. Skip if generated with name
|
|
||||||
*/
|
|
||||||
logfile: string;
|
|
||||||
/**
|
|
||||||
* Filename/path of the logfile. Skip if generated with name
|
|
||||||
*/
|
|
||||||
errorfile: string;
|
|
||||||
/**
|
|
||||||
* Prints output to console
|
|
||||||
*/
|
|
||||||
console_out: boolean;
|
|
||||||
}
|
|
||||||
|
|
||||||
class LoggingFiles {
|
|
||||||
private static files: LoggingFiles[] = [];
|
|
||||||
static getFile(filename: string): LoggingFiles {
|
|
||||||
filename = path.resolve(filename);
|
|
||||||
let file = this.files.find(e => e.file === filename);
|
|
||||||
if (!file) {
|
|
||||||
file = new LoggingFiles(filename);
|
|
||||||
this.files.push(file);
|
|
||||||
}
|
|
||||||
return file;
|
|
||||||
}
|
|
||||||
|
|
||||||
private file: string;
|
|
||||||
private size: number = 0;
|
|
||||||
private stream: fs.WriteStream = undefined;
|
|
||||||
private lock = new Lock();
|
|
||||||
private constructor(file: string) {
|
|
||||||
this.file = path.resolve(file);
|
|
||||||
this.init();
|
|
||||||
}
|
|
||||||
|
|
||||||
public async awaitinit() {
|
|
||||||
(await this.lock.getLock()).release();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async init() {
|
|
||||||
let lock = await this.lock.getLock();
|
|
||||||
await this.initializeFile()
|
|
||||||
lock.release();
|
|
||||||
this.checkQueue()
|
|
||||||
}
|
|
||||||
|
|
||||||
private async initializeFile(new_file = false) {
|
|
||||||
try {
|
|
||||||
if (this.stream) {
|
|
||||||
this.stream.close();
|
|
||||||
}
|
|
||||||
const folder = path.dirname(this.file);
|
|
||||||
if (folder) {
|
|
||||||
if (!await fsExists(folder)) {
|
|
||||||
await fsMkDir(folder).catch(() => { }); //Could happen, if two seperate instances want to create the same folder so ignoring
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
let size = 0;
|
|
||||||
if (await fsExists(this.file)) {
|
|
||||||
let stats = await fsStat(this.file);
|
|
||||||
if (new_file || stats.size >= maxFileSize) {
|
|
||||||
if (await fsExists(this.file + ".old"))
|
|
||||||
await fsUnlink(this.file + ".old");
|
|
||||||
await fsMove(this.file, this.file + ".old")
|
|
||||||
} else {
|
|
||||||
size = stats.size;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
this.stream = fs.createWriteStream(this.file, { flags: "a" })
|
|
||||||
this.size = size;
|
|
||||||
} catch (e) {
|
|
||||||
console.log(e);
|
|
||||||
//ToDo is this the right behavior?
|
|
||||||
process.exit(1);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private queue: Buffer[] = [];
|
|
||||||
|
|
||||||
async checkQueue() {
|
|
||||||
if (this.lock.locked) return;
|
|
||||||
let lock = await this.lock.getLock();
|
|
||||||
let msg: Buffer;
|
|
||||||
while (msg = this.queue.shift()) {
|
|
||||||
await this.write_to_file(msg);
|
|
||||||
}
|
|
||||||
lock.release();
|
|
||||||
}
|
|
||||||
|
|
||||||
private async write_to_file(data: Buffer) {
|
|
||||||
try {
|
|
||||||
if (data.byteLength < maxFileSize && this.size + data.byteLength > maxFileSize) {
|
|
||||||
await this.initializeFile(true)
|
|
||||||
}
|
|
||||||
this.size += data.byteLength;
|
|
||||||
this.stream.write(data);
|
|
||||||
} catch (err) {
|
|
||||||
console.error(err);
|
|
||||||
this.initializeFile(false);
|
|
||||||
this.write_to_file(data);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
public write(data: Buffer) {
|
|
||||||
this.queue.push(data);
|
|
||||||
this.checkQueue()
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
export class LoggingBase {
|
export class LoggingBase extends LoggingBaseOriginal {
|
||||||
private config: LoggingBaseOptions;
|
constructor(config: Partial<LoggingOptions> | string = {}) {
|
||||||
|
super(config);
|
||||||
|
|
||||||
private logFile: LoggingFiles;
|
if (typeof config === "string" || config.files !== false) {
|
||||||
private errorFile: LoggingFiles;
|
let logfile: string;
|
||||||
|
let errorfile: string;
|
||||||
constructor(options?: Partial<LoggingBaseOptions> | string) {
|
if (typeof config !== "string" && typeof config.files === "object") {
|
||||||
let opt: Partial<LoggingBaseOptions>;
|
logfile = config.files.logfile;
|
||||||
if (!options) opt = {}
|
errorfile = config.files.errorfile;
|
||||||
else if (typeof options === "string") {
|
|
||||||
opt = { name: options };
|
|
||||||
} else {
|
|
||||||
opt = options;
|
|
||||||
}
|
|
||||||
if (opt.name) {
|
|
||||||
if (opt.logfile === undefined) {
|
|
||||||
opt.logfile = `./logs/all.${opt.name}.log`
|
|
||||||
}
|
}
|
||||||
|
|
||||||
if (opt.errorfile === undefined) {
|
let name = this.name ? "." + this.name : "";
|
||||||
opt.errorfile = `./logs/error.${opt.name}.log`
|
if (!logfile && logfile !== null)
|
||||||
}
|
logfile = `./logs/all${name}.log`;
|
||||||
|
if (!errorfile && errorfile !== null)
|
||||||
|
errorfile = `./logs/error${name}.log`;
|
||||||
|
|
||||||
|
if (logfile)
|
||||||
|
this.addAdapter(new LoggingFiles(logfile));
|
||||||
|
|
||||||
|
|
||||||
|
if (errorfile)
|
||||||
|
this.addAdapter(new LoggingFiles(errorfile, true));
|
||||||
}
|
}
|
||||||
this.config = Object.assign(<LoggingBaseOptions>{
|
|
||||||
name: undefined,
|
|
||||||
console_out: true,
|
|
||||||
logfile: "./logs/all.log",
|
|
||||||
errorfile: "./logs/error.log"
|
|
||||||
}, opt);
|
|
||||||
|
|
||||||
for (let key in this) {
|
|
||||||
if (typeof this[key] === "function") this[key] = (<any>this[key]).bind(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.config.logfile) {
|
|
||||||
this.logFile = LoggingFiles.getFile(this.config.logfile);
|
|
||||||
}
|
|
||||||
|
|
||||||
if (this.config.errorfile) {
|
|
||||||
this.errorFile = LoggingFiles.getFile(this.config.errorfile);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
get console_out() {
|
|
||||||
return this.config.console_out;
|
|
||||||
}
|
|
||||||
|
|
||||||
set console_out(value: boolean) {
|
|
||||||
this.config.console_out = value;
|
|
||||||
}
|
|
||||||
|
|
||||||
public waitForSetup() {
|
|
||||||
let w = [];
|
|
||||||
if (this.logFile) w.push(this.logFile.awaitinit());
|
|
||||||
if (this.errorFile) w.push(this.errorFile.awaitinit());
|
|
||||||
return Promise.all(w)
|
|
||||||
}
|
|
||||||
|
|
||||||
public events: EventEmitter = new EventEmitter();
|
|
||||||
|
|
||||||
debug(...message: any[]) {
|
|
||||||
this.message(LoggingTypes.Debug, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
log(...message: any[]) {
|
|
||||||
this.message(LoggingTypes.Log, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
warning(...message: any[]) {
|
|
||||||
this.message(LoggingTypes.Warning, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
logWithCustomColors(type: LoggingTypes, colors: string, ...message: any[]) {
|
|
||||||
this.message(type, message, colors);
|
|
||||||
}
|
|
||||||
|
|
||||||
error(error: Error | string) {
|
|
||||||
if (!error) error = "Empty ERROR was passed, so no informations available";
|
|
||||||
if (typeof error === "string") {
|
|
||||||
let e = new Error()
|
|
||||||
this.message(LoggingTypes.Error, [error, "\n", e.stack]);
|
|
||||||
} else {
|
|
||||||
this.message(LoggingTypes.Error, [error.message, "\n", error.stack], undefined, getCallerFromExisting(error));
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
errorMessage(...message: any[]) {
|
|
||||||
this.message(LoggingTypes.Error, message);
|
|
||||||
}
|
|
||||||
|
|
||||||
private message(type: LoggingTypes, message: any[] | string, customColors?: string, caller?: { file: string, line: number }) {
|
|
||||||
var consoleLogFormat = Colors.Reset;
|
|
||||||
if (!customColors) {
|
|
||||||
switch (type) {
|
|
||||||
case LoggingTypes.Log:
|
|
||||||
//m += FgWhite + BgBlack;
|
|
||||||
break;
|
|
||||||
case LoggingTypes.Error:
|
|
||||||
consoleLogFormat += Colors.FgRed;//FgWhite + BgRed + FgWhite;
|
|
||||||
break;
|
|
||||||
case LoggingTypes.Debug:
|
|
||||||
consoleLogFormat += Colors.FgCyan;
|
|
||||||
break;
|
|
||||||
case LoggingTypes.Warning:
|
|
||||||
consoleLogFormat += Colors.FgYellow;
|
|
||||||
break;
|
|
||||||
}
|
|
||||||
} else {
|
|
||||||
consoleLogFormat += customColors;
|
|
||||||
}
|
|
||||||
var mb = "";
|
|
||||||
if (typeof message === "string") {
|
|
||||||
mb = message;
|
|
||||||
} else {
|
|
||||||
message.forEach((e, i) => {
|
|
||||||
if (typeof e !== "string") e = util.inspect(e, false, null);
|
|
||||||
if (e.endsWith("\n") || i === message.length - 1) {
|
|
||||||
mb += e;
|
|
||||||
} else {
|
|
||||||
mb += e + " ";
|
|
||||||
}
|
|
||||||
});
|
|
||||||
}
|
|
||||||
let file = caller || getCallerFile();
|
|
||||||
let date = new Date().toISOString().replace(/T/, ' ').replace(/\..+/, '');
|
|
||||||
let prefix = `[ ${date} ][${LoggingTypes[type].toUpperCase()}][${file.file}:${String(file.line).padEnd(3, " ")}]: `;
|
|
||||||
let message_lines = mb.split("\n").map(line => prefix + line);
|
|
||||||
|
|
||||||
if (this.config.console_out) {
|
|
||||||
let name = "";
|
|
||||||
if (this.config.name) name = `[${this.config.name}]=>`;
|
|
||||||
message_lines.forEach(line => console.log(consoleLogFormat + name + line + Colors.Reset));
|
|
||||||
}
|
|
||||||
|
|
||||||
let m = message_lines.join("\n");
|
|
||||||
|
|
||||||
m = m.replace(/[\u001b\u009b][[()#;?]*(?:[0-9]{1,4}(?:;[0-9]{0,4})*)?[0-9A-ORZcf-nqry=><]/g, "");
|
|
||||||
|
|
||||||
let index = m.indexOf("\x1b");
|
|
||||||
while (index >= 0) {
|
|
||||||
m = m.substring(0, index) + m.substring(index + 5, m.length);
|
|
||||||
index = m.indexOf("\x1b");
|
|
||||||
}
|
|
||||||
|
|
||||||
let data = Buffer.from(m + "\n")
|
|
||||||
if (type === LoggingTypes.Error && this.errorFile) {
|
|
||||||
this.errorFile.write(data);
|
|
||||||
}
|
|
||||||
if (this.logFile) {
|
|
||||||
this.logFile.write(data);
|
|
||||||
}
|
|
||||||
this.events.emit("message", { type: type, message: m, module: this.config.name });
|
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
@ -313,140 +54,5 @@ if (process.env.LOGGING_NO_DEFAULT !== "true") {
|
|||||||
}
|
}
|
||||||
export default Logging;
|
export default Logging;
|
||||||
|
|
||||||
function fsUnlink(path) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
fs.unlink(path, (err) => {
|
|
||||||
if (err) reject(err);
|
|
||||||
else resolve();
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function fsStat(path: string) {
|
|
||||||
return new Promise<fs.Stats>((resolve, reject) => {
|
|
||||||
fs.stat(path, (err, stats) => {
|
|
||||||
if (err) reject(err);
|
|
||||||
else resolve(stats);
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function fsMove(oldPath: string, newPath: string) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
let callback = (err?) => {
|
|
||||||
if (err) reject(err)
|
|
||||||
else resolve()
|
|
||||||
}
|
|
||||||
|
|
||||||
fs.rename(oldPath, newPath, function (err) {
|
|
||||||
if (err) {
|
|
||||||
if (err.code === 'EXDEV') {
|
|
||||||
copy();
|
|
||||||
} else {
|
|
||||||
callback(err)
|
|
||||||
}
|
|
||||||
return;
|
|
||||||
}
|
|
||||||
callback()
|
|
||||||
});
|
|
||||||
|
|
||||||
function copy() {
|
|
||||||
fs.copyFile(oldPath, newPath, (err) => {
|
|
||||||
if (err) callback(err)
|
|
||||||
else fs.unlink(oldPath, callback);
|
|
||||||
})
|
|
||||||
// var readStream = fs.createReadStream(oldPath);
|
|
||||||
// var writeStream = fs.createWriteStream(newPath);
|
|
||||||
|
|
||||||
// readStream.on('error', callback);
|
|
||||||
// writeStream.on('error', callback);
|
|
||||||
|
|
||||||
// readStream.on('close', function () {
|
|
||||||
// fs.unlink(oldPath, callback);
|
|
||||||
// });
|
|
||||||
|
|
||||||
// readStream.pipe(writeStream);
|
|
||||||
}
|
|
||||||
})
|
|
||||||
}
|
|
||||||
|
|
||||||
function fsExists(path: string) {
|
|
||||||
return new Promise<boolean>((resolve, reject) => {
|
|
||||||
fs.exists(path, resolve);
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function fsMkDir(path: string) {
|
|
||||||
return new Promise((resolve, reject) => {
|
|
||||||
fs.mkdir(path, (err) => err ? reject(err) : resolve());
|
|
||||||
});
|
|
||||||
}
|
|
||||||
|
|
||||||
function getStack() {
|
|
||||||
// Save original Error.prepareStackTrace
|
|
||||||
let origPrepareStackTrace = (<any>Error).prepareStackTrace;
|
|
||||||
|
|
||||||
// Override with function that just returns `stack`
|
|
||||||
(<any>Error).prepareStackTrace = function (_, stack) {
|
|
||||||
return stack
|
|
||||||
}
|
|
||||||
|
|
||||||
// Create a new `Error`, which automatically gets `stack`
|
|
||||||
let err = new Error();
|
|
||||||
|
|
||||||
// Evaluate `err.stack`, which calls our new `Error.prepareStackTrace`
|
|
||||||
let stack: any[] = <any>err.stack;
|
|
||||||
|
|
||||||
// Restore original `Error.prepareStackTrace`
|
|
||||||
(<any>Error).prepareStackTrace = origPrepareStackTrace;
|
|
||||||
|
|
||||||
// Remove superfluous function call on stack
|
|
||||||
stack.shift(); // getStack --> Error
|
|
||||||
|
|
||||||
return stack
|
|
||||||
}
|
|
||||||
|
|
||||||
function getCallerFile() {
|
|
||||||
try {
|
|
||||||
let stack = getStack()
|
|
||||||
|
|
||||||
let current_file = stack.shift().getFileName();
|
|
||||||
|
|
||||||
while (stack.length) {
|
|
||||||
let caller_file = stack.shift();
|
|
||||||
const util = require("util")
|
|
||||||
if (current_file !== caller_file.getFileName())
|
|
||||||
return {
|
|
||||||
file: path.basename(caller_file.getFileName()),
|
|
||||||
line: caller_file.getLineNumber()
|
|
||||||
};
|
|
||||||
}
|
|
||||||
} catch (err) { }
|
|
||||||
return { file: undefined, line: 0 };
|
|
||||||
}
|
|
||||||
|
|
||||||
function getCallerFromExisting(err: Error): { file: string, line: number } {
|
|
||||||
if (!err || !err.stack) return { file: "NOFILE", line: 0 };
|
|
||||||
let lines = err.stack.split("\n");
|
|
||||||
let current = path.basename(__filename);
|
|
||||||
lines.shift();// removing first line
|
|
||||||
while (lines.length > 0) {
|
|
||||||
let line = lines.shift();
|
|
||||||
let matches = line.match(/[a-zA-Z_-]+[.][a-zA-Z_-]+[:][0-9]+/g)
|
|
||||||
if (matches && matches.length > 0) {
|
|
||||||
let [f, line] = matches[0].split(":")
|
|
||||||
if (f != current) {
|
|
||||||
return {
|
|
||||||
file: f, line: Number(line)
|
|
||||||
};
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
export enum LoggingTypes {
|
|
||||||
Log,
|
|
||||||
Warning,
|
|
||||||
Error,
|
|
||||||
Debug
|
|
||||||
}
|
|
36
src/lock.ts
36
src/lock.ts
@ -1,36 +0,0 @@
|
|||||||
export type Release = { release: () => void };
|
|
||||||
export default class Lock {
|
|
||||||
private _locked: boolean = false;
|
|
||||||
get locked() {
|
|
||||||
return this._locked;
|
|
||||||
}
|
|
||||||
private toCome: (() => void)[] = [];
|
|
||||||
|
|
||||||
constructor() {
|
|
||||||
this.release = this.release.bind(this);
|
|
||||||
}
|
|
||||||
|
|
||||||
async getLock(): Promise<Release> {
|
|
||||||
if (!this._locked) return { release: this.lock() };
|
|
||||||
else {
|
|
||||||
return new Promise<Release>((resolve) => {
|
|
||||||
this.toCome.push(() => {
|
|
||||||
resolve({ release: this.lock() });
|
|
||||||
})
|
|
||||||
})
|
|
||||||
}
|
|
||||||
}
|
|
||||||
|
|
||||||
private lock() {
|
|
||||||
this._locked = true;
|
|
||||||
return this.release;
|
|
||||||
}
|
|
||||||
|
|
||||||
private async release() {
|
|
||||||
if (this.toCome.length > 0) {
|
|
||||||
this.toCome.shift()();
|
|
||||||
} else {
|
|
||||||
this._locked = false;
|
|
||||||
}
|
|
||||||
}
|
|
||||||
}
|
|
30
src/test.ts
30
src/test.ts
@ -1,5 +1,22 @@
|
|||||||
import { Logging, LoggingBase } from "./index";
|
|
||||||
import { randomBytes } from "crypto";
|
import { randomBytes } from "crypto";
|
||||||
|
import * as fs from "fs";
|
||||||
|
import { Logging, LoggingBase } from ".";
|
||||||
|
|
||||||
|
const deleteFolderRecursive = function (path: string) {
|
||||||
|
if (fs.existsSync(path)) {
|
||||||
|
fs.readdirSync(path).forEach(function (file, index) {
|
||||||
|
var curPath = path + "/" + file;
|
||||||
|
if (fs.lstatSync(curPath).isDirectory()) { // recurse
|
||||||
|
deleteFolderRecursive(curPath);
|
||||||
|
} else { // delete file
|
||||||
|
fs.unlinkSync(curPath);
|
||||||
|
}
|
||||||
|
});
|
||||||
|
fs.rmdirSync(path);
|
||||||
|
}
|
||||||
|
};
|
||||||
|
|
||||||
|
deleteFolderRecursive("./logs")
|
||||||
|
|
||||||
Logging.log("test")
|
Logging.log("test")
|
||||||
Logging.log("i", "am", { a: "an" }, 1000);
|
Logging.log("i", "am", { a: "an" }, 1000);
|
||||||
@ -30,17 +47,20 @@ cus2.log("Hello from custom Logger 2")
|
|||||||
cus22.log("Hello from custom Logger 22")
|
cus22.log("Hello from custom Logger 22")
|
||||||
cus2.log("Hello from custom Logger 2")
|
cus2.log("Hello from custom Logger 2")
|
||||||
|
|
||||||
Logging.console_out = false;
|
const BenchmarkLogger = new LoggingBase({
|
||||||
|
console: false,
|
||||||
|
name: "bench"
|
||||||
|
})
|
||||||
async function benchmark(count: number, message_size: number) {
|
async function benchmark(count: number, message_size: number) {
|
||||||
await Logging.waitForSetup();
|
await BenchmarkLogger.waitForSetup();
|
||||||
const randData = randomBytes(message_size).toString("hex")
|
const randData = randomBytes(message_size).toString("hex")
|
||||||
const t = process.hrtime();
|
const t = process.hrtime();
|
||||||
for (let i = 0; i < count; i++) {
|
for (let i = 0; i < count; i++) {
|
||||||
Logging.log(randData)
|
BenchmarkLogger.log(randData)
|
||||||
}
|
}
|
||||||
const diff = process.hrtime(t);
|
const diff = process.hrtime(t);
|
||||||
const NS_PER_SEC = 1e9;
|
const NS_PER_SEC = 1e9;
|
||||||
await Logging.waitForSetup();
|
await BenchmarkLogger.waitForSetup();
|
||||||
const ns = diff[0] * NS_PER_SEC + diff[1];
|
const ns = diff[0] * NS_PER_SEC + diff[1];
|
||||||
console.log(`Benchmark took ${ns / 1000000}ms for ${count} messages with a size of ${message_size} characters`);
|
console.log(`Benchmark took ${ns / 1000000}ms for ${count} messages with a size of ${message_size} characters`);
|
||||||
console.log(`This is equal to ${(ns / 1000000) / count} ms per message`)
|
console.log(`This is equal to ${(ns / 1000000) / count} ms per message`)
|
||||||
|
Reference in New Issue
Block a user