Где журнал ошибок php

I can guarantee you, I am not the only person who has been driven to madness at least once in a frustrating search for a log file. It seems like it should be the easiest thing to find in the whole system.

A definitive guide on where the PHP error log is stored would be a complicated bit of work. The official PHP manual does not even try to address the whole topic, because there are dependencies on systems outside PHP, such as the operating system (Linux vs. Windows, which distribution of Linux), including settings within Windows and Linux that affect the name and location of the PHP error log.

Until someone takes the time to write a complete, cross-system guide, the best you are going to get is general directions where you can inquire. Every PHP developer has had to endure agony in this pursuit, with one exception. If you work in one place and the information is provided when you first need it, then you have the information need forever, that is, until you find yourself in a new working environment. There are such fortunate people.

If the information is not given to you on a silver platter, so to speak, you have some hunting to do. The hunt is not the longest you will face in your career, but it is not the simplest either.

As is evident from the many answers already posted, a smart place to begin is the output of phpinfo(). To view it, create a PHP file containing this:

<?php
    phpinfo();

Either browse to that file or run it from the command line. If you do both, you likely will find the error_log is in different places, depending on command line vs. web server use of PHP. That is because the PHP interpreter that runs on a web server is not the same PHP interpreter that runs from the command line, even when the command line is on the same machine as the web server. The answers already posted in here mostly are making an unstated assumption that PHP is running as part of a web server.

Sample output from phpinfo() via web server and web browser

The default for error_log is no value

Default error_log in php running as an Apache mod.

Whatever the value is, it comes from the php.ini files used to configure PHP. There can be many php.ini files. Finding your way among them is confusing at first, but you do not need to deal with this to find your PHP log.

If the output from phpinfo() shows a full path to a file, that is where the log is. You are lucky.

The trick is there usually is not a full path indicated in phpinfo(). When there is not a full path, the location depends on:

  1. Whether error_log is no value. If it is, the log file location will depend on the operating system and the mode PHP is running. If PHP is running as an Apache module, on Linux the log often is in /var/log/apache2/error.log. Another likely spot is in a logs directory in your account home directory, ~/logs/error.log.

  2. If there is a file name without a path, the location depends on whether the file name has the value syslog. If it syslog, then the PHP error log is injected into the syslog for the server, which varies by Linux distribution. A common location is /var/log/syslog, but it can be anywhere. Even the name of the syslog varies by distribution.

  3. If the name without a path is not syslog, a frequent home for the file is is the document root of the website (a.k.a., website home directory, not to be confused with the home directory for your account).

This cheat sheet has been helpful in some situations, but I regret to have to admit it is not nearly universal. You have my condolences.

Enter image description here

Vitaily

А если в php.ini прописан этот файл так, как вы здесь указали (и phpinfo() выводит это), стоят права на этот файл 644 (rw-r—r—), пользователем установлен www-data, но логирование в этот файл не происходит? Апач перегружен несколько раз…

Что может быть сделано не так?

Reply

admin

Апач в процессах работает от этого пользователя?
LOG_ERRORS = 1, так же попробуйте изменить уровень логирования. Проверьте права на паку выше.

Reply

Как посмотреть логи PHP

Логи PHP — это важный инструмент для отслеживания ошибок и предупреждений, возникающих во время работы вашего веб-приложения. В этой статье мы рассмотрим, как найти и просмотреть логи PHP на вашем сервере.

1. Определение местоположения логов PHP

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

  • Для Linux: /var/log/php_errors.log или /var/log/httpd/error_log
  • Для Windows (WAMP, XAMPP): C:\wamp\logs\php_error.log или C:\xampp\php\logs\php_error_log

Вы также можете проверить значение директивы error_log в файле конфигурации php.ini для определения местоположения файла логов на вашем сервере:

error_log = /path/to/your/php_error.log

2. Просмотр логов PHP

После того как вы определили местоположение файла логов PHP, вы можете просмотреть его содержимое. В зависимости от вашего предпочтения и доступных инструментов, вы можете использовать различные методы:

  • С помощью текстового редактора (Notepad, Vim, Nano и т.д.)
  • С помощью командной строки (например, команда tail в Linux)
  • С помощью FTP-клиента (если логи находятся на удаленном сервере)
  • С помощью специализированных инструментов для просмотра логов

3. Разбор ошибок и предупреждений в логах

При просмотре логов PHP, обратите внимание на типы сообщений об ошибках и предупреждениях. Это поможет вам определить причину возникновения проблемы и разработать стратегию ее решения. Вот некоторые типы ошибок и предупреждений, которые могут встретиться в логах PHP:

  • Parse error — синтаксическая ошибка в коде, которую необходимо исправить;
  • Fatal error — критическая ошибка, которая приводит к остановке выполнения скрипта;
  • Warning — предупреждение о потенциальной проблеме, которое не останавливает выполнение скрипта, но может вызвать нежелательное поведение;
  • Notice — уведомление о возможной проблеме, которая не влияет на работу скрипта, но может указывать на проблемы в коде или настройках сервера.

4. Исправление ошибок и предупреждений

После того как вы определили тип ошибки или предупреждения, вы можете приступить к исправлению проблемы. В большинстве случаев, вам придется изменить исходный код вашего веб-приложения. Возможно, потребуется также настроить сервер или обновить используемые библиотеки и компоненты.

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

5. Мониторинг логов PHP

