sample lines to get you started:
Code: Select all
console := new class_consoleLogger ;New class instance
console.register()
;inits some variables, including log path and text encoding.
;Leave blank to auto-generate a timestamped file in %a_scriptdir%\logs\
;Basic Usage
console.log("This writes to file and console.")
console.fileLog("This writes to file only.")
console.consoleLog("This writes to console only.")
console.setWritingColor(5) ;changes the console "palette" at the exact place in text it's called. 0 returns to normal white on black.
console.changeLogPath(a_scriptdir "\different log folder\log.txt")
;changes the targeted output file and encoding.
;Returns 1 on success or 0 on failure (such as making a file where you don't have permissions).
;Leave blank to use the default timestamped file.
and the code:
Code: Select all
class class_consolelogger{
static hConsoleOut := ""
static stdin := ""
static stdout := ""
static logPath := ""
static logHandle := ""
register(logPath := "",logEncoding := "UTF-16"){
DllCall("AllocConsole")
,this.hConsoleOut := DllCall("GetStdHandle", "uint", -11, Ptr)
,this.stdout := FileOpen("*", "w `n")
,this.stdin := FileOpen("*","r `n")
SplitPath,A_ScriptFullPath,ScriptName,ScriptDir,ScriptExt,ScriptBase,ScriptDrive
if (logPath = "")
logPath := a_scriptdir "\logs\" ScriptBase " [" A_NowUTC "]" ".txt"
SplitPath,LogPath,LogName,LogDir,LogExt,LogBase,LogDrive
FileCreateDir, % logDir
,this.logpath := logpath
,this.logHandle := FileOpen(this.logpath,"a",logEncoding) ;opens in append mode to allow updating old log files
}
log(byref input){
this.consoleLog(input)
,this.fileLog(input)
}
SetWritingColor(Color := 0){
return DllCall("SetConsoleTextAttribute", "uPtr", this.hConsoleOut, "UShort", color)
}
fileLog(byref input){
this.logHandle.write("[" A_NowUTC "]" a_tab input "`n")
;DllCall("FlushFileBuffers", "Ptr", this.logHandle.__Handle) ;slow
,this.logHandle.__Handle ;fast
}
consoleLog(byref input){
this.stdout.write(input "`n")
,this.stdout.read(0)
}
changeLogPath(byref newPath := "",logEncoding := "UTF-16"){
if (newPath = ""){
SplitPath,A_ScriptFullPath,ScriptName,ScriptDir,ScriptExt,ScriptBase,ScriptDrive
newPath := a_scriptdir "\logs\" ScriptBase " [" A_NowUTC "]" ".txt"
}
SplitPath,newPath,LogName,LogDir,LogExt,LogBase,LogDrive
FileCreateDir, % LogDir
if InStr(FileExist(LogPath),"D"){
this.logHandle.close()
,this.logPath := newPath
,this.logHandle := FileOpen(this.logpath,"a",logEncoding)
return 1 ;success
}
return 0 ;failure
}
}