Лог ошибок php wordpress

WordPress логи - логирование ошибок и действий на сайте

Диагностика проблем, возникающих на сайте WordPress, может оказаться сложной. Наглядный способ проследить появление ошибок и получить обратную связь – использование журнала логов. Изучение записей в логах позволит выяснить причину проблемы и устранить ее.

Где хранится лог ошибок ВордПресс и как его посмотреть

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

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

Фактический журнал логов хранится в файле с именем debug.log в каталоге содержимого вашего сайта wp-content на сервере хостинг-провайдера. Как посмотреть логи? Один из способов просмотра и очистки журнала – прямой доступ к этому файлу. Скачайте файл с помощью файлового менеджера и откройте его любым текстовым редактором. Можно воспользоваться плагинами, которые упрощают работу с логами.

вордпресс логи

Можно ли удалять логи? Файл с отладочной информацией и уведомлениями об ошибках со временем может разрастись до внушительных размеров. Поэтому, если ваш сайт работает нормально, то старые логи можно удалить, чтобы освободить рабочее пространство.

Как включить/выключить логирование

Чтобы включить создание лог-журнала для сайта на WordPress, понадобится внести изменения в системный файл wp-config.php, который расположен на сервере хостинга.

  1. Запустите файловый менеджер и подключитесь к удаленному серверу со своей учетной записью, который вам предоставил хостинг-провайдер.
  2. Перейдите в корневой каталог, где установлен ваш сайт.
  3. Сделайте резервную копию файла wp-config.php, чтобы восстановить систему после завершения отладки.

Откройте файл wp-config.php на удаленном сервере, вставьте или отредактируйте строки, которые управляют созданием логов:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_DISPLAY', false );
define( 'WP_DEBUG_LOG', true );

Большинство сайтов на WordPress уже имеют запись для константы WP_DEBUG, установленную в значение false, поэтому вам нужно изменить это значение на true. Строка с WP_DEBUG_LOG может отсутствовать, поэтому придется ее добавить, эта команда активирует создание журнала логов для сайта. Константа WP_DEBUG_DISPLAY, установленная в значение false, поможет скрыть запись логов от посетителей сайта. Убедитесь, что каждая константа определена в файле только один раз.

вордпресс конфиг

Лог действий в WordPress

После того как запись логов включена, перейдите в папку содержимого сайта на WordPress. Обычно она называется wp-content, если вы не переименовали ее ранее. Откройте файл журнала debug.log, перейдите в конец и найдите строки с метками времени, соответствующими вашим недавним действиям над сайтом.

Каждый раз, когда возникает предупреждение или ошибка в работе сайта, WordPress генерирует уведомление, которое записывается в журнал логов с отметкой времени в формате UTC. По этим причинам на работающем сайте рекомендуется оставить WP_DEBUG включенным. Устраните выявленные проблемы, при необходимости восстановите оригинальный файл wp-config.php.

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

Плагины для логирования действий

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

Activity Log – популярный плагин с большим количеством активных установок. Позволяет записать хронологию действий пользователей, их вход в админку и выход. Будут зафиксированы последние действия со страницами и записями, удаление и установка тем и плагинов.

WP Security Audit Log – плагин для мониторинга действий пользователей в админке сайта. Можно использовать для ведения лог-журнала электронного магазина WooCommerce и отслеживать изменение состояния продукта. Плагин создает предупреждение о безопасности, когда в системе создается новый пользователь, и позволяет отследить подозрительную активность, прежде чем это станет проблемой безопасности.

WP Log Viewer – плагин создает виджет панели администратора и позволяет включить/отключить запись лога одним щелчком мыши, при этом не требуется вручную редактировать файл wp-config.php. Можно выполнить фильтрацию ошибок, очистить журнал, сортировать записи по дате или провести поиск ошибок по времени. Пользовательские ошибки обозначаются разными цветами.

