如何在 CodeIgniter (PHP) 中进行错误日志记录

问题描述 投票:0回答:6

我想要在 PHP CodeIgniter 中记录错误。如何启用错误日志记录?

我有一些问题:

  1. 记录错误的所有步骤是什么?
  2. 错误日志文件是如何创建的?
  3. 如何将错误消息推送到日志文件中(每当发生错误时)?
  4. 如何通过电子邮件将该错误发送到电子邮件地址?
php codeigniter logging error-handling
6个回答
209
投票

CodeIgniter 内置了一些错误记录功能。

  • 使您的 /application/logs 文件夹可写
  • /application/config/config.php 设置
    $config['log_threshold'] = 1;

    或使用更高的数字,具体取决于您想要在日志中包含多少详细信息
  • 使用
    log_message('error', 'Some variable did not contain a value.');
  • 要发送电子邮件,您需要扩展核心 CI_Exceptions 类方法
    log_exceptions()
    。您可以自己执行此操作或使用this。有关扩展核心的更多信息这里

参见 http://www.codeigniter.com/user_guide/general/errors.html


27
投票

要简单地在服务器的错误日志中添加一行,请使用 PHP 的 error_log() 函数。但是,该方法不会发送电子邮件。

首先,触发错误:

trigger_error("Error message here", E_USER_ERROR);

默认情况下,这将进入服务器的错误日志文件。请参阅 Apache 的ErrorLog 指令。设置您自己的日志文件:

ini_set('error_log', 'path/to/log/file');

请注意,您选择的日志文件必须已经存在并且可由服务器进程写入。使文件可写的最简单方法是使服务器用户成为文件的所有者。 (服务器用户可能是 nobody、_www、apache 或其他用户,具体取决于您的操作系统发行版。)

要通过电子邮件发送错误,您需要设置自定义错误处理程序:

function mail_error($errno, $errstr, $errfile, $errline) {
  $message = "[Error $errno] $errstr - Error on line $errline in file $errfile";
  error_log($message); // writes the error to the log file
  mail('[email protected]', 'I have an error', $message);
}
set_error_handler('mail_error', E_ALL^E_NOTICE);

请参阅相关 PHP 文档了解更多信息。


4
投票

还要确保您已允许 codeigniter 在配置文件中记录您想要的消息类型。

$config['log_threshold'] = [log_level ranges 0-4];


4
投票
In config.php add or edit the following lines to this:
------------------------------------------------------
$config['log_threshold'] = 4; // (1/2/3)
$config['log_path'] = '/home/path/to/application/logs/';

Run this command in the terminal:
----------------------------------
sudo chmod -R 777 /home/path/to/application/logs/

1
投票

有关问题第 4 部分的更多内容 如何通过电子邮件将该错误发送到电子邮件地址? error_log 函数也有电子邮件目的地。 http://php.net/manual/en/function.error-log.php

Agha,在这里我找到了一个显示用法的示例。 使用 error_log() 通过电子邮件发送错误消息

error_log($this->_errorMsg, 1, ADMIN_MAIL, "Content-Type: text/html; charset=utf8\r\nFrom: ".MAIL_ERR_FROM."\r\nTo: ".ADMIN_MAIL);

0
投票

启用日志记录

机器:Mac OS - Intel 芯片

是的,您可以为本地主机启用它。只需转到 src/customers/application/config/config.php 并添加

$config['log_threshold'] = 1;
$config['log_path'] = '/Applications/XAMPP/logs/';

并重新启动服务器

示例:
我在文件中添加了以下 log_message 语句:src/customers/application/views/admin/orders/view.php

log_message('info', 'Inside view.php file');
log_message('debug', 'Inside view.php file');
log_message('error', 'Inside view.php file');

生成的日志文件格式:log-YYYY-MM-DD.php内部位置/Applications/XAMPP/logs/

© www.soinside.com 2019 - 2024. All rights reserved.