PHP Logging class. WordPress code example open

PHP Logging class. WordPress code example

Approved. Code works!
This is exactly the working code that is verified by the moderator or site administrators
Tested: WordPress 5+

This code defines a Class_Log class with methods to log messages to a file. The constructor of the class takes an optional argument $args, which is an array that can contain the property log_path to specify a custom path for the log file.

The class has a method insert_title() which inserts a string message with the current time to the log file and a method insert_log() which inserts any data to the log file after converting it to a string using print_r(). The log file is saved in the logs/directory relative to the main PHP file calling this class, with a filename that starts with the current date in GMT format.

<?php


class Class_Log {

	public $log_path;

	function __construct( $args = false ) {

		if ( $args ) {
			$this->init_properties( $args );
		}

		if ( ! $this->log_path ) {

			$logDir = PATH . 'logs/';

			if ( ! file_exists( $logDir ) ) {
				wp_mkdir_p( $logDir );
			}

			$this->log_path = $logDir . gmdate( 'Y-m-d' ) . '.log';
		}
	}

	function init_properties( $args ) {
		$properties = get_class_vars( get_class( $this ) );

		foreach ( $properties as $name => $val ) {
			if ( isset( $args[ $name ] ) ) {
				$this->$name = $args[ $name ];
			}
		}
	}

	function insert_title( $title ) {

		$this->insert_log( gmdate( 'H:i:s' ) . " " . $title );
	}

	function insert_log( $data ) {

		if ( ! is_string( $data ) ) {
			$data = print_r( $data, true );
		}

		file_put_contents( $this->log_path, $data . "\n", FILE_APPEND );
	}

}

0

More

Leave a Reply

Your email address will not be published. Required fields are marked *

How many?: 22 + 22

lil-code© | 2022 - 2024
Go Top
Authorization
*
*
Registration
*
*
*
*
Password generation