Error Log Monitor – этот плагин добавляет виджет, который видим только для администраторов. Он отображает последние сообщения из журнала логов, а также умеет отправлять уведомления по электронной почте о новых возникших ошибках. Частота уведомлений и количество отображаемых записей в журнале настраивается. Плагин оптимизирован для работы с очень большими лог-файлами.

iPipe – надёжный хостинг-провайдер с опытом работы более 15 лет.

Мы предлагаем:

  • Виртуальные серверы с NVMe SSD дисками от 299 руб/мес
  • Безлимитный хостинг на SSD дисках от 142 руб/мес
  • Выделенные серверы в наличии и под заказ
  • Регистрацию доменов в более 350 зонах

Темы

  • WP_DEBUG
    • PHP ошибки, предупреждения, и заметки
    • Устаревшие функции и аргументы
  • WP_DEBUG_LOG
  • WP_DEBUG_DISPLAY
  • SCRIPT_DEBUG
  • SAVEQUERIES
  • Пример файла wp-config.php для отладки
  • Плагины для отладки
  • Внешние ссылки

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

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

WP_DEBUG

WP_DEBUG это константа PHP , используемая для установки режима отладки в WordPress. По умолчанию она имеет значение «false», но может быть установлена как «true» в файле конфигурации wp-config.php на сайтах, на которых проводится отладка.

define( 'WP_DEBUG', true );
define( 'WP_DEBUG', false );

Заметка: значения true и false в примере не заключены в кавычки или апострофы, поскольку являются булевыми (правда/ложь) значениями. Не заключайте их в кавычки (например 'false'), иначе они станут восприниматься как строковые значения.

Не рекомендуется включать WP_DEBUG или другие инструменты отладки на рабочих сайтах, отладку рекомендуется производить при локальном тестировании или на разрабатываемых сайтах.

Наверх ↑

PHP ошибки, предупреждения, и заметки

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

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

Заметка: Не стоит самостоятельно заниматься исправлением кода ядра, плагинов, тем. Сообщите о проблеме разработчикам соответствующих компонентов, чтобы они внесли исправления в будущих версиях.

Наверх ↑

Устаревшие функции и аргументы

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

Наверх ↑

WP_DEBUG_LOG

WP_DEBUG_LOG это дополнение к WP_DEBUG которое позволяет сохранять ошибки в файл debug.log. Это полезно если вы хотите посмотреть ошибки позже или посмотреть то, что не выводится на экран (например для AJAX запросов или работы wp-cron).

Заметьте, что запись в лог производится внутренней функцией PHP error_log(), она очень удобна для отладки событий AJAX.

При установке в значение true, журнал будет сохраняться как wp-content/debug.log на вашем сайте. Вы можете задать альтернативное имя, для сохранения его в другом месте.

define( 'WP_DEBUG_LOG', true );
-или-
define( 'WP_DEBUG_LOG', '/tmp/wp-errors.log' );

Заметка: Для работы WP_DEBUG_LOG нужно включить WP_DEBUG (true). Вы можете независимо от этого отключить WP_DEBUG_DISPLAY.

Наверх ↑

WP_DEBUG_DISPLAY

WP_DEBUG_DISPLAY это другое дополнение для WP_DEBUG, которое контролирует вывод сообщений отладки в HTML код страницы (на экран). Значение по умолчанию — ‘true’, что позволяет видеть ошибки и предупреждения на экране, в момент их возникновения. Установка значения как false спрячет все ошибки, что можно использовать вместе с WP_DEBUG_LOG, чтобы просмотреть ошибки из файла позже.

define( 'WP_DEBUG_DISPLAY', false );

Заметка: Для работы WP_DEBUG_LOG нужно включить WP_DEBUG (true). Вы можете независимо от этого использовать WP_DEBUG_LOG

Наверх ↑

SCRIPT_DEBUG

SCRIPT_DEBUG это константа, позволяющая использовать версии для разработки CSS и JavaScript файлов ядра, вместо их оптимизированных версий, которые используются по умолчанию. Константа полезна при тестировани изменений в стандартных файлах .js и .css. По умолчанию — false.

