Codeigniter вывод ошибок

Toggle Table of Contents

CodeIgniter lets you build error reporting into your applications using
the functions described below. In addition, it has an error logging
class that permits error and debugging messages to be saved as text
files.

Note

By default, CodeIgniter displays all PHP errors. You might
wish to change this behavior once your development is complete. You’ll
find the error_reporting() function located at the top of your main
index.php file. Disabling error reporting will NOT prevent log files
from being written if there are errors.

Unlike most systems in CodeIgniter, the error functions are simple
procedural interfaces that are available globally throughout the
application. This approach permits error messages to get triggered
without having to worry about class/function scoping.

CodeIgniter also returns a status code whenever a portion of the core
calls exit(). This exit status code is separate from the HTTP status
code, and serves as a notice to other processes that may be watching of
whether the script completed successfully, or if not, what kind of
problem it encountered that caused it to abort. These values are
defined in application/config/constants.php. While exit status codes
are most useful in CLI settings, returning the proper code helps server
software keep track of your scripts and the health of your application.

The following functions let you generate errors:

show_error($message, $status_code, $heading = ‘An Error Was Encountered’)
Parameters:
  • $message (mixed) – Error message
  • $status_code (int) – HTTP Response status code
  • $heading (string) – Error page heading
Return type:

void

This function will display the error message supplied to it using
the error template appropriate to your execution:

application/views/errors/html/error_general.php

or:

application/views/errors/cli/error_general.php

The optional parameter $status_code determines what HTTP status
code should be sent with the error. If $status_code is less
than 100, the HTTP status code will be set to 500, and the exit
status code will be set to $status_code + EXIT__AUTO_MIN.
If that value is larger than EXIT__AUTO_MAX, or if
$status_code is 100 or higher, the exit status code will be set
to EXIT_ERROR.
You can check in application/config/constants.php for more detail.

show_404($page = », $log_error = TRUE)
Parameters:
  • $page (string) – URI string
  • $log_error (bool) – Whether to log the error
Return type:

void

This function will display the 404 error message supplied to it
using the error template appropriate to your execution:

application/views/errors/html/error_404.php

or:

application/views/errors/cli/error_404.php

The function expects the string passed to it to be the file path to
the page that isn’t found. The exit status code will be set to
EXIT_UNKNOWN_FILE.
Note that CodeIgniter automatically shows 404 messages if
controllers are not found.

CodeIgniter automatically logs any show_404() calls. Setting the
optional second parameter to FALSE will skip logging.

log_message($level, $message)
Parameters:
  • $level (string) – Log level: ‘error’, ‘debug’ or ‘info’
  • $message (string) – Message to log
Return type:

void

This function lets you write messages to your log files. You must
supply one of three “levels” in the first parameter, indicating what
type of message it is (debug, error, info), with the message itself
in the second parameter.

Example:

if ($some_var == '')
{
        log_message('error', 'Some variable did not contain a value.');
}
else
{
        log_message('debug', 'Some variable was correctly set');
}

log_message('info', 'The purpose of some variable is to provide some value.');

There are three message types:

  1. Error Messages. These are actual errors, such as PHP errors or
    user errors.
  2. Debug Messages. These are messages that assist in debugging. For
    example, if a class has been initialized, you could log this as
    debugging info.
  3. Informational Messages. These are the lowest priority messages,
    simply giving information regarding some process.

Note

In order for the log file to actually be written, the
logs/ directory must be writable. In addition, you must
set the “threshold” for logging in
application/config/config.php. You might, for example,
only want error messages to be logged, and not the other
two types. If you set it to zero logging will be disabled.

Обработка ошибок

CodeIgniter позволяет создавать отчеты об ошибках в приложениях, используя функции описанные ниже. Кроме того, он имеет класс ведения журнала ошибок, который позволяет сохранять ошибки и отладочные сообщения в виде текстовых файлов.

Примечание

По умолчанию, CodeIgniter отображает все PHP ошибки. При желании, вы можете изменить это поведение как только завершите разработку. Вы найдете error_reporting() функцию расположенную в верхней части основного файла index.php. Отключение отчетов об ошибках не помешает записывать лог файлы при возникновении ошибок.