Регулярное просматривание логов PHP поможет вам оперативно обнаруживать и исправлять ошибки и предупреждения, возникающие в вашем веб-приложении. Вы также можете использовать специализированные инструменты и сервисы для мониторинга логов, которые автоматизируют процесс сбора, анализа и оповещения о возникающих проблемах.

Теперь вы знаете, как найти и просмотреть логи PHP на вашем сервере, а также как разбираться с ошибками и предупреждениями. Это поможет вам поддерживать стабильную и безопасную работу вашего веб-приложения.

как посмотреть логи пхп

Я арендовал виртуальный хостинг и использую Cpanel, Apache, PHP, который работает под управлением fastcgi. Где PHP хранит журнал ошибок?

Есть ли другой способ найти журнал ошибок в среде общего хостинга вместо того, чтобы просматривать всю структуру сайта в поисках файлов error_log?

У меня есть доступ к php.ini (я использую PHP версии 5.2.16).

Ответ 1

PHP сохраняет журналы ошибок в папке /var/log/apache2, если PHP является модулем apache2. Общие хосты часто хранят файлы журналов в подпапке корневого каталога /log. Но, если у вас есть доступ к php.ini файлу, вы можете сделать это:

error_log = /var/log/php-scripts.log

Если вы используете cPanel, главный файл журнала, который вы, вероятно, ищете, хранится (по умолчанию) в:

/usr/local/apache/logs/error_log

Если ничего не помогает, вы можете проверить расположение файла журнала, используя:

<?php phpinfo(); ?>

Ответ 2

В Linux:

php —info | grep error 

Терминал выведет местоположение журнала ошибок.

В Windows:

php —info | findstr /r /c:»error_log»

Командная строка выведет местоположение журнала ошибок.

Чтобы установить местоположение журнала:

Откройте php.ini и добавьте следующую строку:

error_log = /log/myCustomLog.log

Ответ 3

В среде LAMP ошибки php по умолчанию направляются в этот файл:

/var/log/httpd/error_log

Все журналы доступа находятся здесь:

/var/log/httpd/access_log

Ответ 4

Как найти журнал ошибок PHP в Linux:

eric@dev /var $ sudo updatedb

[sudo] password for eric:

eric@dev /var $ sudo locate error_log

/var/log/httpd/error_log

Альтернативный способ:

eric@dev /home/eric $ sudo find / -name «error_log» 2>/dev/null

/var/log/httpd/error_log

Ответ 5

Необходимо использовать абсолютный путь при установке переменной error_log в вашем файле php.ini, иначе журналы ошибок будут сохраняться в соответствии с вашим относительным путем.

error_log = /var/log/php.errors

Другое решение — написать простой скрипт, который будет перечислять все файлы журналов ошибок из дерева каталогов.

Ответ 6

По умолчанию php нигде не регистрирует журнал ошибок error_log. В php.ini параметр закомментирован во всех установках, которые я видел.

Возможные решения:

  1. ищите файлы php.ini. в locate php.ini;

  2. ищите в этих файлах error_reporting значение;

  3. проверяйте error_log значение, чтобы убедиться, что оно указывает на реальное место и не закомментировано.

Ответ 7

Лучше всего заглянуть в файл httpd.conf и посмотреть, что установлено по умолчанию. Он также может быть отменен вашим конкретным виртуальным хостом. Я начинаю с просмотра /etc/httpd/conf/httpd.conf или /etc/apache2/httpd.conf и ищу error_log. Он может быть указан как /var/log/httpd/error_log или /var/log/apache2/error_log как logs/error_log.

В этом случае это будет относительный путь, который означает, что он будет указывать на /etc/httpd/logs/error_log. Если вы все еще не можете его найти, посмотрите на конечную часть файла httpd.conf и посмотрите, где включены ваши виртуальные хосты. Он может находиться в /etc/httpd/conf.d/<- как «другой» или «дополнительный». Ваш виртуальный хост может переопределить его с помощью ErrorLog «/path/to/error_log».

The location of the error log file can be check by using phpinfo() function. Create a simple PHP file containing phpinfo() function and run it. It will display the information about PHP configuration.

Run the above program and search for error_log directive using f3 on chrome. This will show the location of the logfile. Following is an example run on WAMP server, but the procedures will be the same as described below for every development stack.

phpinfo()

Open your php.ini file as specified and edit following directives to specify the path of the error log file to some other location.

display_errors = Off

Then you have to give the path to your log file via error_log directive as follows:

logfile
You can find the path to the php.ini file directly using the following command on UNIX/Linux.

php -i | grep php.ini

PHP contains a simple and effective solution to display all log errors into the log file. It is mandatory to turn off displaying error on the server to the end user using a web browser. PHP gives lots of information related to the path, database schema and all other sorts of sensitive information. It strongly advises using error logging in place of error displaying on production web sites. This idea is helpful in displaying the error log to the developer only. PHP offers to log all the errors in a log file instead of displaying the error to the end users via a web browser. To do this first you have to turn off displaying error via a browser in the php.ini file, by setting the display_errors directive to off as mentioned above. Then you have to give the path to your log file via error_log directive as follows:
Ex: error_log = /var/log/php-scripts.log, errors will be logged in php-scripts.log file.

Last Updated :
23 Apr, 2019

Like Article

Save Article

Понравилась статья? Поделить с друзьями:
  • Гас управление ошибка при установлении защищенного соединения
  • Где допущены ошибки о тяжком бремени
  • Гбо 4 поколения ловато коды ошибок
  • Где допущена ошибка выбери правильный ответ количество колеблется
  • Гауссовский интеграл ошибок таблица