define( 'SCRIPT_DEBUG', true );

Наверх ↑

SAVEQUERIES

Определение SAVEQUERIES будет сохранять запросы к СУБД в массив, который можно проанализировать. При определении константы как true, будут сохраняться все запросы, время исполнения, функция вызова запроса.

define( 'SAVEQUERIES', true );

Массив сохраняется в глобальном $wpdb->queries.

Заметка: Это сильно снижает производительность вашего сайта.

Наверх ↑

Пример файла wp-config.php для отладки

Следующий код в файле wp-config.php включит запись всех ошибок, предупреждений и заметок PHP в файл debug.log внутри папки wp-content. Он также отключит вывод на экран (в код страницы):

// Включить отладку WP_DEBUG
define( 'WP_DEBUG', true );

// Включить журнал /wp-content/debug.log
define( 'WP_DEBUG_LOG', true );

// Отключить вывод на экран
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );

// Использовать версии JS и CSS для разработчика (при тестировании изменений в них)
define( 'SCRIPT_DEBUG', true );

Заметка: Это нужно вставить перед /* Это всё, дальше не редактируем. Успехов! */ в файл wp-config.php .

Наверх ↑

Плагины для отладки

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

  • Query Monitor
  • Debug Bar
  • Log Deprecated Notices

Наверх ↑

Внешние ссылки

  • Генератор файла «wp-config.php»
  • Плагин «No White Screen»: показывает ошибку вместо белого экрана

No one likes to see errors on their website. Not only do they look bad to visitors and potential customers, but they also indicate that something’s wrong. But they’re, unfortunately, an inevitable part of running a site. The good news is that following a few best practices and being proactive can dramatically reduce the number of errors you experience. 

One way to monitor potential site issues — or troubleshoot existing ones — is to keep and review an error log. Let’s dive into this a bit more.

What is error logging and why is it important?

Error logging is the process of tracking and monitoring issues that occur on a website. This is usually done with a record of simple text files that live on your web server and are updated whenever an error occurs. Error logs are used to identify the number of problems that occur, provide details about each one, and show when it took place.

How to enable error logging

To enable error logging on your WordPress site, you’ll need sFTP access, available with WordPress.com plugin-enabled plans. This allows you to edit your website files remotely. In this case, you’ll be working with the wp-config.php file, which holds the basic configuration settings for your website.

A word of warning: you should only use sFTP and edit your wp-config.php file if you feel comfortable doing so. Mistakes can cause catastrophic errors on your website. If you don’t have experience changing these types of files, you may want to hire a developer or reach out to WordPress.com support for help.

1. Connect to your website via sFTP

You’ll need to start by enabling sFTP on your site. Go to My Site(s) → Settings → Hosting Configuration and click the Enable SFTP button.

Then, you’ll see your sFTP login details: URL, Port Number, Username, and Password. You’ll need to input these into FTP software, like FileZilla, to access your site. Follow these detailed instructions to connect to your WordPress.com website.

2. Find and download your wp-config.php file

Navigate to your wp-config.php file. This sits in the root directory of your file structure, alongside folders such as wp-content. Download this file, so you have a backup copy on hand.

3. Edit the wp-config.php file

Edit your wp-config.php file using a text editor such as Notepad.

Look for define( ‘WP_DEBUG’, false ); and replace this text with the following:

define( ‘WP_DEBUG’, true );

if ( WP_DEBUG ) {

        @error_reporting( E_ALL );

        @ini_set( ‘log_errors’, true );

        @ini_set( ‘log_errors_max_len’, ‘0’ );

        define( ‘WP_DEBUG_LOG’, true );

        define( ‘WP_DEBUG_DISPLAY’, false );

        define( ‘CONCATENATE_SCRIPTS’, false );

        define( ‘SAVEQUERIES’, true );

}

You’ve now successfully enabled error logging. You should only have this feature turned on while troubleshooting. Otherwise, it can leave your site more vulnerable to hacking attempts. To disable logging, simply delete the code you just added and restore the following:

