Skip to content

Commit

Permalink
Merge pull request #2 from alleyinteractive/javascript-logging
Browse files Browse the repository at this point in the history
  • Loading branch information
srtfisher authored Sep 11, 2020
2 parents 32555ff + d0ad828 commit c83db05
Show file tree
Hide file tree
Showing 4 changed files with 146 additions and 0 deletions.
1 change: 1 addition & 0 deletions ai-logger.php
Original file line number Diff line number Diff line change
Expand Up @@ -21,6 +21,7 @@
}

define( 'AI_LOGGER_PATH', __DIR__ );
define( 'AI_LOGGER_URL', plugins_url( '/', __FILE__ ) );

// Check if Composer is installed.
if ( ! file_exists( __DIR__ . '/vendor/autoload.php' ) ) {
Expand Down
15 changes: 15 additions & 0 deletions inc/bootstrap.php
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,21 @@

AI_Logger::instance();

add_action(
'after_setup_theme',
function() {
/**
* Flag if Javascript logging is enabled.
*
* @param bool $enabled Flag if Javascript logging is enabled.
*/
if ( apply_filters( 'ai_logger_enable_js_logging', false ) ) {
new AI_Logger_JS();
}
},
20
);

// wp-cli command.
if ( defined( 'WP_CLI' ) && WP_CLI ) {
\WP_CLI::add_command( 'ai-logger', __NAMESPACE__ . '\CLI' );
Expand Down
88 changes: 88 additions & 0 deletions inc/class-ai-logger-js.php
Original file line number Diff line number Diff line change
@@ -0,0 +1,88 @@
<?php
/**
* AI_Logger_JS class file.
*
* @package AI_Logger
*/

namespace AI_Logger;

/**
* Class to implement JavaScript logging functionality.
* Disabled by default, enable by passing true to the
* 'ai_logger_enable_js_logging' filter.
*/
class AI_Logger_JS {

/**
* Initialize JavaScript Logging functionality.
*/
public function __construct() {
// Create AJAX actions.
add_action( 'wp_ajax_ai_logger_insert', [ $this, 'log' ] );
add_action( 'wp_ajax_nopriv_ai_logger_insert', [ $this, 'log' ] );

// Set up assets.
add_action( 'wp_enqueue_scripts', [ $this, 'enqueue' ] );
add_action( 'admin_enqueue_scripts', [ $this, 'enqueue' ] );
add_action( 'login_enqueue_scripts', [ $this, 'enqueue' ] );
}

/**
* Enqueue and localize assets.
*/
public function enqueue() {
wp_enqueue_script( 'ai-logger-insert', AI_LOGGER_URL . '/static/js/logger-insert.js', [], '0.1', true );
wp_localize_script(
'ai-logger-insert',
'aiLoggerConfig',
[
'nonce' => wp_create_nonce( 'ai-logger-insert' ),
'url' => admin_url( 'admin-ajax.php' ),
]
);
}

/**
* Create a log message based on posted data.
*/
public function log() {
if ( ! check_ajax_referer( 'ai-logger-insert', 'ai_logger_nonce', false ) ) {
wp_send_json_error( [ 'response' => __( 'Insecure request.', 'ai-logger' ) ] );
} elseif ( empty( $_POST['message'] ) ) {
wp_send_json_error( [ 'response' => __( 'Key and message parameters are required.', 'ai-logger' ) ] );
}

// Sanitize input.
$message = sanitize_text_field( wp_unslash( $_POST['message'] ) );
$clean_args = [];

// Clean up the arguments array.
if ( isset( $_POST['args'] ) ) {
$args = wp_unslash( $_POST['args'] );
if ( is_string( $args ) ) {
$args = json_decode( $args, true );
}

foreach ( $args as $arg => $value ) {
$clean_args[ sanitize_text_field( $arg ) ] = sanitize_text_field( $value );
}
}

// Setup some default arguments.
$level = $args['level'] ?? 'info';
$args['context'] = $args['context'] ?? 'front-end';

// Create the log entry.
ai_logger()->$level( $message, $args );

// Respond.
wp_send_json_success(
[
'args' => $clean_args,
'message' => $message,
'response' => __( 'Log entry created.', 'ai-logger' ),
]
);
}
}
42 changes: 42 additions & 0 deletions static/js/logger-insert.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@

window.aiLogger = window.aiLogger || [];

class Logger {
/**
* Constructor.
*
* @param {...any} args Array of arguments from `window.aiLogger`.
*/
constructor(...args) {
if (args.length) {
args.forEach((item) => this.push(...item))
}
}

/**
* Handle a log event.
*
* @param {Array} record Log record.
*/
async push(...args) {
const [ message, logArgs ] = args;
const { nonce, url } = window.aiLoggerConfig;

// Include the current request information.
logArgs.url = window.location.href;

const body = new URLSearchParams();
body.append('action', 'ai_logger_insert');
body.append('ai_logger_nonce', nonce);
body.append('args', JSON.stringify(logArgs));
body.append('message', message);

await fetch(url, {
method: 'POST',
credentials: 'same-origin',
body,
});
}
}

window.aiLogger = new Logger(...window.aiLogger || []);

0 comments on commit c83db05

Please sign in to comment.