0

我刚刚写了一个小“日志”类,想问一个关于这个类的用法的问题,我怎样才能让它更容易使用。

例如:

$log = new Log();
$log->Error("You have an error!", __FILE__, __CLASS__, __FUNCTION__, __LINE__);

这就是我目前将错误写入日志文件的方式,但它似乎很复杂?!有没有办法从“调用” php 中获取日志类中的“MAGIC CONSTANTS”?

这是课程代码(也欢迎任何其他提示):

    <?php
    class Log
    {   
        private $path;

        public function __construct()
        {
            $config = new Config();         // init. from autoloader
            $path = $config->app_log_dir;

            if (!is_dir($path) && !is_writable($path))
            {
                error_log('[ERROR] [Log::__Construct()] -> ' . $path . ' does not exist or is not writeable!',0);
                header("HTTP/1.0 500 Internal Server Error");
                exit();
            }

            $this->path = $path;
        }

        public function Error($message, $file, $class = '', $function = '', $line)
        {
            $array_data = array($message, $file, $class, $function, $line);
            $this->write('ERROR', $array_data);
        }

        public function TestError($message, $file = __FILE__, $class = __CLASS__, $function = __FUNCTION__, $line = __LINE__)
        {
            $array_data = array($message, $file, $class, $function, $line);
            $this->write('TESTERROR', $array_data);
        }

        private function write($error_type, $array_data)
        {
            $date = date("Y-m-d H:i:s");
            $dateFile = date("Y-m-d");      

            $message = "[{$date}] [{$error_type}] [{$array_data[1]}->{$array_data[2]}::{$array_data[3]}:{$array_data[4]}] $array_data[0]".PHP_EOL;

            try 
            {
                file_put_contents($this->path.'/'.$dateFile.'.log', $message, FILE_APPEND);
            }
            catch (Exception $e)
            {
                error_log('[ERROR] [Log::write()] -> ' . $e, 0);
                header("HTTP/1.0 500 Internal Server Error");
                exit();
            }
        }
    }  
4

2 回答 2

1

退房debug_backtrace()

所以你可以这样做:

public function Error($message, $debug)
{
    $array_data = array($message, $debug);
    $this->write('ERROR', $array_data);
}

$log->Error("Oh noo!!", print_r(debug_backtrace(),true) );

回溯可能包含大量数据,因此我不会在这里举例说明完整的数据,但它可以包含:

  • function; 当前函数名称。另见__FUNCTION__。
  • line; 当前行号。另见__LINE__。
  • file; 当前文件名。另见 __FILE__。
  • class ; 当前类名。另见 __CLASS__。
  • object; 当前对象。
  • type; 当前呼叫类型。如果是方法调用,->则返回“”。如果是静态方法调用,::则返回“”。如果是函数调用,则不返回任何内容。
  • args; 如果在函数内部,则列出函数参数。如果在包含的文件中,则会列出包含的文件名。

debug_backtrace()是调试 PHP 的信息金矿。这涵盖了您在问题中要求的所有内容。

于 2019-03-01T19:53:30.270 回答
1

将这些常量作为函数参数传递:

public function Error(
    $message,
    $file = __FILE__,
    $class = __CLASS__,
    $function = __FUNCTION__,
    $line = __LINE__,
) {
    // ...
}

和往常一样打电话:

$log->Error('xxx');

如果可以的话,你的代码有异味,为什么不使用像Monolog这样的 PSR-3 兼容记录器?甚至可以像使用Whoops的专业人士一样处理错误。

于 2019-03-01T19:35:00.653 回答