define( ‘WP_DEBUG’, false );

How to view the error log manually

Once the log is enabled, you’ll need to load your website to trigger any error codes. Those codes are stored in a file called debug.log, which you can access via sFTP by following the same steps as above. 

You can find the debug.log file inside of the wp-content folder. If there are errors, the file will appear. However, if there aren’t any errors, then you won’t see it at all — congratulations!

Once you find the file, download it to your computer to view the full log, using a text editing software like Notepad. It will look something like this:

This file will provide valuable information that will point you, or your developer, to the source of your problem. 

How to view the error log using a plugin 

Using a plugin to find your error log can be an easier and faster method, depending on your level of experience. In the WordPress dashboard, click on Plugins → Add New. Search for “Error Log Monitor” and click Install → Activate.

This plugin installs a widget on your WordPress dashboard that allows you to access your error log. If you haven’t enabled error logging correctly, the widget will display instructions on how to do so. However, you should ignore these instructions, as they’re incorrect for a WordPress.com installation. Instead, use the ones listed above.

If you can’t see the dashboard widget, click on the Screen options tab at the top of the WordPress dashboard and ensure that “PHP error log” is checked.

How to find the plugin or theme that’s causing an error

Error logs are not inherently easy to read, but they do give insightful information into the cause of an error.

Typically, each line in your error log will display a message, alongside the date and time it happened and the file in which the error occurred. It also lists the line number where the error is located. For example:

Apr 20, 15:08:59

Notice: Undefined index: fg2 in /wordpress/themes/pub/varia/functions.php on line 166

Let’s break this down. First of all, there’s the date and time of the error: April 20, 15:08:59. This helps you determine if this was a one-off glitch or a recurring issue.

Then, you can see the type of error that’s been logged. Here are a few common types of error you may see here:

  • Notice. These are more warnings than errors, as they don’t actually stop your website code from executing. While you should still address a notice, your site will most likely still function, although potentially not as designed.
  • Parse error. This is typically the result of a mistake in the syntax of the underlying PHP code of the website (often in a theme or plugin). Parse errors include things like missing semicolons, parentheses, and other similar mistakes. A parse error will stop executing code when it hits the problem, so your site may look visibly broken or not function as intended.
  • Fatal error. This is often caused by undefined functions or classes, like a typo or poor coding practice. You can avoid it by using high-quality code, along with functions such as class_exists or function_exists.

In this case, the error is a notice.

Next, we see the error itself. In the example above the error is “undefined index.” This is followed by the specific location of the problem. In the above example, the error is occurring with the functions.php file of the Varia theme.

How to fix errors

Now that you can see your errors, it’s time to troubleshoot. Here’s a few things you can try:

  • If you’re a developer and the error is in your custom code, go to the line number in the log entry and work to debug.
  • If the error is within a theme or plugin, start by checking for any available updates. Keeping your plugins and themes up to date is critical for avoiding bugs and maintaining website security. Once you’ve applied any updates, re-check the error log to see if there are any new entries. If the error still exists, reach out to the plugin author or consider switching to an alternative. 
  • The error may also be caused by a conflict between two plugins. Try using the WordPress troubleshooting mode to fix this problem.
  • If the problem occurred immediately after installing or updating a plugin, deactivate it to see if the error persists. If it doesn’t, the plugin is the likely cause and you may want to find an alternative. If the error occured after a core update, you may need to manually deactivate plugins to find the source.

Troubleshooting with the WordPress error log

WordPress, like any software, may occasionally run into problems. It may seem confusing to find and fix those problems, but the error log can be a huge help! It enables you to learn valuable information that can help you troubleshoot and solve site errors in a timely manner.

To avoid errors, always use well-maintained plugins and themes, and keep on top of updates. Need more help? If you have a WordPress plugin-enabled plan, you benefit from world-class Happiness Engineers that can provide guidance.

Do you need to access the WordPress error logs to troubleshoot a problem on your site?

WordPress comes with a debugging system that can log any error messages displayed on your site. This can help you discover and fix problems on your website.

