Add DB log handler

This commit is contained in:
Jon Surrell 2016-11-20 15:17:55 +01:00
parent 09ea8b074e
commit 5a9db9738f
1 changed files with 85 additions and 0 deletions

View File

@ -0,0 +1,85 @@
<?php
if ( ! defined( 'ABSPATH' ) ) {
exit; // Exit if accessed directly
}
if ( ! class_exists( 'WC_Log_Handler' ) ) {
include_once( dirname( dirname( __FILE__ ) ) . '/abstracts/abstract-wc-log-handler.php' );
}
/**
* Handles log entries by writing to database.
*
* @class WC_Log_Handler_DB
* @version 1.0.0
* @package WooCommerce/Classes/Log_Handlers
* @category Class
* @author WooThemes
*/
class WC_Log_Handler_DB extends WC_Log_Handler {
/**
* Handle a log entry.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug
* @param string $message Log message.
* @param array $context {
* Additional information for log handlers.
*
* @type string $tag Optional. Tag will be available in log table. Default '';
* }
*
* @return bool Log entry should bubble to further loggers.
*/
public function handle( $timestamp, $level, $message, $context ) {
if ( ! $this->should_handle( $level ) ) {
return true;
}
if ( isset( $context['tag'] ) && $context['tag'] ) {
$tag = $context['tag'];
} else {
$tag = '';
}
// Bubble if add is NOT successful
return ! $this->add( $timestamp, $level, $message, $tag, $context );
}
/**
* Add a log entry to chosen file.
*
* @param int $timestamp Log timestamp.
* @param string $level emergency|alert|critical|error|warning|notice|info|debug
* @param string $message Log message.
* @param string $tag Log tag. Useful for filtering and sorting.
* @param array $context {
* Context will be serialized and stored in database.
* }
*
* @return bool True if write was successful.
*/
public function add( $timestamp, $level, $message, $tag, $context ) {
global $wpdb;
$insert = array(
'timestamp' => date( 'Y-m-d H:i:s', $timestamp ),
'level' => $level,
'message' => $message,
'tag' => $tag,
);
if ( ! empty( $context ) ) {
$insert['context'] = serialize( $context );
}
$result = $wpdb->insert( "{$wpdb->prefix}woocommerce_log", $insert );
var_dump( $result );
return false !== $result;
}
}