Thursday, February 2, 2017

Vertx: How to write log file using JavaScript

For those who  are not familiar with Vertx- its tool-kit for building reactive applications on the JVM.
It make sense to start with introduction  to Vertx, but  it's already done by many other  guys in internet. I'll share here   few  code snippets that I wrote  using Vertx in JavaScript.
I would like to admit one important  thing: Vertx runs on JVM- which means- we can get access to entire Java ecosystem from any language that supported by Vertx.
Now let's  get back to our main topic: how to write log file  using Vertx in JavaScript?
Here is code snippet of mylog.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
var fw = null;//log file handler
var logFile=null;

var $logEnabled=null;
var $logPath=null;
var $maxLogFileSize=null;

//create Text file using java.io.FileWriter and java.io.File
this.createLogFile =function(){
var FileWriter=Java.type("java.io.FileWriter"); 
 fw = new FileWriter($logPath);
 
var File= Java.type("java.io.File");
 logFile=new File($logPath);
}

function closeLogFile(){
 fw.close();
}

//write to log file
function append(msg){ 
 
 var curDate=new Date();
 msg=curDate+':'+msg;
 
 var fileSize=logFile.length();
 console.log('file size='+fileSize);
 if(fileSize>$maxLogFileSize){ //rotation for log file based on size value
  console.log('rewrite file from scratch');
  closeLogFile();//close file
  createLogFileHandler()//recreate file
  fw.write(msg);
  fw.write("\n");
 }
 else
 {
  fw.append(msg);
  fw.append("\n");
 }
 fw.flush();  
}

//set initial values to variables
this.construct= function(){
 $logEnabled=true;
 $logPath="/var/tmp/test.log";
 $maxLogFileSize=1000000;
}

//public method available from main program
this.log=function(msg){
 msg=msg.toString()+'\n ';
 
 if($logEnabled){  
  if($logPath!==null){      
   appendToExistingLogFile(msg);
  }
  else
   console.log("log file path is not defined- unable to  write into file");  
 }
 else 
  console.log(msg);
}
 

We have to include mylog.js file in main application to start using it.


1
2
3
4
5
6
7
require("mylog.js");

construct();

createLogFile();

log("Hello world");


Pretty simple.