In this article, we’ll show you how to find and access your WordPress error logs.

How to Find and Access WordPress Error Logs

How and When Can WordPress Error Logs Help?

Are you having problems with your WordPress website? Checking your WordPress error logs can help you find the source of the issues, such as slow website performance, plugins that aren’t working properly, and website crashes.

What Is an Error Log?

An error log is a list of error messages generated by your website and the dates and times they occurred. Once WordPress debug mode is turned on, these messages are collected in a file so that you can review them later.

Your WordPress error log is a troubleshooting tool that can help you identify plugins, themes, or code that are causing problems. You can then go ahead and find a fix for those WordPress errors.

For example, checking the error logs can help troubleshoot errors like the WordPress white screen of death, PHP errors, the invalid JSON error, and the “Sorry, you are not allowed to access this page” error.

That being said, let’s look at how to find and access your WordPress error logs. The first step is to enable WordPress debug mode, which you can do using either a plugin or code.

  • Enabling WordPress Debug Mode With a Plugin
  • Enabling WordPress Debug Mode Using Code
  • How to Find and Access WordPress Error Logs
  • How to Fix Issues Found in WordPress Error Logs
  • Disabling WordPress Debug Mode

Enabling WordPress Debug Mode With a Plugin

WordPress debugging is turned off by default, so WordPress will not be logging any errors. If you can still log in to your WordPress site, then you can enable debug mode using a plugin.

The first thing you need to do is install the WP Debugging plugin. For more details, see our step-by-step guide on how to install a WordPress plugin.

WP Debugging plugin

Upon activation, the plugin automatically activates WordPress debug mode, and error messages on your site will now be logged.

Enabling WordPress Debug Mode Using Code

You can also turn on WordPress debug mode using code. This method is suitable for more advanced users or if you can’t log in to your WordPress admin area.

You will need to edit your wp-config.php file using an FTP client or the file manager option in your WordPress hosting control panel.

Edit Your Website's wp-config.php File

Once you have the file open, simply find the text where it says, ‘That’s all, stop editing! Happy blogging.’

Just before this line, go ahead and add the following code:

define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );

For step-by-step instructions, you can see our guide on how to set up WordPress error logs in wp-config with code.

How to Find and Access WordPress Error Logs

Now that you have enabled WordPress debug mode, any future error messages on your website will be stored in the WordPress error logs.

That means that your logs will be empty at first. You will need to try to recreate the problem on your site so that the error messages can be saved to the log file.

For example, you should revisit any posts or pages that are causing an error.

Next, you must connect to your website using an FTP client or the file manager option in your WordPress hosting control panel. If you haven’t used FTP before, then you may want to see our guide on how to use FTP to upload files to WordPress.

Once you are connected to your site, navigate to the /wp-content/ folder. Inside the folder, you will find a file called debug.log. This file contains every WordPress error message, warning, and notice that has been logged.

Download, View, or Edit the debug.log File

To see the contents of this file, you will need to download, view, or edit it.

You can then inspect the error messages along with the date and time they occurred. This information can help you find a solution to the problems you are encountering on your website.

Debug.log Contains Error Messages and Time Stamps

How to Fix Issues Found in WordPress Error Logs

Once you have accessed your WordPress error logs, you can find the error message that was logged when the problem on your website happened. Remember that the times displayed are UTC, not your local time.

While most users won’t understand the error messages, they are a good place to start troubleshooting. Once you note the error message and code, you may find a solution to your problem in our guide on the 50 most common WordPress errors and how to fix them.

If you can’t find the solution on your own, then you can reach out for help on our free WPBeginner Engage Facebook Group, where you can get support from our WordPress experts and over 80,000 users. Just make sure to quote the error code or message you found in the WordPress error logs.

Other places you can turn for help are the official WordPress forums, your WordPress web hosting company’s support team, or the designated support area for the plugin or theme you are having trouble with.

When asking for support, we recommend reading our guide on how to properly ask for WordPress support and get it to learn the right way to ask questions and the best places to find help.

