This example shows how to create a simple logger that will log 404-errors on your website.
The logger is split into two parts:
- Part 1 loads and registers the logger. The code for this can be placed in your
functions.php
-file or in a custom plugin. - Part 2 is the actual logger class, that will live in it’s own file.
Part 1: Loading and registering the logger
Put this code in functions.php
or similar.
<?php
/**
* Use function "register_logger" to load our logger and to
* notify Simple History that our custom logger exists.
*/
add_action(
'simple_history/add_custom_logger',
function ( $simple_history ) {
require_once __DIR__ . '/class-four-oh-four-logger.php';
$simple_history->register_logger( 'Four_Oh_Four_Logger' );
}
);
Code language: HTML, XML (xml)
Part 2: The logger class
Put this code into file class-four-oh-four-logger.php
.
<?php
/**
* This is the class that does the main work!
*/
class Four_Oh_Four_Logger extends \Simple_History\Loggers\Logger {
/**
* The slug is used to identify this logger in various places.
*/
public $slug = 'Four_Oh_Four_Logger';
/**
* Return information about this logger.
*
* Used to show info about the logger at various places.
*/
public function get_info() {
return array(
'name' => __( '404 Logger', 'simple-history' ),
'description' => __( 'Logs access to pages that result in page not found errors (error code 404)', 'simple-history' ),
'capability' => 'edit_pages',
'messages' => array(
'page_not_found' => __( 'Got a 404-page when trying to visit "{request_uri}"', 'simple-history' ),
),
'labels' => array(
'search' => array(
'label' => _x( 'Pages not found (404 errors)', 'User logger: 404', 'simple-history' ),
'options' => array(
_x( 'Pages not found', 'User logger: 404', 'simple-history' ) => array(
'page_not_found',
),
),
), // end search
), // end labels
);
}
/**
* When Simple History has loaded this logger it automagically
* calls a loaded() function. This is where you add your actions
* and other logger functionality.
*/
public function loaded() {
// Call a function when WordPress finds a 404 page
add_action( '404_template', array( $this, 'on_404_template' ), 10, 1 );
}
/**
* Function that is called when WordPress finds a 404 page.
* It collects some info and then it logs a warning message
* to the log.
*/
public function on_404_template( $template ) {
$context = array(
'_initiator' => \Simple_History\Log_Initiators::WEB_USER,
'request_uri' => isset( $_SERVER['REQUEST_URI'] ) ? $_SERVER['REQUEST_URI'] : '',
'http_referer' => isset( $_SERVER['HTTP_REFERER'] ) ? $_SERVER['HTTP_REFERER'] : '',
);
$this->warning_message( 'page_not_found', $context );
return $template;
}
}
Code language: HTML, XML (xml)