PageRenderTime 59ms CodeModel.GetById 27ms RepoModel.GetById 0ms app.codeStats 0ms

/trasweb/common/helpers/Log.class.php

https://bitbucket.org/trasweb/trasweb-framework
PHP | 259 lines | 145 code | 38 blank | 76 comment | 15 complexity | 9c27fcc2bade145b470dcf538e1dec8c MD5 | raw file
Possible License(s): BSD-3-Clause
  1. <?php
  2. /**
  3. New Licence bsd:
  4. Copyright (c) <2012>, Manuel Jesus Canga Mu?oz
  5. All rights reserved.
  6. Redistribution and use in source and binary forms, with or without
  7. modification, are permitted provided that the following conditions are met:
  8. * Redistributions of source code must retain the above copyright
  9. notice, this list of conditions and the following disclaimer.
  10. * Redistributions in binary form must reproduce the above copyright
  11. notice, this list of conditions and the following disclaimer in the
  12. documentation and/or other materials provided with the distribution.
  13. * Neither the name of the Trasweb.net nor the
  14. names of its contributors may be used to endorse or promote products
  15. derived from this software without specific prior written permission.
  16. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
  17. ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
  18. WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
  19. DISCLAIMED. IN NO EVENT SHALL Manuel Jesus Canga Mu?oz BE LIABLE FOR ANY
  20. DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
  21. (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
  22. LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
  23. ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
  24. (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
  25. SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
  26. */
  27. /**
  28. Herramienta de escritura de logs con soporte a formato.
  29. Tags availables:
  30. - Utils: <vars>, <functions>,<constants>, <file>, <pathfile>, <line>, <function>, <object>, <type>, <args>, <date>, <time>, <post>, <get>, <files>,<session>, <classes>
  31. - Colors: <color>, <reset>, <bright>,<underscore>, <blink>, <black>, <red>, <green>, <yellow>, <blue>, <magenta>, <cyan>, <white>, <bblack>, <bred>, <bgreen>, <byellow>, <bblue>, <bmagenta>, <bcyan>, <bwhite>
  32. @TODO: date format and time format segun formato pasados,
  33. */
  34. class Log {
  35. const actived = true;
  36. static $_backtrace = array();
  37. static $_files = array();
  38. /**
  39. Todos los colores posibles de usar
  40. */
  41. static $_colors = array(
  42. "reset" => "\x1b[0;0;0m",
  43. "bright" => "\x1b[1m",
  44. "underscore" => "\x1b[4m",
  45. "blink" => "\x1b[5m",
  46. "black" => "\x1b[30m",
  47. "red" => "\x1b[31m",
  48. "green" => "\x1b[32m",
  49. "yellow" => "\x1b[33m",
  50. "blue" => "\x1b[34m",
  51. "magenta" => "\x1b[35m",
  52. "cyan" => "\x1b[36m",
  53. "white" => "\x1b[37m",
  54. "bblack" => "\x1b[40m",
  55. "bred" => "\x1b[41m",
  56. "bgreen" => "\x1b[42m",
  57. "byellow" => "\x1b[43m",
  58. "bblue" => "\x1b[44m",
  59. "bmagenta" => "\x1b[45m",
  60. "bcyan" => "\x1b[46m",
  61. "bwhite" => "\x1b[47m"
  62. );
  63. /** ETIQUETAS de LOGS: <{string}> -> _option_{string>_() */
  64. static function _option_vars() { $_vars = get_defined_vars(); return $_vars["user"]; }
  65. static function _option_functions() { $_funcs = get_defined_functions(); return $_funcs["user"]; }
  66. static function _option_constants() { $_const = get_defined_constants(true); return $_const["user"]; }
  67. static function _option_file() { return preg_replace("/.+\//i", "", self::$_backtrace[1]['file']); }
  68. static function _option_pathfile() { return self::$_backtrace[1]['file']; }
  69. static function _option_line() { return self::$_backtrace[1]['line']; }
  70. static function _option_function() { return self::$_backtrace[1]['function']; }
  71. static function _option_object() { return self::$_backtrace[1]['object']; }
  72. static function _option_type() { return self::$_backtrace[1]['type']; }
  73. static function _option_args() { return self::$_backtrace[1]['args']; }
  74. static function _option_date($_format="Y-m-d") { return @date($_format); }
  75. static function _option_time($_format="H:i:s") { return @date($_format); }
  76. static function _option_get() { return print_r($_GET, true); }
  77. static function _option_post() { return print_r($_POST, true); }
  78. static function _option_files() { return print_r($_FILES, true); }
  79. static function _option_session() { return print_r($_SESSION, true); }
  80. static function _option_classes() { return print_r(get_declared_classes(), true); }
  81. static function _option_color($_color="reset") { return Log::$_colors[$_color]; }
  82. static function _option_break($_num = 1) { return str_pad(" ", $_num+1, "\n\t\r"); }
  83. static function _option_split($_char = "*") { return "\n\t\r".str_pad(" ", 80, $_char)."\n\t\r"; }
  84. /**
  85. Inserta un mensaje de log
  86. @param String $_file_log: Fichero donde se guardara
  87. @param String $_var lo que se quiere visualizar con etiquetas incluidas
  88. @param String $_label etiqueta que se va a usar
  89. @param String $_file fichero donde ocurrio el incidente
  90. @param String $_line linea donde ocurrio el incidente
  91. */
  92. public static function insertLog($_file_log, $_var, $_label, $_file, $_line) {
  93. self::$_backtrace = debug_backtrace();
  94. $label = "";
  95. if(!empty($_label) ) {
  96. $label = $_label. " ==> ";
  97. }
  98. $var = self::valuate($_var);
  99. $msg = "<reset>[<date>|<time>]: <green> {$label} <reset>";
  100. $msg .= " {$var} <reset>on <{$_file}>:<{$_line}> <break>";
  101. $msg = self::replaceTags($msg);
  102. self::saveLog($_file_log, $msg);
  103. }
  104. /**
  105. Recibe la peticion de registro en log
  106. @param String $_file fichero donde se va a guardar
  107. @param Array $_args contiene toda las informaciones que queremos insertar en el log
  108. */
  109. public static function __callStatic($_file, $_args) {
  110. if(!self::actived) return "";
  111. self::$_backtrace = debug_backtrace();
  112. $args = func_get_args();
  113. //$file = $args[0];
  114. $msg = self::parseArgs($args[1]);
  115. $msg = self::putTail($msg);
  116. $msg = self::replaceTags($msg);
  117. self::saveLog($_file, $msg);
  118. return $msg;
  119. }
  120. /**
  121. Vamos a arreglar la visualizacion de la informacion que se quiere insertar
  122. */
  123. public static function parseArgs($_args) {
  124. if(!empty($_args) ) {
  125. $max = count($_args);
  126. for($i = 0; $i<$max; $i++) {
  127. $args[$i] = " ".self::valuate($_args[$i]);
  128. }
  129. return implode("<reset> |",$args);
  130. }else {
  131. return ;
  132. }
  133. }
  134. /**
  135. Por cada etiqueta encontrada, llamamos a su metodo especifico
  136. @param String $_msg Mensaje que vamos a parsear(y que se insertara en el log)
  137. */
  138. public static function replaceTags($_msg) {
  139. return preg_replace_callback(
  140. "/<((\w+?)(\ [\"\'](.+?)[\"\'])?)>/",
  141. create_function('$tag',
  142. '
  143. $attr = (count($tag)>4)? $tag[4] : null;
  144. $func = "_option_".$tag[2];
  145. if(isset(Log::$_colors[$tag[2]]) ) {
  146. return Log::$_colors[$tag[2]];
  147. }elseif( method_exists("\Log",$func) && null != $attr )
  148. return call_user_func("\Log::".$func, $attr );
  149. else if ( method_exists("\Log",$func) )
  150. return call_user_func("\Log::".$func );
  151. else
  152. return "";
  153. '),
  154. $_msg
  155. );
  156. }
  157. /**
  158. Ponemos un pie fijo en el mensaje a insertar en el log
  159. */
  160. public static function putTail($_msg) {
  161. $msg = "<reset>[<date>|<time>]: ".$_msg;
  162. $msg .= " <reset>on <file>:<line> [<function>] <break>";
  163. return $msg;
  164. }
  165. /**
  166. Escribimos en el log
  167. @param String $_file fichero donde se escribira
  168. @param String $_msg texto que se grabara
  169. */
  170. public static function saveLog($_file, $_msg) {
  171. if ( $_file != "apache") {
  172. $file = PATH."/common/data/logs/{$_file}.log";
  173. file_put_contents($file, $_msg, FILE_APPEND | LOCK_EX);
  174. } else {
  175. @error_log($msg);
  176. }
  177. }
  178. /**
  179. "normalizamos" la cadena a insertar en los logs
  180. */
  181. static function valuate($val) {
  182. if(null === $val) {
  183. return "NULL";
  184. }
  185. if(is_array($val) ) {
  186. if(!empty($val) ) {
  187. return print_r($val,true);
  188. }else {
  189. return " array() ";
  190. }
  191. }
  192. if(is_bool($val) ) {
  193. if(true === $val) {
  194. return "TRUE";
  195. }else {
  196. return "FALSE";
  197. }
  198. }
  199. if("" === $val) {
  200. return " \"\" ";
  201. }
  202. if(is_object($val) ) {
  203. return "OBJECT OF ".get_class($val);
  204. }
  205. return $val;
  206. }
  207. /**
  208. Creamos el directorio de logs sino estuviera creado
  209. */
  210. public static function __initialize() {
  211. if(!FileSystem::exists("/trasweb/common/data/logs/") ) {
  212. mkdir( PATH."/trasweb/common/data/logs/", 0777, true);
  213. }
  214. }
  215. }