Skip to content

How to Use

Nicole Furlan edited this page Apr 27, 2023 · 7 revisions

Using the plugin to log records is possible through two methods:

Monolog

You can use Monolog to send records to various Handlers.

Examples

Logging to the Log Post Type

use Monolog\Logger;
use AI_Logger\Handler\Post_Handler;

// Use the logger instance the plugin already has setup!
ai_logger()->error( 'This is an error message.' );
ai_logger()->info( 'This is an error message.', [ 'hello' => 'world' ] );

// Roll your own logger instance.
$post_logger = new Logger( 'Example', [ new Post_Handler( Logger::DEBUG, true ) ] );
$post_logger->info( 'Test message' );
$post_logger->error( 'Oh no, an error!', [ 'user_id' => 1234 ] );

Logging to Post Meta

ai_logger()->to_post( 'key', $object_id )->info( 'My info message.' );

You can also register the handlers directly.

use Monolog\Logger;
use AI_Logger\Handler\Post_Meta_Handler;

// Register the logger.
$post_logger = new Logger( 'Example', [ new Post_Meta_Handler( Logger::DEBUG, true, $post_id, 'test_key' ) ] );

// Send a log message.
$post_logger->info( 'Test message' );
$post_logger->error( 'Oh no, an error!', [ 'user_id' => 1234 ] );

Logging to Term Meta

ai_logger()->to_term( 'key', $term_id )->info( 'My info message.' );

You can also use the AI_Logger\Handler\Term_Meta_Handler class as a Monolog Handler, too.

WordPress Hook

The ai_logger_insert action hook accepts the following parameters:

Parameters

$key

String. A short and unique title for this specific log entry

$message

String. The full message for the log entry

$args

Array. (Optional)

level - String, 'info', 'warning', 'error', 'critical'. Default is 'error'.

  • NOTE: Log entries with a level of info will only be written to the database if WP_DEBUG is true

context - String, This value helps to organize your logs into logical areas. For example, if you assign a context of your theme name to any theme code, you'll be able to filter down to log entries in that context.

Examples

Insert a general info message to the log. Typically used to confirm a successful action or response.

$key = 'This is a unique log title';
$message = 'This can be an exception message, API response, wp-cron results, WP_Error message, etc';
$args = array(
	'level' => 'info',
	'context' => 'My plugin name / theme name / general feature',
	'include_stack_trace' => false,
);

do_action( 'ai_logger_insert', $key, $message, $args );

Capture an error and log the error message

try {

	do_something_dangerous();

} catch ( Exception $e ) {

	do_action( 'ai_logger_insert', 'Dangerous Function Failed', $e->getMessage() );
}