В отличии от большинства систем CodeIgniter, функциям ошибок свойственны простые процедурные интерфейсы, которые глобально доступны для всего приложения. Этот подход позволяет получать сообщения об ошибках, не беспокоясь об обзоре класс/функция .

CodeIgniter также возвращает код состояния, всякий раз когда ядро вызывает exit(). Этот код состояния отличный от HTTP кода состояния, и уведомляет другие процессы был ли сценарий завершен успешно или нет, и что за проблема повлекла прерывание. Эти значения определены в application/config/constants.php. Эти коды состояния наиболее полезны при использовании CLI параметров, возвращаемых надлежащий код серверного обеспечения помогающий отслеживать ваши скрипты и состояние ваших приложений.

Следующие функции позволяют генерировать ошибки:

show_error($message, $status_code, $heading = ‘Произошла Ошибка’)
Параметры:
  • $message (смешаный) – Сообщение об ошибке
  • $status_code (число) – HTTP код состояния ответа
  • $heading (строка) – Заголовок страницы с ошибкой
Возвращаемый тип:

пустота

Эта функция отобразит сообщение об ошибке через шаблон ошибки, соответствующего вашему исполнению:

application/views/errors/html/error_general.php

or:

application/views/errors/cli/error_general.php

Необязательный параметр $status_code обозначает что код состояния HTTP должен быть отправлен с ошибкой. Если $status_code меньше 100, код состояния HTTP будет иметь значение 500, и выход кода состояния будет иметь значение $status_code + EXIT__AUTO_MIN. Если это значение больше, чем EXIT__AUTO_MAX, или $status_code 100 или выше, выход кода состояния будет установлен EXIT_ERROR. Вы можете ознакомиться в application/config/constants.php более подробно.

show_404($page = », $log_error = TRUE)
Параметры:
  • $page (строка) – URI строка
  • $log_error (булево (bool)) – Нужно ли регистрировать ошибки
Возвращаемый тип:

пустота

Эта функция отобразит сообщение об ошибке 404 используя шаблон ошибки, соответствующего вашему исполнению:

application/views/errors/html/error_404.php

or:

application/views/errors/cli/error_404.php

Функция ожидает что ей передадут строку, являющуюся путем к файлу на ненайденную страницу. Выход кода состояния будет установлен в EXIT_UNKNOWN_FILE. Обратите внимание, CodeIgniter автоматически показывает ошибки 404 если контроллер не найден.

CodeIgniter автоматически регистрирует все show_404() вызовы. Необязательный второй параметр FALSE будет пропускать ведение журнала.

log_message($level, $message, $php_error = FALSE)
Параметры:
  • $level (строка) – Уровень журнала: ‘ошибка (error)’, ‘отладка (debug)’ или ‘инфо (info)’
  • $message (строка) – Сообщение журнала
  • $php_error (булево (bool)) – Записывать ли родные сообщения об ошибках PHP
Возвращаемый тип:

пустота

Эта функция позволяет записывать сообщения в лог файлы. Необходимо указать один из трех “уровней” первым параметром, указывая на тип сообщения (debug, error, info), с сообщением во втором параметре.

Example:

if ($some_var == '')
{
        log_message('error', 'Some variable did not contain a value.');
}
else
{
        log_message('debug', 'Some variable was correctly set');
}

log_message('info', 'The purpose of some variable is to provide some value.');

Существует три типа сообщений:

  1. Сообщения об ошибках. Эти фактические ошибки, такие как ошибки PHP или ошибки пользователя.
  2. Сообщения отладки. Это сообщения, которые помогают в отладке. Например, если класс был инициализирован, это может являться в качестве отладочной информации.
  3. Информационные сообщения. Они имеют самый низкий приоритет сообщений, просто давая информацию относительно некоторых процессов.

Примечание

Для того чтобы файл журнала на самом деле велся, категория logs/ должна быть доступна для записи. Кроме того, вы должны установить “порог” для ведения журналов application/config/config.php. Вы могли бы, например, записывать в журнал только сообщения об ошибках, а не двух других типов. Если вы установите его равным нулю, то ведение журнала будет отключено.

