-
Notifications
You must be signed in to change notification settings - Fork 4
How to Use
Using the plugin to log records is possible through two methods:
You can use Monolog to send records to various Handlers.
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 ] );
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 ] );
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.
The ai_logger_insert
action hook accepts the following 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 ifWP_DEBUG
istrue
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.
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() );
}