-
Notifications
You must be signed in to change notification settings - Fork 1
/
server_logger.js
88 lines (80 loc) · 2.54 KB
/
server_logger.js
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
'use strict'
var path = require( 'path' );
var fs = require( 'fs-extra' );
var parse = require( 'date-fns/parse' );
var format = require( 'date-fns/format' );
const root = path.resolve();
const dgram = require( 'dgram' );
const serverUdpShake = dgram.createSocket( 'udp4' );
const serverUdpWeb = dgram.createSocket( 'udp4' );
const dateFormat = 'YYYY-MM-DDTHH:mm:ss.SSS';
const filenameDateFormat = 'YYYYMMDDHH';
var serverSettings = openJsonSync( 'serverLoggerSettings.json' );
var udpPortServerWeb = serverSettings.udpPortServerWeb;
var udpPortShake = serverSettings.udpPortShake;
function sendUpdateToServerWeb( whichStream, msg ) {
let data = JSON.stringify( { whichStream: whichStream, message: msg } );
serverUdpWeb.send( data, udpPortServerWeb, ( err ) => {
} );
}
serverUdpShake.on( 'error', ( err ) => {
serverUdpShake.close();
} );
serverUdpShake.on( 'listening', () => {
} );
serverUdpShake.on( 'message', ( msg, rinfo ) => {
msg = `${ msg }`;
msg = removeBraces( msg );
msg = removeSingleQuotes( msg );
msg = msg.trimStart().split( ',' );
let whichStream = whichDataStream( msg );
rawAppend( msg );
sendUpdateToServerWeb( whichStream, msg );
} );
serverUdpShake.bind( udpPortShake );
function rawAppend( msg ) {
let dataType = msg[ 0 ];
msg = removeDataType( msg );
msg[ 0 ] = fixEpoch( msg[ 0 ] );
let file = getFilenameDate( msg[ 0 ] ) + '_' + dataType + '.log';
msg[ 0 ] = reformatEpoch( msg[ 0 ] );
appendNewLine( msg, file );
}
function whichDataStream( msg ) {
return msg[ 0 ];
}
function openJsonSync( fileName ) {
let file = path.join( root, fileName );
fs.ensureFileSync( file );
return fs.readJsonSync( file );
}
function removeBraces( data ) {
return data.replace( /[{}]/g, '' );
}
function removeSingleQuotes( data ) {
return data.replace( /'/g, '' );
}
function removeDataType( data ) {
return data.slice( 1 );
}
function fixEpoch( data ) {
return ( data * 1000 );
}
function reformatEpoch( data ) {
return format( parse( data ), dateFormat );
}
function getFilenameDate( data ) {
return format( parse( data ), filenameDateFormat );
}
function appendNewLine( data, filename ) {
let file = path.join( root, 'logs', filename );
fs.ensureFile( file ).then(
() => {
fs.appendFile( file, data + '\n', function ( err ) { } );
}
)
}
process.on( 'uncaughtException', function ( err ) {
var message = err.message;
console.log( err );
} )