CodeIgniter builds error reporting into your system through Exceptions, both the SPL collection, as
well as a few custom exceptions that are provided by the framework. Depending on your environment’s setup,
the default action when an error or exception is thrown is to display a detailed error report unless the application
is running under the production environment. In this case, a more generic message is displayed to
keep the best user experience for your users.

  • Using Exceptions

  • Configuration

    • Logging Exceptions

  • Framework Exceptions

    • PageNotFoundException

    • ConfigException

    • DatabaseException

    • RedirectException

  • Specify HTTP Status Code in Your Exception

  • Specify Exit Code in Your Exception

  • Logging Deprecation Warnings

Using Exceptions

This section is a quick overview for newer programmers, or for developers who are not experienced with using exceptions.

Exceptions are simply events that happen when the exception is “thrown”. This halts the current flow of the script, and
execution is then sent to the error handler which displays the appropriate error page:

<?php

throw new Exception('Some message goes here');

If you are calling a method that might throw an exception, you can catch that exception using a try/catch block:

<?php

try {
    $user = $userModel->find($id);
} catch (Exception $e) {
    exit($e->getMessage());
}

If the $userModel throws an exception, it is caught and the code within the catch block is executed. In this example,
the scripts dies, echoing the error message that the UserModel defined.

In the example above, we catch any type of Exception. If we only want to watch for specific types of exceptions, like
a UnknownFileException, we can specify that in the catch parameter. Any other exceptions that are thrown and are
not child classes of the caught exception will be passed on to the error handler:

<?php

try {
    $user = $userModel->find($id);
} catch (CodeIgniterUnknownFileException $e) {
    // do something here...
}

This can be handy for handling the error yourself, or for performing cleanup before the script ends. If you want
the error handler to function as normal, you can throw a new exception within the catch block:

<?php

try {
    $user = $userModel->find($id);
} catch (CodeIgniterUnknownFileException $e) {
    // do something here...

    throw new RuntimeException($e->getMessage(), $e->getCode(), $e);
}

Configuration

By default, CodeIgniter will display all errors in the development and testing environments, and will not
display any errors in the production environment. You can change this by setting the CI_ENVIRONMENT variable
in the .env file.

Important

Disabling error reporting DOES NOT stop logs from being written if there are errors.

Logging Exceptions

By default, all Exceptions other than 404 — Page Not Found exceptions are logged. This can be turned on and off
by setting the $log value of app/Config/Exceptions.php:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Exceptions extends BaseConfig
{
    public $log = true;
}

To ignore logging on other status codes, you can set the status code to ignore in the same file:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Exceptions extends BaseConfig
{
    public $ignoredCodes = [404];
}

Note

It is possible that logging still will not happen for exceptions if your current Log settings
are not set up to log critical errors, which all exceptions are logged as.

Framework Exceptions

The following framework exceptions are available:

PageNotFoundException

This is used to signal a 404, Page Not Found error. When thrown, the system will show the view found at
app/Views/errors/html/error_404.php. You should customize all of the error views for your site.
If, in app/Config/Routes.php, you have specified a 404 Override, that will be called instead of the standard
404 page:

<?php

if (! $page = $pageModel->find($id)) {
    throw CodeIgniterExceptionsPageNotFoundException::forPageNotFound();
}

You can pass a message into the exception that will be displayed in place of the default message on the 404 page.

ConfigException

This exception should be used when the values from the configuration class are invalid, or when the config class
is not the right type, etc:

<?php

throw new CodeIgniterExceptionsConfigException();

This provides an exit code of 3.

DatabaseException

This exception is thrown for database errors, such as when the database connection cannot be created,
or when it is temporarily lost:

<?php

throw new CodeIgniterDatabaseExceptionsDatabaseException();

This provides an exit code of 8.

RedirectException

This exception is a special case allowing for overriding of all other response routing and
forcing a redirect to a specific route or URL:

<?php

throw new CodeIgniterRouterExceptionsRedirectException($route);

$route may be a named route, relative URI, or a complete URL. You can also supply a
redirect code to use instead of the default (302, “temporary redirect”):

<?php

throw new CodeIgniterRouterExceptionsRedirectException($route, 301);

Specify HTTP Status Code in Your Exception

New in version 4.3.0.

Since v4.3.0, you can specify the HTTP status code for your Exception class to implement
HTTPExceptionInterface.