Disabling WordPress Debug Mode

Once you have fixed the issue on your WordPress site, we recommend disabling debug mode. Leaving it on may slow down your website and potentially leak unwanted information, which is a security risk.

If you enabled debug mode with a plugin, then simply navigate to Plugins » Installed Plugins and deactivate the WP Debugging plugin.

Deactivate the WP Debugging Plugin

If you enabled debug mode with code, then simply edit the wp-config file as you did before.

You will need to change the WP_DEBUG and WP_DEBUG_LOG lines to ‘false’.

Deactivate WordPress Debug Mode

We hope this tutorial helped you learn how to find and access your WordPress error logs. You may also want to learn how to get a free SSL certificate for your website or read our tips on how to speed up WordPress performance.

/cta

Disclosure: Our content is reader-supported. This means if you click on some of our links, then we may earn a commission. See how WPBeginner is funded, why it matters, and how you can support us.

Editorial Staff

Editorial Staff at WPBeginner is a team of WordPress experts led by Syed Balkhi with over 16 years of experience building WordPress websites. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.

The following are some techniques I use nearly every day for debugging WordPress and WooCommerce, and can be used for plugin or theme development equally.

Echoing or printing to the screen will only get you so far when debugging, especially in a complex framework like WordPress; to really understand the code flow, and to trace and fix issues, you need to be able to log messages to a file. For this WordPress makes use of the PHP core error_log() function, which allows you to “send an error message somewhere.” Using it is quite simple:

error_log( "Hello World!" );

Put this into a script, request the page and we will have logged a message “somewhere”, but where? By default when running under Apache and called with no additional arguments, error_log() will send the message to your apache error log file. For me this is found at /var/log/apache2/error_log, for you this may be somewhere else, and is specified by your apache conf file. My Apache conf is found at /etc/apache2/httpd.conf, again yours could be elsewhere on your system depending on how you installed Apache. Logging to the apache error log is a good first step, however a lot of stuff that we don’t necessarily care about also gets logged there, and it doesn’t always work well with newlines in your debug statements; thankfully WordPress provides a solution with a set of debugging constants.

Debugging with WP_DEBUG

The first and most important constant is WP_DEBUG. Enable this within your wp-config.php file to report all PHP notices to your log file, and allow the use of the other debugging constants:

define( 'WP_DEBUG', true );

WordPress recommends “that plugin and theme developers use WP_DEBUG in their development environments”, which is indeed good advice, but unfortunately not followed by all developers, which means that your log file can become inundated with notices from misbehaving 3rd party plugins and themes, making it all but impossible to watch for notices from your own plugin development. You don’t have many options here:

  • You can take the time to fix the notices in the offending code (which is nice until you update and get the notice-ridden code all over again)
  • You can deactivate the plugin if you don’t really need it (not always an option)
  • Or you can disable notice reporting (useful if you just want to be able to log debug statements without losing them among notices you don’t care about). Unfortunately this makes it difficult to stay on top of notices from your own plugin development and can make you part of the problem! Still, it’s the best option at times, see my debug helper plugin for a simple way to do this.

A Better Log File With WP_DEBUG_LOG

Enabling the WP_DEBUG_LOG constant, in the same manner as the WP_DEBUG above improves our debugging experience by sending notices and messages to wp-content/debug.log. Another benefit is being able to use the print_r(), var_dump() and other handy multiline debugging functions. WP_DEBUG must be enabled for this constant to have any effect:

define( 'WP_DEBUG',     true );
define( 'WP_DEBUG_LOG', true );

Watch the log file like any other for convenience while developing:

$ tail -f wp-content/debug.log

Remember: One thing to keep in mind with this configuration enabled is that there will be some spots in the WordPress code that are executed prior to the log file being set, so depending on how deeply you’re debugging into core files, you may need to watch the apache error log (or other location, as always depending on your php.ini) for some of your messages. It doesn’t come up often, but if you’re deep into core territory and start missing statements that you know should be logged, check your apache error log, or other default destination before you accuse the computer of cheating.

