-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathserver.js
More file actions
68 lines (59 loc) · 1.83 KB
/
server.js
File metadata and controls
68 lines (59 loc) · 1.83 KB
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
const dgram = require('dgram');
var fs = require('fs');
var mkdirp = require('mkdirp');
const DEFAULT_FILENAME = "errors.log";
const socket = dgram.createSocket('udp4');
function Server(host, port){
this.host = host;
this.port = port;
}
Server.prototype.addTransports = function(directory){
const lastCharacter = directory.charAt(directory.length - 1);
this.directory = directory;
if(lastCharacter !== '/')
this.directory = this.directory + "/";
mkdirp(this.directory, function (err) {
if (err) console.error(err);
else console.log("Transports have been created!");
});
}
function writeLog(message, directory, filename = DEFAULT_FILENAME){
fs.appendFile( directory + filename, message, function (err) {
if(err) console.log("error" + err);
});
}
function makeLog(log){
const level = log['level'];
const message = log['message'];
const timestamp = log['timestamp'];
return JSON.stringify({
"level" : level,
"message" : message,
"timestamp" : timestamp
}) + "\n";
}
function createLogFileFromCategory(category){
const filename = category + ".log";
return filename;
}
Server.prototype.listen = function(){
socket.on('message', (msg, rinfo) => {
msgJSON = JSON.parse(msg.toString('utf8'));
const log = makeLog(msgJSON);
if(msgJSON.hasOwnProperty('category')){
const filename = createLogFileFromCategory(msgJSON['category']);
writeLog(log, this.directory, filename);
}else{
writeLog(log, this.directory);
}
});
socket.on('listening', () => {
const address = socket.address();
console.log(`Listening on port ${address.port}`);
});
socket.bind({
address: this.host,
port: this.port
});
}
module.exports = Server;