When an exception implementing HTTPExceptionInterface is caught by CodeIgniter’s exception handler, the Exception code will become the HTTP status code.

Specify Exit Code in Your Exception

New in version 4.3.0.

Since v4.3.0, you can specify the exit code for your Exception class to implement
HasExitCodeInterface.

When an exception implementing HasExitCodeInterface is caught by CodeIgniter’s exception handler, the code returned from the getExitCode() method will become the exit code.

Logging Deprecation Warnings

New in version 4.3.0.

By default, all errors reported by error_reporting() will be thrown as an ErrorException object. These
include both E_DEPRECATED and E_USER_DEPRECATED errors. With the surge in use of PHP 8.1+, many users
may see exceptions thrown for passing null to non-nullable arguments of internal functions.
To ease the migration to PHP 8.1, you can instruct CodeIgniter to log the deprecations instead of throwing them.

First, make sure your copy of ConfigExceptions is updated with the two new properties and set as follows:

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;
use PsrLogLogLevel;

class Exceptions extends BaseConfig
{
    // ... other properties

    public bool $logDeprecations       = true;
    public string $deprecationLogLevel = LogLevel::WARNING; // this should be one of the log levels supported by PSR-3
}

Next, depending on the log level you set in ConfigExceptions::$deprecationLogLevel, check whether the
logger threshold defined in ConfigLogger::$threshold covers the deprecation log level. If not, adjust
it accordingly.

<?php

namespace Config;

use CodeIgniterConfigBaseConfig;

class Logger extends BaseConfig
{
    // .. other properties

    public $threshold = 5; // originally 4 but changed to 5 to log the warnings from the deprecations
}

After that, subsequent deprecations will be logged instead of thrown.

This feature also works with user deprecations:

<?php

@trigger_error('Do not use this class!', E_USER_DEPRECATED);
// Your logs should contain a record with a message like: "[DEPRECATED] Do not use this class!"

For testing your application you may want to always throw on deprecations. You may configure this by
setting the environment variable CODEIGNITER_SCREAM_DEPRECATIONS to a truthy value.

I had a line — $autoload['libraries'] = array('database');, in CI’s autoload.php. Because of this I was getting a blank page. When I removed the 'database', option then I started getting the output.

Now my question is not how to configure the database, but how to configure CI to speak its mind. When 'database' was enabled all I got was a complete blank page. No error in php log, no error in Apache log, no error in CI log. In PHP I have set E_ALL. In my CI config I have set log_threshold to 4, i.e. all messages should be logged. What more do I need to do?

asked Sep 10, 2011 at 7:52

AppleGrew's user avatar

5

It depends on your version of CI. For < 2.x edit the top level index.php and adjust the error_reporting function to use E_ALL»

error_reporting(E_ALL);

For >= 2.x edit the top level index.php and make sure ENVIRONMENT is set as:

define('ENVIRONMENT', 'development');

which sets the error_reporting to E_ALL.

answered Sep 10, 2011 at 10:16

davidethell's user avatar

davidethelldavidethell

11.6k6 gold badges41 silver badges62 bronze badges

2

Create a .htaccess file in your webroot with the following content

php_flag display_startup_errors on
php_flag display_errors on
php_flag html_errors on
php_flag log_errors on
php_flag ignore_repeated_errors off
php_flag ignore_repeated_source off
php_flag report_memleaks on
php_flag track_errors on
php_value error_reporting -1
php_value log_errors_max_len 0

Hopefully that should enable your logs.
Make sure to set the values to off and reporting to 0 on your production server :)

answered Sep 11, 2011 at 8:20

Dennis Rasmussen's user avatar

0

