【问题标题】:Formatting error log using PDO使用 PDO 格式化错误日志
【发布时间】:2014-01-11 03:42:30
【问题描述】:

我希望错误日志以时间戳开头的新行显示每个错误。

目前错误只显示在连接的块中。

catch(PDOException $e) {
        file_put_contents('logs/insert_errors.txt', $e->getMessage(), FILE_APPEND);
    }   

我相信这很简单。只是我第一次使用 PDO,不知道如何完成。

【问题讨论】:

  • 这与 PDO 有什么关系?为什么不展示一个您希望错误日志看起来如何的示例,而不是一大堆无法解释您的问题的代码?
  • @Phil 我不小心将我的凭据粘贴到其中并匆忙删除了一大块。立即编辑
  • 该查询是否可以在 php 之外工作,例如在命令行或工作台中?
  • @MadeOfAir 这只是处理与我的问题相关的错误记录的部分。不过还有更多。

标签: php exception-handling error-logging


【解决方案1】:

序言:正如@Phil 所说,这与 PDO 无关。

您的问题分为两部分:

a) 都在一条连接线上

原因很明显,你没有在末尾添加换行符。该字符是什么取决于您的操作系统,但 PHP 使用 PHP_EOL 常量为您解决了这个问题,您可以将其附加到字符串的末尾。

b) 您希望在每行的开头添加一个时间戳

同样,问题是因为你没有把它放在那里。只需在打印出消息之前添加date('r') 的输出就足够了。

真正的解决方案:真正的记录器

您可能希望考虑为您的代码使用完整的日志记录解决方案。比如log4php。

自制解决方案

或者,如果太多,您可以构建自己的记录器。在comments of the documentation of PHP's error_log function 中可以找到一个很好的小示例,我根据您的需要进行了调整:

Class Log { 
    const ERROR_DIR = '/home/site/error_log/db_errors.log'; 

    // Log PDO errors
    public function error($msg) { 
        $date = date('r'); 
        $log = sprintf('%s: %s%s', $date, %msg, PHP_EOL); 
        error_log($log, 3, self::ERROR_DIR); 
    }

    // shortcut for PDO exceptions
    public function exception($e) {
        $this->error($e->getMessage())
    } 
} 

try {
    $log = new log(); 
    $log->error($msg); //use for general messages
} except (Exception $e)
    $log->exception($e); //use for exceptions
}

【讨论】:

    【解决方案2】:

    只需格式化要插入的字符串,例如

    catch (PDOException $e) {
        $error = sprintf('%s: %s%s', date('c'), $e->getMessage(), PHP_EOL);
        file_put_contents('logs/insert_errors.txt', $error, FILE_APPEND);
    
        // don't forget to re-throw the exception otherwise your program will
        // continue execution
        throw $e; 
    }
    

    【讨论】:

      猜你喜欢
      • 2019-08-28
      • 2023-03-20
      • 2015-06-23
      • 1970-01-01
      • 2017-10-02
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多