In Your Face Debugging With WP_DEBUG_DISPLAY

Enabling the WP_DEBUG_DISPLAY constant will cause notices/errors to be displayed right on the page when they occur. When you have all outstanding notices fixed and are developing a plugin or theme this is a great constant to have enabled as it doesn’t require watching your log file. Granted it won’t catch all notices all the time so you will still need to be aware of your log file, but this is a great way to keep yourself honest.

Script Debugging with SCRIPT_DEBUG

By default WordPress will use minified CSS/JavaScript files, which is great for site performance, but not so great for finding and fixing issues with them. Sure you could learn to read minified JavaScript, or you could use yet another handy constant: SCRIPT_DEBUG, which will cause the un-minified scripts to be loaded instead.

Query Debugging With SAVEQUERIES

WordPress is obviously heavily dependent on the database, and this is an area that can be difficult at times to get visibility into. One solution is to enable the SAVEQUERIES constant, which will save all queries to the queries member of the db object along with their execution time, and the stack of functions that called them. I find this one to be of limited benefit just due to the sheer number of database queries in the typical WordPress page load, and I prefer to error_log() the particular query that I’m actually interested in, but it certainly can be useful:

global $wpdb;

error_log( print_r( $wpdb->queries, true ) );

// try and narrow down a particular query:
foreach ( $wpdb->queries as $query ) {
  if ( strpos( $query[2], 'WP_Query->get_posts' ) !== false ) error_log( print_r( $query, true ) );
}

A Plugin to Help with Debuggin’

One of the first plugins I wrote for myself is a small debug helper plugin unimaginatively called WP Debug Helper. This can disable notice reporting for those times when you just can’t deal (this functionality commented-out by default), and adds two functions that I find useful additions to my debugging toolbox:

wp_debug_backtrace()
Convenience function for printing a stack trace
wp_var_dump()
Convenience function for calling the core var_dump() function

Feel free to download it, use it, add to it; let me know in the comments if you have suggestions for any other helpful functions to add.

Putting it all Together

To put it all together and wrap things up, here are some example logging patterns I find myself using over and over:

Configure wp-config.php:

/**
 * For developers: WordPress debugging mode.
 *
 * Change this to true to enable the display of notices during development.
 * It is strongly recommended that plugin and theme developers use WP_DEBUG
 * in their development environments.
 */
define( 'WP_DEBUG',        true );
define( 'WP_DEBUG_LOG',    true );
define( 'WP_DEBUG_DISPLAY',true );
define( 'SCRIPT_DEBUG',    true );
define( 'SAVEQUERIES',     true );

Watch the Log File:

$ tail -f wp-content/debug.log

Example log statement:

error_log( "Hello World!" );

Example logging print_r:

error_log( print_r( $foo, true ) );

Get the classname of an unknown object:

error_log( get_class( $obj ) );

Example logging a stacktrace (if my WP Debug Helper plugin is installed and active):

error_log( wp_debug_backtrace() );

Example var dumping a variable (if my WP Debug Helper plugin is installed and active):

error_log( wp_var_dump( $foo ) );

Dump all defined constants (note that this will be quite extensive within WordPress):

error_log( print_r( get_defined_constants(), true ) );

Dump all available globals (note that this will be quite extensive within WordPress):

error_log( print_r( $GLOBALS, true ) );

// or maybe:
foreach( $GLOBALS as $key => $value ) {
  if ( ! in_array( $key,array( '_wp_using_ext_object_cache', 'wpdb', 'registered' ) ) )
    error_log( $key . " => " . print_r( $value, true ) );
}

Dump queries:

global $wpdb;

error_log( print_r( $wpdb->queries, true ) );

Have any other tips or patterns you find yourself using again and again? Let us know in the comments below. Happy Debugging!

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

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

  • Яндекс еда ошибка привязки карты
  • Лог ошибок iphone
  • Лог ошибок google chrome
  • Лог ошибок debian
  • Лог ошибки как исправить

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

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