WPDK  1.5.0
WordPress Development Kit
 All Data Structures Files Functions Variables Pages
wpdk-watchdog.php
Go to the documentation of this file.
1 <?php
3 
4 /*
5  * [DRAFT]
6  *
7  * THE FOLLOWING CODE IS A DRAFT. FEEL FREE TO USE IT TO MAKE SOME EXPERIMENTS, BUT DO NOT USE IT IN ANY CASE IN
8  * PRODUCTION ENVIRONMENT. ALL CLASSES AND RELATIVE METHODS BELOW CAN CHNAGE IN THE FUTURE RELEASES.
9  *
10  */
11 
34 class WPDKWatchDog {
35 
41  const LOG_SEPARATOR = '---------------------------------------------------------------------------------------------';
42 
50  public $enabled;
51 
59  public $triggerError;
60 
68  public $separator;
69 
77  public $path;
78 
86  public $logname;
87 
95  public $available;
96 
104  public $extensionFilename;
105 
113  public $prefix;
114 
127  public function __construct( $path, $folder = 'logs', $extension = 'php' )
128  {
129  $this->path = trailingslashit( trailingslashit( $path ) . $folder );
130  $this->enabled = true;
131  $this->triggerError = false;
132  $this->separator = self::LOG_SEPARATOR;
133  $this->extensionFilename = $extension;
134 
135  /* Under the plugin path ($path) create a log/ folder */
136  if ( !file_exists( $this->path ) ) {
137  @wp_mkdir_p( $this->path );
138  }
139 
140  $this->logname = sprintf( '%s%s.%s', $this->path, date( 'Ymd' ), $this->extensionFilename );
141 
142  /* Check if log file is available */
143  $handle = @fopen( $this->logname, "a+" );
144  $this->available = ( false !== $handle );
145 
146  /* Remove old zero logs. */
147  $yesterday_log = sprintf( '%s%s.%s', $this->path, date( 'Ymd', strtotime( '-1 days' ) ), $this->extensionFilename );
148  if ( file_exists( $yesterday_log ) ) {
149  $size = @filesize( $yesterday_log );
150  if ( empty( $size ) ) {
151  @unlink( $yesterday_log );
152  }
153  }
154  }
155 
169  public function log( $txt, $title = '' )
170  {
171  if ( $this->enabled && $this->available ) {
172 
173  /* If not a pre-formatted string, grab the var dump object, array or mixed for output */
174  if ( !is_string( $txt ) && !is_numeric( $txt ) ) {
175  ob_start();
176  var_dump( $txt );
177  $content = ob_get_contents();
178  ob_end_clean();
179  $txt = $content;
180 
181  /* @since 1.4.3 */
182  do_action( 'wpdk_watchdog_log', $content );
183  }
184 
185  $date = sprintf( '[%s]', date( 'Y-m-d H:i:s' ) );
186  $sepa = substr( $this->separator, 0, ( strlen( $this->separator ) - strlen( $date ) - 1 ) );
187  $output = sprintf( "%s (%s) %s\n%s\n\n", $date, $title, $sepa, $txt );
188  $handle = fopen( $this->logname, 'a+' );
189  if ( false !== $handle ) {
190  fwrite( $handle, $output );
191  fclose( $handle );
192  }
193  else {
194  $this->available = false;
195  }
196 
197  if ( $this->triggerError ) {
198  trigger_error( $output );
199  }
200  }
201  return $this->available;
202  }
203 }
204