Advertisement
Guest User

Untitled

a guest
Nov 24th, 2014
204
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. /*  
  2.     Title:  Logger Control
  3.             *Logging API*
  4.  
  5.     Logger is an AHK module implementing small HTML logging API. It allows you to use consistent logging between different projects.
  6.     Logger can display 3 types of messages - info, warning and error. Each message can display icon, category, text and time in fully
  7.     customizable manner.
  8.  
  9.     In its current implementation Logger uses QHTM control and thus it depends on qhtm.ahk wrapper.
  10.     The module can be quickly changed to use other controls instead, for instance IE control. This can be done by reimplementing 3
  11.     functions with _WebControl_ prefix.
  12.  */
  13.  
  14. /*
  15.     Function: Add
  16.               Add Logger control to the GUI.
  17.  
  18.     Parameters:
  19.               GUI       - Handle of the parent.
  20.               X-H       - Control coordinates.
  21.               Handler   - Notification function that fires when user clicks on the type icon (i.e. properties). Function accepts two parameters - Type and Id.
  22.    
  23.     Config:
  24.              To setup Logger edit *Logger_config* or call Logger_Store(var, value) for dynamic set-up (for some values). You can entirely delete Logger_config.ahk if you don't need it.
  25.  
  26.              You can omit any parameter you don't use, in which case Logger will use default values.
  27.  
  28.                 bg              - Global background, by default "white".
  29.                 fg              - Global foreground, by default "black".
  30.                 fsize           - Global font size, 1-7 for predefined sizes or number with 'pt' suffix (points).
  31.                 isize           - Global icon size, by default 16.
  32.                 separator       - HTML used to separate log entries, none by default. If starts with *, it will separate only on type change, that is , messages from the same module will not be separated.
  33.                 icongroup       - Icon suffix. Icons are normally grabbed from the icons folder in the script directory. Icons are named by type with eventual suffix. Suffix can be used to quickly change icon group.
  34.                 style           - Space separated list of styles for the control, can include 'border' and 'transparent'. None by default.
  35.  
  36.                 catwidth        - Category width or if no category is used, separator between icons and text.
  37.                 catalign        - Category align, by default "left".
  38.                 tcategory       - If true, type will be set as category. By default false.
  39.  
  40.        
  41.                 The following parameters can be set for each type of message. The possible message types are "info", "warning" and "error"
  42.                 If not set, parameter will be set to the global one.
  43.  
  44.                 %type%_bg       - Type background.
  45.                 %type%_fg       - Type foreground.
  46.                 %type%_fsize    - Type font size.
  47.                 %type%_isize    - Type icon size.
  48.                 %type%_catfg    - Type category foreground color.
  49.  
  50.  
  51.                 Behavioral options :
  52.                
  53.                 saveHour        - N, hour at which to save the content of the Logger in an external file.
  54.                                   If starts with "*" content will be saved every N hours instead at Nth hour of the day.
  55.                                   By default empty, means that this functionality will be disabled.
  56.                 logDir          - Directory in which to save log files. Has no meaning if saveHour is disabled.
  57.                 timeFormat      - Time format used for log file names. See FormatTime for details about the format. Has no meaning if saveHour is disabled.
  58.                 error_kw, warning_kw - Coma separated list of keywords for <Auto> function.
  59.  
  60.     Remarks:
  61.                 The Logger will try to include ahk files it needs (Logger_config.ahk, qhtm.ahk) from the root of the script and from the "inc" folder.
  62.                 This function makes one global, Log_hwnd, that keeps handle of the Logger.
  63.  
  64.  */
  65. Log_Add(hGui, x, y, w, h, Handler=""){
  66.     global Log_hwnd
  67.     Logger("*", "bg style saveHour logDir", bg, style, saveHour, logDir)
  68.  
  69.     Logger("handler", Handler)
  70.     Log_hwnd := WebControl_Add(hGui, "<html><body bgcolor='" bg "'>", x, y, w, h, style, "Log_Handler")
  71.  
  72.     if (saveHour != "")
  73.     {  
  74.         FileCreateDir, %logdir%
  75.         Log_saveTimer(true)                 ;initialize save timer
  76.         SetTimer, Log_saveTimer, 60000      ;check every minute
  77.     }
  78. }
  79.  
  80. /*
  81.     Function: Error
  82.               Add error message
  83.  
  84.     Parameters:
  85.               txt       - Text of the message. It can contain references to AHK variables.
  86.               category  - Optional category.
  87.               link      - Optional link. Within application link handler can be set up to fire upon link clicks.
  88.                           To let the user open the link with default browser return 1 from the handler function.
  89.                           The primary use of this parameter is, however, in offline mode, i.e. when user is viewing the log in the local browser.
  90.                           By default, link is set to "javascript:void(0)".
  91.    
  92.     Returns:
  93.               Error number.
  94.    
  95.     Remarks:
  96.               Text can be any kind of HTML with usual meaning except for new line, tab and space characters.
  97.               Those will be transformed to their usual meaning. Apart from mentioned, the text
  98.               is normal HTML which means that you may want to additionally stylish the message.
  99.               In some occasions you may also want to replace special HTML chars - for instance '<' or '>' - with appropriate HTML entities.
  100.                  
  101.               Category parameter is optional. Use it to the put the name of the module that posted a message.
  102.               If logger option _tcategory_ is enabled, type will be set as category. If you use this parameter make sure you set _catwidth_
  103.               to appropriate value.
  104.  
  105.  
  106.  */
  107. Log_Error(txt, category="", link="") {
  108.     return Log_addHtml(txt, A_ThisFunc, category, link)
  109. }  
  110.  
  111. /*
  112.     Function: Warning
  113.               Add warning message.
  114.  
  115.     Remarks:
  116.              See <Error> function.
  117.  */
  118. Log_Warning(txt, category="", link="") {
  119.     return Log_addHtml(txt, A_ThisFunc, category, link)
  120. }
  121.  
  122. /*
  123.     Function: Info
  124.               Add info message.
  125.  
  126.     Remarks:
  127.              See <Error> function.
  128.  */
  129. Log_Info(txt, category="", link="") {
  130.     return Log_addHTML(txt, A_ThisFunc, category, link)
  131. }
  132.  
  133. /*
  134.     Function: Auto
  135.               Add error, warning or info message.
  136.  
  137.     Remarks:
  138.              By default, if it sees word "error" inside message it will call <Error> function (similarly for warnings).
  139.              You can add comma separated list of keywords in the config file. Put error keywords in "error_kw" variable and
  140.              warning fields in "warning_kw". If keywords are not matched, message will be posted as <Info>.
  141.  
  142.              See <Error> function for other remarks.
  143.  
  144.  */
  145. Log_Auto(txt, category="", link="") {
  146.     static error_kw, warning_kw
  147.  
  148.     if (error_kw = "")
  149.         Logger("*", "error_kw warning_kw", error_kw, warning_kw)
  150.  
  151.     loop, parse, error_kw, %A_Space%
  152.         if InStr(txt, A_LoopField)
  153.             return Log_Error(txt, category, link)
  154.  
  155.     loop, parse, warning_kw, %A_Space%
  156.         if InStr(txt, A_LoopField)
  157.             return Log_Warning(txt, category, link)
  158.    
  159.     return Log_Info(txt, category, link)
  160. }
  161.  
  162. /*
  163.     Function: Clear
  164.               Clears the Logger control.
  165.  */
  166. Log_Clear(){
  167.     global Log_hwnd
  168.     ControlSetText, , , ahk_id %Log_hwnd%
  169.     WebControl_AddHtml(Log_hwnd, "<html><body bgcolor='" Logger("bg") "'>")
  170.  
  171. }
  172.  
  173. /*
  174.     Function: OpenInBrowser
  175.               Opens the content of the logger control in the default system browser.
  176.  */
  177. Log_OpenInBrowser() {
  178.     fName = %A_Temp%\%A_ScriptName%_Logger.html
  179.     Log_Save(fName)
  180.     Run, %fName%
  181. }
  182.  
  183. /*
  184.     Function: Save
  185.               Saves the content of the logger control in the file.
  186.  
  187.     Parameters:
  188.               FileName  - File name to save content to.
  189.               bAppend   - Set to true to append content to the file, by default false.
  190.  */
  191. Log_Save(FileName, bAppend = false){
  192.     global Log_hwnd
  193.     txt := WebControl_GetHTML(Log_hwnd)
  194.  
  195.     if (!bAppend)
  196.         FileDelete, %FileName%
  197.     FileAppend %txt%</body></html>, %FileName%
  198. }
  199.  
  200. /*
  201.     Function: SetSaveFile
  202.               Set up the real time save file.
  203.  
  204.     Parameters:
  205.               FileName - If non empty, this file will be used to write information as soon as it is added to the control.
  206.                          To disable real time file saving, omit this parameter. Its disabled by default.
  207.  */
  208. Log_SetSaveFile(FileName="") {
  209.     file := Logger("save")
  210.     ifNotEqual, file, ,FileAppend, </body></html>, %file%
  211.     Logger("save", FileName)
  212. }
  213.  
  214. ;===========================================================================================
  215.  
  216. Log_addHTML( txt, type, category="", link="") {
  217.      global Log_hwnd
  218.      static warning_no, info_no, error_no, init, last_category, bTypeSep
  219.      static separator, imaxsize, catwidth, tcategory, catalign, icongroup
  220.      static space=" &nbsp;"
  221.  
  222.      StringReplace, type, type, Log_,  
  223.      StringReplace, txt, txt, `n, <br>, A
  224.      StringReplace, txt, txt, %A_Space%%A_Space%,%space%, A
  225.      StringReplace, txt, txt, %A_Tab%,%space%%space%, A
  226.  
  227.      if SubStr(category, 1, 1)="*"
  228.          category := (j := InStr(category, "_")) = -1 ? SubStr(category, 2) : SubStr(category, 2, j-2)
  229.  
  230.      if !init {
  231.          imaxsize   := Logger("imaxsize")+5
  232.          catwidth   := Logger("catwidth")
  233.          tcategory  := Logger("tcategory")
  234.          catalign   := Logger("catalign")
  235.          icongroup  := Logger("icongroup")
  236.          separator  := Logger("separator")
  237.  
  238.          if bTypeSep := (SubStr(separator, 1, 1) = "*")
  239.             separator := SubStr(separator, 2)
  240.          last_category := category
  241.  
  242.          init := 1
  243.      }
  244.  
  245.      Logger("*" type "_", "bg fg isize fsize catfg", bg,fg,isize,fsize,catfg)
  246.  
  247.      %type%_no +=1
  248.      no := %type%_no
  249.      category .= (category = "") && tcategory ? type : ""
  250.      link  .= link != "" ? "" : "javascript:void(0)"
  251.      txt := Log_derefernce(txt)
  252.  
  253.      if (separator != "")
  254.         sep := bTypeSep && (category != last_category) ? separator : ""
  255.  
  256.      html =
  257.      (LTrim Join
  258.                 %sep%
  259.                 <table  bgcolor='%bg%' width=100`%>
  260.                   <tr>
  261.                     <td align=center width=%imaxsize%px >
  262.                          <a id='%type%%no%' href="%link%" title='%type% %no%' ><img width=%isize% height=%isize% src='%A_ScriptDir%\icons\%type%%icongroup%.png'></a>
  263.                     </td>
  264.                     <td align=%catalign% width=%catwidth%px>
  265.                         <font size=%fsize% color='%fg%'>%category%</font>
  266.                     </td>
  267.                     <td width=70`%>
  268.                         <font size=%fsize% color='%fg%'>%txt%</font>
  269.                     </td>
  270.                     <td align='right'>
  271.                         <font size=1 color='%fg%'>%A_Hour%:%A_Min%:%A_Sec%</font>
  272.                     </td>
  273.                   </tr>
  274.                 </table>
  275.      )
  276.    
  277.     WebControl_AddHtml(Log_hwnd, html)
  278.     if save := Logger("save")  
  279.         FileAppend, %html%, %save%
  280.  
  281.     last_category := category
  282.     return %no%
  283. }
  284.  
  285.  
  286. /*
  287.     Storage Function   
  288.  
  289.     Usage:
  290.         store(x)     - return value of x
  291.         store(x, v)  - set value of x to v and return previous value
  292.         store("*", "x y z", x, y, z)  - get values of x, y and z into x, y and z
  293.         store("*preffix_", "x y z", x, y, z) - get values of preffix_x, preffix_y and preffix_z into x, y and z
  294.  
  295.  */
  296. Logger(var, value="~`a", ByRef o1="", ByRef o2="", ByRef o3="", ByRef o4="", ByRef o5="") {
  297.     static
  298.     ifEqual, init, , gosub Logger
  299.  
  300.     c := SubStr(var,1,1)
  301.     if (c = "*" ){
  302.         c := SubStr(var, 2)
  303.         loop, parse, value, %A_Space%
  304.             _ := %c%%A_LoopField%,   o%A_Index% := _ != "" ? _ : %A_LoopField%
  305.         return
  306.     }
  307.  
  308.     if InStr(var, "isize")
  309.         %var% := value, imaxsize := (error_isize > imaxsize) ? error_isize : warning_isize > imaxsize ? warning_isize : (info_isize > imaxsize) ? info_isize : imaxsize
  310.  
  311.     return (value !="~`a") ? %var% := value : %var%
  312.  
  313.  Logger:
  314.     #include *i Logger_Config.ahk
  315.     #include *i inc\Logger_Config.ahk
  316.  
  317.    ;defaults
  318.     catwidth .= (catwidth = 0) or (catwidth = "") ? 1 : ""
  319.  
  320.     fsize    .= fsize   != "" ? ""      : 1
  321.     bg       .= bg      != "" ? ""      : "white"
  322.     fg       .= fg      != "" ? ""      : "black"
  323.     isize    .= isize   != "" ? ""      : 16
  324.     fsize    .= fsize   != "" ? ""      : 1
  325.     catfg    .= catfg   != "" ? ""      : fg
  326.     catfg    .= catfg   != "" ? ""      : fg
  327.     catalign .= catalign!= "" ? ""      : "left"
  328.    
  329.     error_kw .= error_kw!= "" ? ""      : "error"
  330.     warning_kw.= warning_kw!= "" ? ""   : "warning"
  331.    
  332.     imaxsize := isize
  333.     imaxsize := (error_isize > imaxsize) ? error_isize : warning_isize > imaxsize ? warning_isize : (info_isize > imaxsize) ? info_isize : imaxsize
  334.     if tcategory && (catwidth=1)
  335.         catwidth = 100
  336.     init := 1
  337.  return
  338. }
  339.  
  340. ; Dereference variables in text
  341. Log_derefernce(txt) {
  342.     global
  343.     local match, match1, val
  344.  
  345.     loop{
  346.         if !(j := RegExMatch(txt, "i)%([^ \t%]+)%", match))
  347.             break
  348.  
  349.         val := %match1%
  350.         StringReplace, txt, txt, `%%match1%`%, %val%, A
  351.     }
  352.     return txt
  353. }
  354.  
  355.  
  356. ; Function that runs every minut to handle saveHour
  357. Log_saveTimer( init = false ) {
  358.     static saveHour, lastSave, b, logdir, timeformat
  359.     if (saveHour = "")
  360.         Logger("*", "saveHour logdir timeFormat", saveHour, logdir, timeformat),  lastSave := A_Now,   b := SubStr(saveHour, 1, 1) = "*",   saveHour := b ? SubStr(saveHour,2) : saveHour
  361.    
  362.     if !init   
  363.     {
  364.         if b {
  365.             t -= lastSave, hours
  366.             ifLess, t, %saveHour%, return              
  367.         }
  368.         else ifNotEqual, A_Hour, %saveHour%, return
  369.     }
  370.  
  371.     FormatTime, time, , %timeFormat%
  372.     fn :=  (logdir ? logdir "\" : "") time ".htm"
  373.     Log_Clear(), Log_SetSaveFile( fn )
  374.     lastSave := A_Now
  375. }
  376.  
  377. Log_saveTimer:
  378.     Log_saveTimer()
  379. return
  380.  
  381.  
  382. Log_handler(hLogger, Type, Id) {
  383.     static handler=0
  384.    
  385.     if handler = 0
  386.         handler := Logger("handler")
  387.    
  388.     RegExMatch(Id, "(.+?)([0-9]+)", out)
  389.  
  390.     return IsFunc(handler) ? %handler%(out1, out2) : 0
  391. }
  392.  
  393. ;================= WEB CONTROL INTERFACE =============================
  394.  
  395. WebControl_Add(hCtrl, Text, X, Y, W, H, Style="", Fun=""){
  396.     return QHTM_Add(hCtrl, X, Y, W, H, Text, Style, Fun)
  397. }
  398.  
  399. WebControl_AddHtml(hCtrl, HTML, bScroll=false){
  400.     return QHTM_AddHtml( hCtrl, HTML, bScroll )
  401. }
  402.  
  403. WebControl_GetHtml(hCtrl){
  404.     return QHTM_GetHTML(hCtrl)
  405. }
  406.  
  407. #include *i qhtm.ahk
  408. #include *i inc\qhtm.ahk
  409.  
  410. ;================ WEB CONTROL INTERFACE END ==========================
  411.  
  412. /*
  413.  Group: Example
  414. (start code)
  415.     #SingleInstance force
  416.         Gui, +LastFound
  417.         hGui := WinExist()
  418.         Log_Add( hGui, 0, 0, 600, 500)
  419.         Gui, show, w600 h500
  420.  
  421.         Log_Info("This is some info"), s()
  422.         Log_Error("Error ocured`nThis is the description of the error"), s()
  423.         Log_Warning("This is warning"), s()
  424.  
  425.         Log_Auto("This is some info"), s()
  426.         Log_Auto("Error ocured`nThis is the description of the error"), s()
  427.         Log_Auto("This is warning"), s()
  428.  
  429.     return
  430.  
  431.     s() {
  432.         Random, x, 1, 3
  433.         Sleep, % x*1000
  434.     }
  435.  
  436. (end code)
  437.  */
  438.  
  439.  
  440. /*
  441.  Group: About
  442.     o Logger ver 1.0 by majkinetor.
  443.     o QHTM copyright © GipsySoft. See http://www.gipsysoft.com/qhtm/
  444.     o Licenced under GNU GPL <http://creativecommons.org/licenses/GPL/2.0/>
  445.  */
  446.  
  447. #include qhtm.ahk
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement