php - 如何在php中实现错误记录器文件

标签 php error-handling

我在PHP中创建了一个错误记录器文件,并在调用Web API时尝试记录错误时从邮件index.php文件中调用它,但未创建错误记录器文件,也无法将其错误记录到记录器文件中,有人可以帮助我吗在这个??

looger.php

<?php
    class Logger {
        static $directoryName = 'log/';
        static $fileName = 'error.json';

        public static function init() {
            function handleError($code, $description, $file = null, $line = null, $context = null) {
                list($error, $log) = mapErrorCode($code);
                throw new LoggerException($description, $code, $file, $line, $context, $log, $error);
            }
            function handleException($ex) {
                throw new LoggerException($ex->getMessage(), $ex->getCode(), $ex->getFile(), $ex->getLine());
            }

            function mapErrorCode($code) {
                $error = $log = null;
                switch ($code) {
                    case E_PARSE:
                    case E_ERROR:
                    case E_CORE_ERROR:
                    case E_COMPILE_ERROR:
                    case E_USER_ERROR:
                        $error = 'Fatal Error';
                        $log = LOG_ERR;
                        break;
                    case E_WARNING:
                    case E_USER_WARNING:
                    case E_COMPILE_WARNING:
                    case E_RECOVERABLE_ERROR:
                        $error = 'Warning';
                        $log = LOG_WARNING;
                        break;
                    case E_NOTICE:
                    case E_USER_NOTICE:
                        $error = 'Notice';
                        $log = LOG_NOTICE;
                        break;
                    case E_STRICT:
                        $error = 'Strict';
                        $log = LOG_NOTICE;
                        break;
                    case E_DEPRECATED:
                    case E_USER_DEPRECATED:
                        $error = 'Deprecated';
                        $log = LOG_NOTICE;
                        break;
                    default :
                        break;
                }
                return array($error, $log);
            }
            error_reporting(E_ALL);
            ini_set("display_errors", "off");            
            set_error_handler("handleError");
            set_exception_handler("handleException");
        }
        public static function save($e, $customMessage = '', $customData = []) {

            if (!isset($e)) {
                $bt = debug_backtrace();
                $caller = array_shift($bt);
                if (isset($caller)) {
                    $e = new LoggerException($customMessage, 0, $caller['file'], $caller['line'], null, null, 'NoException');
                } else {
                    $e = new LoggerException($customMessage, 0, null, null, null, null, 'NoException');
                }
            }
            date_default_timezone_set('Asia/Kolkata');
            $logData = Logger::get($e, $customMessage, $customData);            
            $now = date('d_m_Y');

            $directoryName = Logger::$directoryName;
            $fileName = Logger::$fileName;
            if (!file_exists($directoryName)) {
                mkdir($directoryName);
            }
            $fileName = $directoryName . $now . '_' . $fileName;  
            if (!file_exists($fileName)) {
                $file = fopen($fileName, "w");
                fclose($file);
            }

            $jsonData = file_get_contents($fileName);
            $arrayData = json_decode($jsonData, true);
            if (!isset($arrayData)) {
                $arrayData = [];                
            }
            array_push($arrayData, $logData);
            $jsonData = json_encode($arrayData, JSON_PRETTY_PRINT);
            return file_put_contents($fileName, $jsonData);
        }
        public static function get($e, $customMessage = '', $customData = []) {
            $error = get_class($e) == 'LoggerException' ? $e->getError() : get_class($e);
            $context = [
                'HTTP_HOST'          => $_SERVER['HTTP_HOST'],
                'HTTP_CONNECTION'    => $_SERVER['HTTP_CONNECTION'],
                'HTTP_USER_AGENT'    => $_SERVER['HTTP_USER_AGENT'],                
                'REMOTE_ADDR'        => $_SERVER['REMOTE_ADDR'],                
                'REMOTE_PORT'        => $_SERVER['REMOTE_PORT'],
                'REQUEST_SCHEME'     => $_SERVER['REQUEST_SCHEME'],
                'REQUEST_METHOD'     => $_SERVER['REQUEST_METHOD'],
                'REQUEST_URI'        => $_SERVER['REQUEST_URI'],
                'QUERY_STRING'       => $_SERVER['QUERY_STRING'],
                'PHP_SELF'           => $_SERVER['PHP_SELF'],
                'REQUEST_TIME_FLOAT' => $_SERVER['REQUEST_TIME_FLOAT'],
                'REQUEST_TIME'       => $_SERVER['REQUEST_TIME'],
                'GET'                => $_GET,
                'POST'               => $_POST,
                'POST_BODY'          => file_get_contents('php://input'),
                'FILES'              => $_FILES,
                'COOKIE'             => $_COOKIE,                
            ];
            return array(
                'level' => $error,
                'code' => $e->getCode(),
                'error' => $error,
                'description' => $e->getMessage(),
                'file' => $e->getFile(),
                'line' => $e->getLine(),        
                'date' => date('d-m-Y h:i:s a'),        
                'message' => $error . ' (' . $e->getCode() . '): ' . $e->getMessage() . ' in [' . $e->getFile() . ', line ' . $e->getLine() . ']',
                'customMessage' => $customMessage,
                'customData' => $customData,
                'context' => $context
            );
        }
    }

    class LoggerException extends ErrorException {

        private $context = null;
        private $log = null;
        private $error = null;
        function __construct($description, $code, $file = null, $line = null, $context = null, $log = null, $error = null) {
            parent::__construct($description, 0, $code, $file, $line);
            $this->context = $context;
            $this->log = $log;
            $this->error = $error;
        }
        public function getContext() {
            return $this->context;
        }
        public function getLog() {
            return $this->log;
        }
        public function getError() {
            return $this->error;
        }
    }

    Logger::init();
?>

index.php
<?php
include_once './api/logger.php';


 $url = 'http://localhost/jwt_api/api/login1.php';

        //open connection
        $postdata = json_encode($data);
        //print_r($postdata);
        $ch = curl_init($url);
        curl_setopt($ch, CURLOPT_HTTPHEADER, array('Access-Control-Allow-Origin: *', 'Content-Type: application/json', 'Access-Control-Allow-Methods: POST', 'Access-Control-Max-Age: 3600'));
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $postdata);
        curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
        $output = curl_exec($ch);
        $result = json_decode($output);
        if ($result->message == 'Successful login') {
            $jwtname = "Access";
            $jwt = $result->jwt;
            setcookie($jwtname, $jwt, time() + (86400 * 30), "/");
            header("location:create.php");
        }
    } catch (Exception $e) {
        $http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        //echo $http_code;
        //trigger_error("Number cannot be less than 10");
        //Logger::save($e);
        curl_close($ch);

如上所示,$ http_code返回我错误响应代码,现在我想将该错误记录在logger.php文件中,我同时尝试使用trigger_error和Logger::save()方法,但无法记录我的自定义错误

最佳答案

每当我们直接定义文件路径(如您的案例“error.json”)时,如果我们未指定其他目录位置,但通常不会发生,则假定必须在当前目录中创建该文件路径。

我也面临很多时间,因为它总是在其他位置创建文件。这就是在PHP中引入 DIR 的原因。

通过使用 DIR ,您可以获取当前目录的位置,然后创建文件,例如:

$file = __DIR__.'/error.json';

这将确保在当前目录中创建error.json。但是,如果要在日志目录中创建日志,请首先通过在项目的配置文件中定义一个全局变量来指定日志目录的位置,如下所示:
define("LOG", (dirname(dirname(__DIR__)));

根据需要使用目录名。就像如果存在层次结构var-> log和var-> log-> html->您的项目-> config.php一样,您将使用dirname两次,如上所述,因为log和config文件目录之间有2个目录间隙。

在创建LOG全局变量之后,您可以在项目的任何文件中使用它,并且始终使用以下命令获得正确的路径,而不管文件的位置如何:
$file = LOG.'/error.json';

关于php - 如何在php中实现错误记录器文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57572461/

相关文章:

php - 将 2 行合并为一个结果 MySQL

php - 使用不同类的 Android 发送 Json 对象

error-handling - Redux-全局错误处理程序

ios - Swift 单元测试从闭包内部抛出函数

optimization - Adam 优化器错误 : one of the variables needed for gradient computation has been modified by an inplace operation

javascript - 在Chrome/Firefox开发者工具中,是否可以隐藏除前两个错误以外的所有错误? (由于React提供了很多垃圾错误)

php - 使 WooCommerce 结帐运输字段可见并删除 "Ship to different address?"复选框

php - 无法让委托(delegate)方法发挥作用

php - 如果提供的函数中小时和分钟为零,则隐藏小时和分钟

ios - Swift 中的 func 会抛出什么类型的错误?