LoggerCLS

Lets you easily use log files

This generic class is very usefull if you have to create log files.
Just copy/paste this code to use it, or include it like this : <script language="JScript" src="Lib\LoggerCLS.js"/>
Best used in wsf files.

File Name : LoggerCLS.js
Requirement : none
Author : Branimir Petrovic
Submitted : 03/09/2001
Category : Class

To use a class, follow this syntax :
var MyObjClass = new MyClass;
WScript.Echo(MyObjClass.MyMethod());
//	FileName:	LoggerCLS(sFQfN, DEBUG, TIME).js
//////////////////////////////////////////////////////////////////////
if (WScript.ScriptName == "LoggerCLS.js") demoLogger(); 

// ======================== CLASS ====================================
function LoggerCLS(sFQfN, DEBUG, TIME) {

//	Author:		Branimir Petrovic
//	Date:		15 August 2001
//
//	Depends on:	acces to "flashMessage(sMsg, nTime, sTitl, Type).js" global function	
//
//	Methods:	- getClassName()			Returns string "LoggerCLS"
//				- setLogName(sName) 		Will change log file name from current name to "sName"
//											(default name is "LoggerCLS(sFQfN, DEBUG, TIME).log")  
//				- renameUsingTimeStamp() 	Will add time stamp to existing log file name 
//											"activity_YYYYMMDD_hhmmss.log
//				- Write(sLine, fTimeStamp, nLeftMargine) 
//											Last two params are optional;
//											if fTimeStamp omitted, time stamp will be added to the beginning of line
//											if nLeftMargine omitted, left margine starts at 0
//				- WriteBlankLines(nNumber) 	Will write nNumber of blank lines to log
//				- ReadAll() 				Returns string containing the whole log file
//
//
//  NOTE:	"sFQfN", "DEBUG" and "TIME" are all optional parameters 
//
//				"sFQfN" is fully qualified name to log file
//				"DEBUG" when true will cause debug messages to pop up, so you can see what's cookin'
//				"TIME" will determine how many seconds debug messages will be visible
//
//				If "sFQfN" is missing - sLogFQfN is set to point to %ScriptPath%\history\%SciptName%.log
//				If DEBUG is missing fDebug is set to default value - false
//				If TIME is missing, nTime is set to default value of 1 Sec
//
//			By intention this class tries to create sLogFldr very early, if it fails to do so
//				(and it can fail due to lack of permissions), the whole script is aborted
//				on a pretext of no point in running the script when its actions can not be logged.


	String.prototype.trim = function () { return this.replace(/(^\s*)|(\s*$)/g, ""); }


	//	--- Private Data Members ---
	var SELF = "LoggerCLS";
	var sMsg;
	var sTitl;
	var oFSO = new ActiveXObject("Scripting.FileSystemObject");	

	var fDebug = false;		//	false by default (true will cause debug messages to flash)
	var nTime = 1;			//	1 Sec by default (debug messages will flash nTime seconds)
	var sLogFQfN;

	var sScriptPath;
	var sLogFldr = "history"; // set this to "" if you do not want to log into subfolder
	var sLogName;


	//	---	Public Methods ---
	this.getClassName = function () {return SELF; }
	this.setLogName = setLogName;
	this.renameUsingTimeStamp = renameUsingTimeStamp;
	this.Write = Write;
	this.WriteBlankLines = WriteBlankLines;
	this.ReadAll = ReadAll;

	
	//	--- "LoggerCLS" Constructor ---
	if (typeof(DEBUG) != "undefined") fDebug = DEBUG;
	if (typeof(TIME) != "undefined") setTimeout(TIME);
	
	if (typeof(sFQfN) == "undefined") {
		setDefaults();
	} else if (isFQfN(sFQfN)) {
		//	passed string has proper "Fully Qualified file Name" format
		if ( oFSO.DriveExists(oFSO.GetDriveName(sFQfN)) ) {
			// make sure that drive name really exists 
			//	(if drive name exists - all other folders in sFQfN can be created)
			sLogFQfN = sFQfN;
			sScriptPath = oFSO.GetParentFolderName(WScript.ScriptFullName);
			sLogName = oFSO.GetFileName(sLogFQfN);
			if (createFolder(oFSO.GetParentFolderName(sLogFQfN))) {
				if (fDebug) {  
					flashMessage("\"" + sLogFQfN + "\"", nTime , 
					"Consturctor \"LoggerCLS(sFQfN, DEBUG, TIME)\" have set sLogFQfN to:", "I");
				}
			}
			
		} else {
			setDefaults(); 
		}
	
	} else {
		setDefaults();
	}
	
	return;	//	>>> --- End of Consturctor --- >>>


	//	---------------- Functions Implementing Public Methods -------
	function setLogName(sName) {
		//	Sets (or changes) name of the log file.
		
		if (typeof(sName) == "undefined") return;
		
		sLogName = sName;
		var sTmp = oFSO.GetParentFolderName(sLogFQfN);
		var sNewLogFQfN = oFSO.BuildPath(sTmp, sName);
		
		if ( (oFSO.FileExists(sLogFQfN))&&(sLogFQfN!=sNewLogFQfN) ) {
			// will rename existing log file
			try {
				oFSO.GetFile(sLogFQfN).Name = sName;
			} catch (e) {
				// for some reason renaming failed, pause 1 Sec & try again
				WScript.Sleep(1000);
				try {
					flashMessage("Second attempt to rename LOG file to:\n\n" + sName,
								 60, SELF + "::setLogName()", "E");
					oFSO.GetFile(sLogFQfN).Name = sName;
				} catch (e) {
					//	will record error condition to "error.log"				
					var sParentFQFN = oFSO.GetParentFolderName(sName);
					var sErrorFQfN = oFSO.BuildPath(sParentFQFN, "error.log");
					var FOR_APPENDING = 8;
					var oErrLog = oFSO.OpenTextFile(sErrorFQfN, FOR_APPENDING, true)
					var sLine = getNow() + "\tFailed to rename \"" + oFSO.GetFileName(sLogFQfN) + 
								"\" to \"" +  oFSO.GetFileName(sName) + "\" due to:\r\n";
					sLine += "\t\t\t\t\"" + e.description + "\"\r\n";		
					oErrLog.Write(sLine);
					oErrLog.Close();		
					return;				//	>>>>>
				}
			}	
		}
		
		sLogFQfN = sNewLogFQfN;
		
		if (fDebug) {  
			flashMessage("\"" + sLogFQfN + "\"", nTime, SELF + "::setLogName(\"" + sName + "\")", "I");
		}
		
	}
	//	--------------------------------------------------------------	
	function renameUsingTimeStamp() {
		// adds time stamp to existin log file name
		// (Like: "activity_YYYYMMDD_hhmmss.log")
		
		if (!oFSO.FileExists(sLogFQfN)) return;	//	>>>
	
		var sBaseName = oFSO.GetBaseName(sLogFQfN);
		var sExtName = oFSO.GetExtensionName(sLogFQfN);
		setLogName(sBaseName + getTimeStamp() + "." + sExtName);
	}	
	//	--------------------------------------------------------------
	function Write(sLine, fTimeStamp, nLeftMargine) {
	    //	Will append "sLine" to existing (or newely created) log file; 
		//		if sLine == "" or is missing, new empty line is added 
		//
		//	nLeftMargine is optional parameter defining where will the left margine start;
		//		if missing, nLeftMargine == 0
		//
		//	fTimeStamp is optional parameter; 
		//		if missing, timestamp will be added to every new line (except to the empty ones), 
		//		if false, there will be no timestamp
		//	

		if (typeof(sLine)=="undefined") return;		//	>>>

		var sMsg;
		var sTitl;
		var fTime = (typeof(fTimeStamp) == "undefined") ? true : fTimeStamp
		var nLeftM = (typeof(nLeftMargine) == "undefined") ? 0 : nLeftMargine;
		if (nLeftM>60) nLeftM = 30; //	left margine limited to 30
			
		var sLN = leftJustify("", nLeftM);	//	pads margine with " "
		var TIMESTAMP_LENGTH = 30;
		if (fTime) sLN += leftJustify(getNow(), TIMESTAMP_LENGTH); 
		var nShift = sLN.toString().length;
		
		if (sLine!="") {
			var sAry = new Array();

			if (sLine.indexOf("\r\n")!=-1) {
				// "\r\n" is in the passed line, brake it up to separate lines
				sAry = sLine.split("\r\n");   
			}	else if (sLine.indexOf("\n")!=-1) {
				// "\n" is in the passed line, brake it up to separate lines
			    sAry = sLine.split("\n");
			}

			if (sAry.length>1) {
			    for (var i=0; i<sAry.length; i++) {
					if (i==0) {
						// text starts from nShift position, before that there is a time stamp and left margine
						sLN += leftJustify(sAry[i], nShift) + "\r\n";
						continue;
					}
					// text is starts from nShift position, up to nShift padded with " "
			        sLN += leftJustify("", nShift) + leftJustify(sAry[i], nShift) + "\r\n";
			    }
			} else {
			    sLN += sLine + "\r\n";
			}
		}
		var FOR_APPENDING = 8;
		try {
			var oTxt = oFSO.OpenTextFile(sLogFQfN, FOR_APPENDING, true)
			oTxt.Write(sLN);
			oTxt.Close();
			oTxt = null;
			return;				//	>>>>>
		} catch(e) {
			sTitl = "LoggerCLS::Write(sLine, fTimeStamp, nLeftMargine)";
			sMsg = "File: \n\n\"" + sLogFQfN +"\"\n\nCould not be written to (see why)!";
			flashMessage(sMsg, 0, sTitl, "C");
			WScript.Quit();		// >>>>> ABORTING SCRIPT >>>>>
		} 



		function leftJustify(sStr, nCellWidth) {
			// Will pad with " " to nCellWidth and left justify passed string  
			var nDelta = nCellWidth - sStr.toString().length;
			if (nDelta>0) sStr = sStr + new Array(nDelta+1).join(" ");    
			return sStr;		//	>>>
		}	
	}
	//	--------------------------------------------------------------
	function WriteBlankLines(nNumber) {
		var sTitl;
		var sMsg;
		var FOR_APPENDING = 8;
		try {
			var oTxt = oFSO.OpenTextFile(sLogFQfN, FOR_APPENDING, true)
			if (typeof(nNumber)=="undefined") {
			    oTxt.WriteBlankLines(1);
				oTxt.Close();
			} else {
			    oTxt.WriteBlankLines(nNumber);
				oTxt.Close();
			}
		} catch(e) {
			sTitl = "LoggerCLS::WriteBlankLines(" + nNumber + ")";
			sMsg = "File: \n\n\"" + sLogFQfN +"\"\n\nCould not be written to (see why)!";
			flashMessage(sMsg, 0, sTitl, "C");
			WScript.Quit();		// >>>>> ABORTING SCRIPT >>>>>
		} 
	}	
	//	--------------------------------------------------------------
	function ReadAll() {
		var FOR_READING = 1;
		if (!oFSO.FileExists(sLogFQfN)) return "";	//	>>>
		
		try {
			var oTxt = oFSO.OpenTextFile(sLogFQfN, FOR_READING);
			return oTxt.ReadAll();					// 	>>>
		} catch (e) {
			sTitl = "LoggerCLS::ReadAll()";
			sMsg = "File: \n\n\"" + sLogFQfN +"\"\n\nCould not be read (see why)!";
			flashMessage(sMsg, 0, sTitl, "E");
		}
			
			return "";								//	>>>
	}	//	----------------------------------------------------------
	

	//	---------------- Helper Functions ----------------------------
	function setTimeout(nT) { nTime = (nT>60)? 0: nT; }
	//	--------------------------------------------------------------
	function setDefaults() {
		//  initializes three private vars to default values
	    sScriptPath = oFSO.GetParentFolderName(WScript.ScriptFullName);
		sLogName = oFSO.GetBaseName(WScript.ScriptFullName) + ".log";
		sLogFQfN = oFSO.BuildPath(oFSO.BuildPath(sScriptPath, sLogFldr), sLogName);
		if (createFolder(oFSO.GetParentFolderName(sLogFQfN))) {
			if (fDebug) {  
				flashMessage("\"" + sLogFQfN + "\"", nTime , 
					"Constructor \"LoggerCLS()\" have set sLogFQfN to:", "I");
			}
		}
	}
	//	--------------------------------------------------------------
	function isFQfN(sFQfN) {
		//	Will return true if passed string is in fully qualified file name format
		//		(will NOT try to find out and confirm if file really exists)
		//
		//	Will match ONLY LOCAL PATH: C:\myfile.ext OR
		//								C:\MyFldr1\ ... \myfile.ext
		re = /^[A-Za-z]:\(?:[^\*/\?<>\|]+\)*(?:[^\*/\?<>\|]+\.[^\*/\?<>\|]+)$/;	
		return (re.test(sFQfN)==true) ? true : false	//	>>>
	}
	//	--------------------------------------------------------------
	function getTimeStamp() {
		//	returns date as _20010808_174905
		var oDate = new Date();
		var sNow =  "_" + oDate.getFullYear();
		sNow += padWithZero(oDate.getMonth()+1);
		sNow += padWithZero(oDate.getDate());
		sNow += "_" + padWithZero(oDate.getHours());
		sNow += padWithZero(oDate.getMinutes());
		sNow += padWithZero(oDate.getSeconds());
		return sNow;		
	}	
	//	--------------------------------------------------------------
	function getNow() {
		// duplicates VBScript's getNow() functionality, returns string
		var oDate = new Date();
		var sNow =  padWithZero(oDate.getDate());
		sNow += " " + toNamedMonth(oDate.getMonth()+1); 
		sNow += " " + oDate.getFullYear() + "  ";
		sNow += padWithZero(oDate.getHours()) + ":";
		sNow += padWithZero(oDate.getMinutes()) + ":";
		sNow += padWithZero(oDate.getSeconds());
		return sNow; // >>>
	}	
	//	--------------------------------------------------------------
	function toNamedMonth(iMonth) {
		switch (iMonth) {
			case 1: return "January";
			case 2: return "February";
			case 3: return "March";
			case 4: return "April";
			case 5: return "May";
			case 6: return "Jun";
			case 7: return "July";
			case 8: return "August";
			case 9: return "September";
			case 10: return "October";
			case 11: return "November";
			case 12: return "December";
			default: return iMonth;
		}
	}
	//	--------------------------------------------------------------	
	function padWithZero(iNum) {
		if (iNum<10) iNum = "0" + iNum;
		return iNum;
	}	
	//	--------------------------------------------------------------
	function createFolder(FQFP) {
	//	will create FQFP (node by node) if it does not exist, 

		if (oFSO.FolderExists(FQFP)) return;	//	>>>
		var sAry = FQFP.split("\");
		for (var i=0; i<sAry.length; i++) {
			if (i==0) { var sPath = sAry[i] + "\"; continue; }
			sPath = oFSO.BuildPath(sPath, sAry[i]);
			if (!oFSO.FolderExists(sPath)) {
				try {
					oFSO.CreateFolder(sPath);
				} catch(e) {
					sTitl = "Could NOT Create Folder";
					sMsg =  "Failed to create: \t\"" + sSrc + "\"\n\r\n\r";
					sMsg += "\tCheck your NTFS permissions! \n\r\n\r\tABORTING SCRIPT";
					flashMessage(sMsg, 0, sTitl, "STOP");
					WScript.Quit();		//	>>>>> ABORTING SCRIPT >>>>>
				} 
			}
		}
		sTitl = "LoggerCLS's Private Function:   createFolder(\"" + FQFP + "\")";;
		if (fDebug) flashMessage("Just created: \n\r\n\r" + FQFP, nTime, sTitl, "INFORMATION");
		return true;
	}	//	--- end of function createFolder() 
}	// ======================== END OF CLASS =========================


//	==================================================================
function demoLogger() {
	var oLog = new LoggerCLS();
	oLog.setLogName("activity.log");			
	//oLog.WriteBlankLines(1);
	oLog.Write("LoggerCLS >>> Just a plain simple demo...\nMore stuff,\nand some more.");
	oLog.setLogName("DailyActivity.log");	// 	log file name can be changed any time
	oLog.renameUsingTimeStamp();			//	appends timestamp to log file name
	WScript.Echo(oLog.ReadAll());
	
	oLog = null;
}
//	==================================================================
Server Info
Remote Info
Compress

Batchs
BootSector
Droit
Accessoire GFA
On Now
Ecran plasma
Système d'exploitation
Son
Unités
Scripting
Multilingue
Site Web
Bruit et son
Architecture Google


4K
Color picker
TaskList
Backup files
Mini Port Scanner
Website To CHM
PixyDemo
Web password recovery
4KWebServer
Kill Popup
VBE decoder
Script Optimizer
Database Password Recovery
Class
Ini
EMail validator
Graphical Class
MP3 Info
Pinger Class
IP ranger class
SoftwareMetering
Path Validator
Time Stamper Class
LoggerCLS
HTA
Keyword Ranking
DOM Explorer
HTA-Notepad
PixyPortManager
Other
flashMessage
Kill Popup
VBE decoder (fixed)
Error Codes
Maze generator
Char counter
HTML To Word
ICQ Choose User
ScreenSaver Password decoder
Mp3Playlister - singleList
Long Filename To Short
Trace Math
Dump Hexa File
Self modifying script
Mp3Playlister - multiList
HTANoid
PixyWebServer
Python
Progress indication

©2002 Jean-Luc Antoine. All Rights Reserved. Scripts or any other material on this website may not be redistributed or put as part of ANY collection (script archives, CDs etc) without prior written permission. Permission granted to use and modify any of the scripts found on InterClasse.com