Following environment settings would gonna force PHP to display errors as they occur:

  • APPLICATION ENVIRONMENT
    define(‘ENVIRONMENT’, ‘development’);
    /*
  • ERROR REPORTING

    if (defined(‘ENVIRONMENT’))
    {
    switch (ENVIRONMENT)
    {
    case ‘development’:
    // Report all errors
    error_reporting(E_ALL);

            // Display errors in output
            ini_set('display_errors', 1);
            break;
    
        case 'testing':
        case 'production':
            // Report all errors except E_NOTICE
            // This is the default value set in php.ini
            error_reporting(E_ALL ^ E_NOTICE);
    
            // Don't display errors (they can still be logged)
            ini_set('display_errors', 0);
        break;
    
        default:
            exit('The application environment is not set correctly.');
    }
    

    }

Adrian Mole's user avatar

Adrian Mole

49.5k155 gold badges49 silver badges79 bronze badges

answered Sep 20, 2019 at 0:46

faryal rida's user avatar

faryal ridafaryal rida

3793 silver badges6 bronze badges

1

I am not sure what was the real reason but I had a PHP installation with left-over php.ini file. Later I installed the full WAMP stack with its own PHP. When I deleted the leftover php.ini file from the previous installation then it started working as it should. It seems the PHP binaries in the new installing was using using the left-over php.ini which was in totally different directory; maybe because that directory was in environment PATH.

answered Sep 11, 2011 at 18:38

AppleGrew's user avatar

AppleGrewAppleGrew

9,28224 gold badges78 silver badges124 bronze badges

Реализуем в фреймворке CodeIgniter отключение вывода ошибок на экран и настраиваем их запись в лог-файл. Также внесём в системе CI необходимые изменения, чтобы не показывались SQL-ошибки, но чтобы они логировались.

Хороший тон — в рабочем коде убирать вывод ошибок пользователю и перенаправлять его в лог-файл.

В CodeIgniter для этого необходимо установить следующие настройки:

1. Файл index.php

error_reporting(0);

2. Файл application/config/config.php

/** 
  0 = отключает логирование 
  1 = записывает только сообщения с ошибками 
  2 = добавляются отладочные сообщения 
  3 = добавляются информационные сообщения 
  4 = добавляются все оообщения 
**/ 
$config['log_threshold'] = 1; 
 
/** 
  По умолчанию логи сохраняются в папку system/logs/ 
  Либо, указывается свой путь к папке для лог-файлов. 
  Необходимо проверить права доступа у папки на запись 
**/ 
$config['log_path'] = '';

3. Файл application/config/database.php

/** 
  TRUE - ошибки базы данных отображаются 
  FALSE - ошибки базы данных не отображаются 
**/ 
$db['default']['db_debug'] = FALSE;

После всех этих настроек ошибки перестанут отображаться пользователю и будут записываться в лог-файлы. Все ошибки, кроме ошибок базы данных (SQL запросы)! Т.е. настройка $db[‘default’][‘db_debug’] = FALSE;
отвечает как за отображение, так и за запись в лог. Если TRUE – ошибка показывается пользователю и записывается в лог. FALSE – ни пользователю, ни в лог.
Или это ошибка, или такая задумка разработчиков CI, но явно неудобный момент.
Его и исправим
Открываем файл /system/database/DB_driver.php и ищем конструкции такого типа:

if ($this->db_debug) 
{ 
    log_message('error''Invalid query: '.$sql); 
    return $this->display_error('db_invalid_query'); 
}

И исправляем на такую:

log_message('error''Invalid query: '.$sql); 
if ($this->db_debug) 
{ 
    return $this->display_error('db_invalid_query'); 
}

Т.е. просто выносим вызов функции log_message из условия if.
Возможно, придется проделать немного больше правок, но суть понятна.
Например, в функции query выносим из проверочного условия

log_message('error''Query error: '.$error_msg); 

Значит, нужно вынести и $error_msg = $this->_error_message(); чтобы $error_msg была определена.

$error_msg = $this->_error_message(); 
log_message('error''Query error: '.$error_msg); 

Записываемые сообщения об ошибках БД не очень информативны, поэтому удобно добавлять и сам текст sql-запроса, в котором произошла ошибка.

log_message('error''Query error: '.$error_msg.' '.$sql);

Дальше следите за логами в папке system/logs и работайте над ошибками.

Понравилась статья? Поделить с друзьями:

Не пропустите эти материалы по теме:

  • Яндекс еда ошибка привязки карты
  • Codeblocks ошибка iostream
  • Codeblocks не показывает ошибки
  • Codeblocks компилятор ошибка
  • Codeblocks выдает ошибку при запуске

  • 0 0 голоса
    Рейтинг статьи
    Подписаться
    Уведомить о
    guest

    0 комментариев
    Старые
    Новые Популярные
    Межтекстовые Отзывы
    Посмотреть все комментарии