Skip to content

Instantly share code, notes, and snippets.

@yuriitaran
Forked from kostiantyn-petlia/helpers-write-log.php
Created November 14, 2018 16:01
Show Gist options
  • Save yuriitaran/5a467858fb95e249a02a0f4142bec9ca to your computer and use it in GitHub Desktop.
Save yuriitaran/5a467858fb95e249a02a0f4142bec9ca to your computer and use it in GitHub Desktop.
Logging function write_log() for debugging process
// -----------------------------------------------------------------------------
/**
* Logging to debug.log in DEBUG_LOG_DIR dir (default is the root site dir)
*
* Note: You can define in the wp-config.php:
* 1) define( 'DEBUG_LOG_DIR', dirname( __FILE__ ) . '/' );
* 2) define( 'DEBUG_LOG_INVERTED', false);
*
* Author K
* Version 2.0.1.0
*/
if ( ! function_exists( 'write_log' ) ) {
function write_log( $log = null, $before = '', $after = '', $clear = false ) {
if ( true === WP_DEBUG && ( defined( 'DEBUG_LOG_DIR' ) || defined( 'ABSPATH' ) ) ) {
// Destination File
$debug_log_file = ( ( defined( 'DEBUG_LOG_DIR' ) ) ? DEBUG_LOG_DIR : ABSPATH ) . 'debug.log';
// Clear debug.log if 'true' or the file is more than 10Mb (10485760 bytes)
if ( true === $clear || filesize( $debug_log_file ) > 10485760 || ! file_exists( $debug_log_file ) ) {
file_put_contents( $debug_log_file, '' );
}
if ( is_writable( $debug_log_file ) ) {
$content = '';
// Only string can be in the wrapper role
$before = is_string( $before ) ? $before : '';
$after = is_string( $after ) ? $after : '';
// Build content ('-' & 'hr' define a separate line before the content)
$hr = in_array( $clear, [ '-', 'hr' ], true ) ? str_repeat( '-', 80 ) . PHP_EOL : '';
$content .= date( 'Y-m-d H:i:s' ) . ': ' . $before . var_export( $log, true ) . $after . PHP_EOL;
// Write log
if ( defined( 'DEBUG_LOG_INVERTED' ) && false === DEBUG_LOG_INVERTED ) {
$content = $hr . $content;
file_put_contents( $debug_log_file, $content, FILE_APPEND ); // was (temp): error_log( $content, 3, $debug_log_file );
} else {
$content = $content . $hr . file_get_contents( $debug_log_file );
file_put_contents( $debug_log_file, $content );
}
}
}
}
}
// -----------------------------------------------------------------------------
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment