Диагностика проблем, возникающих на сайте WordPress, может оказаться сложной. Наглядный способ проследить появление ошибок и получить обратную связь – использование журнала логов. Изучение записей в логах позволит выяснить причину проблемы и устранить ее.
Где хранится лог ошибок ВордПресс и как его посмотреть
Первый шаг к исправлению ошибок на сайте – выяснить, при каких обстоятельствах они возникают. Кроме того, периодически могут появляться неявные ошибки и системные предупреждения, о которых вы не знаете, поскольку ваши действия их никогда не вызывали, но посетители сайта могли это заметить.
Чтобы просмотреть ошибки и предупреждения, необходимо записать их в специальный файл журнала. Ведение журнала логов является хорошей практикой, особенно если сайт находится в стадии разработки. Возможно, вам не удастся понять причину ошибки, когда она впервые возникнет, но как только вы получите больше информации при последующей работе, логи в журнале окажутся очень полезными для анализа ситуации.
Фактический журнал логов хранится в файле с именем debug.log в каталоге содержимого вашего сайта wp-content на сервере хостинг-провайдера. Как посмотреть логи? Один из способов просмотра и очистки журнала – прямой доступ к этому файлу. Скачайте файл с помощью файлового менеджера и откройте его любым текстовым редактором. Можно воспользоваться плагинами, которые упрощают работу с логами.
Можно ли удалять логи? Файл с отладочной информацией и уведомлениями об ошибках со временем может разрастись до внушительных размеров. Поэтому, если ваш сайт работает нормально, то старые логи можно удалить, чтобы освободить рабочее пространство.
Как включить/выключить логирование
Чтобы включить создание лог-журнала для сайта на WordPress, понадобится внести изменения в системный файл wp-config.php, который расположен на сервере хостинга.
- Запустите файловый менеджер и подключитесь к удаленному серверу со своей учетной записью, который вам предоставил хостинг-провайдер.
- Перейдите в корневой каталог, где установлен ваш сайт.
- Сделайте резервную копию файла 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.
From permissions problems to PHP issues, there are many types of errors that can occur in WordPress. These can be difficult to diagnose on your site, particularly if you don’t have a technical background.
To simplify the process for monitoring and diagnosing these errors, you can set up WordPress error logs in your wp-config file. The wp-config.php file is a core WordPress file that contains your website’s base configuration details. This information allows WordPress to connect to your database, generate authentication keys that keep your site secure, and more.
By adding a few lines of code, you turn your wp-config.php file into a debugging tool that automatically finds and logs errors on your site. In the error logs, you can identify the plugin, script, or code that is causing errors. You can then troubleshoot these issues yourself or reach out to WordPress support.
Monitoring your site in this way can help you identify and resolve issues before they disrupt your data transfer capacity, negatively impact the visitor experience, or cause downtime.
To help you keep your site running smoothly, let’s walk through the process of setting up error logs in your wp-config file.
To set up WordPress error logs in your wp-config.php file, you just need to add a few lines of code to the file.
It’s a simple process, but as a best practice, you should always make a copy of your wp-config.php file before editing. That’s because even a small error in the file can make your site inaccessible.
Here’s a quick video you can watch to follow along with the steps below.
To start, log in to your control panel and open the File Manager. Locate the wp-config.php file and right-click to copy it. Rename the file wp-config.php.backup.
Now that you have a backup, right-click the original wp-config.php file. Click the Edit option.
Source
Scroll down to the end of the file to the line that reads /* That’s all, stop editing! Happy blogging. */
Right before this line, you might see the following line of code: define(‘WP_DEBUG’, false);
If you do, delete it then copy and paste the following lines of code:
define( 'WP_DEBUG', true );
define( 'WP_DEBUG_LOG', true );
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
Save your changes. Your site’s “debug mode” will now be turned on and all errors will be saved to a debug.log log file inside your /wp-content/ directory.
Errors and warnings will also be hidden on the front end of your site. By hiding these error and warning messages from your visitors, you’ll help ensure they have a seamless experience on your site.
Reviewing Your WordPress Error Logs
To review your error logs, navigate to your /wp-content/ folder in your File Manager. Locate the debug.log file.
Source
This file will contain all WordPress errors, warnings, and notices that were logged. Note that you will only see this file if your site has encountered any errors.
Source
At this point, you can attempt to fix the problem(s) on your own since the WordPress log can help you understand what’s causing the error by naming the element at fault. You can also reach out to WordPress support for help. Make sure to share the text from the error log, which will help the support rep understand the problem and provide you with a solution.
You’re all done now! With error logging automated on your site, you’ll be able to keep track of errors that occur on your site more easily. This monitoring can help you quickly resolve any issues before they damage your site’s reputation or your visitors’ experience.
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 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 problems 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 the 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 have a 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 into 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.
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 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.
Once you have the file open, you need to 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, 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 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 need to 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 connected, you should 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.
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.
How to Fix Issues Found in WordPress Error Logs
Once you’ve accessed your WordPress error logs, you can find the error message that was logged at the time the problem on your website occurred. Keep in mind that the times displayed are UTC, not your own local time.
While most users won’t understand what the error messages mean, they’re 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 help from our WordPress experts and over 80,000 users. Make sure you 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, check 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 support.
Disabling WordPress Debug Mode
Once you have fixed the issue on your WordPress site, we recommend you disable debug mode. Leaving it on may slow down your website and can 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.
If you enabled debug mode with code, then simply edit the wp-config
file as you did before.
You need to change the WP_DEBUG
and WP_DEBUG_LOG
lines to ‘false’.
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 check out our tips on how to speed up WordPress performance.
If you liked this article, then please subscribe to our YouTube Channel for WordPress video tutorials. You can also find us on Twitter and Facebook.
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 at WPBeginner is a team of WordPress experts led by Syed Balkhi. We have been creating WordPress tutorials since 2009, and WPBeginner has become the largest free WordPress resource site in the industry.
Themeisle content is free. When you purchase through referral links on our site, we earn a commission. Learn More
From conflicts between WordPress plugins to poorly coded themes and mistakes in custom coding, several problems sound the alarm with website error codes and warnings. Even if you’re not sure what the warnings mean, you must fix them. The first step is learning how to set up a WordPress error log.
As a short explanation, a WordPress error log is exactly what it sounds like: a list of error codes and times that occur on your website.
In this post, we’ll show you how to set up and work with WordPress error logs using the built-in WordPress debug mode.
When should you set up a WordPress error log?
Consider setting up a WordPress error log in the following situations:
- When you see a blank screen while trying to load your website.
- When a warning with an error code (401, 404, 500, etc.) appears.
- If your entire site crashes.
- If you’re noticing slow website performance.
- If a plugin or theme isn’t working properly.
- If you’re curious as to which plugins or themes are causing performance issues.
As is often the case with WordPress, you have two routes to enable error logging with WordPress debug mode:
- Manually
- With a plugin
We’ll start by showing you the manual method, which just involves adding a few code snippets to your site’s wp-config.php
file.
Then, if you want an even simpler option for error logging, we’ll share a free plugin that can get the job done.
Here’s how to do it manually…
Click here if you’d rather jump to the plugin 👈
Step 1: Access and edit the wp-config.php file
If you’re not familiar with your wp-config.php
file, it’s one of the core files for holding important configuration details, like the credentials for your site’s database.
To access the wp-config.php
file, either download and use an FTP client or a file manager tool in your host’s cPanel.
How to use FTP to connect to WordPress 👈
For this tutorial, we’ll cover the steps to access and edit your wp-config.php
file with an FTP client.
In your FTP client, locate the wp-config.php
file. This is normally in the root site directory.
Upon finding the file, right-click on it and select to edit or view the file. You’ll want to open the file in a text editor.
Step 2: Add a line of code in the wp-config.php file to turn on debug mode
Inside your text editor, search for a line of text that reads Stop editing! Happy blogging
.
Place your cursor on the empty line above that line of text.
Paste in the following code:
define( 'WP_DEBUG', true );
If you already notice this line of code in the file, it may currently be set to false
. If that’s the case, switch it to true
.
Afterward, save the file to your computer and upload the wp-config.php
file as an update to your website. This is done through the FTP client.
Great! Now debugging mode is activated for your WordPress site.
Step 3: But wait! I don’t want the errors to show on the frontend of my website
If you took a moment to check your dashboard or the frontend of your site, you may have already seen WordPress errors listed for everyone to see. This may not seem like a big deal if they show up on the WordPress dashboard, but you definitely don’t want the warnings on the frontend.
Not only is publicly displaying errors confusing for your visitors, but it can also be a security risk because it gives them detailed information about your site.
In short, debugging mode is messy when activated by itself.
Therefore, we need to log the errors in WordPress so they are recorded but not publicly displayed.
To log your errors, go back to that exact same wp-config.php
file in the text editor.
Look at the debug code you recently pasted into the file. Paste the following new code on the empty line below the debug code:
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
Again, in some situations you might discover that the debug log code is already included. For that, simply make sure that the false
at the end of the code is changed to true
.
The first line tells WordPress to save error messages to a file called debug.log
. The second snippet tells WordPress not to publicly display error messages.
Now, your error messages will be safely saved in the log file, but neither you nor your visitors will have to see error messages while browsing your site.
For a second time, save the wp-config.php
file in your file editor and upload it back to your WordPress website.
How to use a WordPress error log plugin
If you don’t feel comfortable working directly with your site’s configuration file, you can also use the free WP Debugging plugin:
As soon as you activate the plugin, it instantly activates WordPress debug mode and enables error logging. It also lets you control whether or not to display debug messages on your site by visiting Tools -> WP Debugging.
Checking your WordPress error logs
We’re assuming you already know the website pages that are alerting you of errors.
You must visit these pages now that the debugging log is configured and ready to store the errors.
Reconnect to your website files using the FTP client. You can also connect via your host’s cPanel.
Go to the /wp-content/
folder.
Open that folder and look for a file called debug.log
.
This is the file you created from the previous steps.
What should I do with this debug log file?
The debug.log
file is accessible by editing, viewing, or downloading the file. It’s similar to the previous steps, where you might either just preview the file to look at it or open it in a file editor to make changes and save it for later.
Overall, a debug log file is for reference, not for editing. Therefore, you have to sift through the list of errors and warnings to identify what’s wrong with your site, theme, plugins, or code.
For most people, the error log codes mean nothing. If anything, it’s closer to gibberish than English. However, you don’t want to forget about those errors.
Your resolution steps should go like this:
- You identify an error with the debug log.
- You find the error code.
- You look up what that error code means.
- You utilize a separate guide to fix that error.
How to fix issues that you discover in the error log
Unfortunately, there’s no one-size-fits-all approach to fixing problems that you might discover in your site’s error log.
However, we do have lots of existing posts on how to fix common WordPress errors:
- A beginner’s guide to WordPress troubleshooting
- The most common HTTP error codes and how to fix them
- A guide for checking for plugin compatibility issues
- What is a 401 error and how do you fix it?
- How to fix any 404 errors with redirects
- How to fix the 500 internal server error in WordPress
- 4 ways to fix an error when establishing a database connection
- How to fix the white screen of death
If you’re still not sure how to fix the issues in your log file, you might want to hire a WordPress developer to do it for you – here are some tips to find the right developer.
Do you have any questions about how to set up a WordPress error log?
Even looking at bits of code feels intimidating for the average WordPress user.
The good news is that setting up a WordPress error log only takes two small snippets of code.
If you have trouble activating your WordPress error log, or questions on how to fix them, let us know in the comments below!
Free guide
5 Essential Tips to Speed Up
Your WordPress Site
Reduce your loading time by even 50-80%
just by following simple tips.
Download free guide
10.06.2017
Приветствую, дорогие читатели!
Движок WordPress состоит из множества файлов, которые исполняются на хостинге (сервере). И если «чистый» WordPress едва ли может сбоить, то при использовании плагинов, и собственноручно вписанных строк кода для расширениядобавления функционала, к примеру, в файл functions.php могут наблюдаться ошибки.
Причины их могут быть разными – либо плагин устарел и уже не отвечает современным требованиям, а может просто код, который подвернулся на просторах сети, который хоть и работает актуальной версии WordPress, но написан «криво» и создаёт ошибки в движке.
Ошибки необходимо контролировать и по возможности исправлять. Если это плагин, то найти ему достойную замену, которая будет работать без ошибок. А если код для расширения функционала, то также стоит либо найти ему грамотно написанную замену, либо посовещаться с программистомверстальщиком и внести соответствующие поправки, дабы убрать ошибки.
Как отслеживать ошибки в работе файлов WordPress
В WordPress можно задать запись всех возникающих ошибок в лог файл. Данный файл является текстовым и спокойно открывается блокнотом. Причём для этого не надо ставить какой-либо плагин.
Просто пропишите в файл wp-config.php, что находится в корневой директории вашего WordPress сайта следующий код (как это правильно сделать – написано здесь):
// НЕ показывать ошибки в самом браузере define('WP_DEBUG_DISPLAY', 0); // Писать ошибки исключительно в ЛОГ файл define('WP_DEBUG_LOG', 1);
А также отыщите уже имеющуюся запись в файле:
define('WP_DEBUG', false);
и измените значение опции в ней, чтобы в итоге стало так:
define('WP_DEBUG', true);
Если в процессе работы WordPress движка будут возникать ошибки, то в корне папки wp-content будет создан файл debug.log, в который эти самые ошибки будут аккуратно прописываться.
Необходимо отметить, что включённый режим протоколирования ошибок совершенно не сказывается на производительности движка WordPress. Лично я на всех своих сайтах держу данный режим включённым.
И последнее, данный файл находится на хостинге, и соответственно если ввести ссылку, в которой указать путь к нему, то файл будет открыт браузером. Это нам явно не нужно, потому следует вписать запрет на открытиепросмотр файла debug.log извне. Для этого в находящемся в корне сайта файле .htaccess следует вписать следующий код:
# Запрет на доступ к debug.log <files debug.log> order allow,deny deny from all </files>
Вот собственно и всё. Желаю вам не сталкиваться с ошибками в WordPress
Пожертвование сайту WPuse.ru (cбор пожертвований осуществляется через сервис «ЮMoney»)
Диагностика проблем, возникающих на сайте WordPress, может оказаться сложной. Наглядный способ проследить появление ошибок и получить обратную связь – использование журнала логов. Изучение записей в логах позволит выяснить причину проблемы и устранить ее.
Где хранится лог ошибок ВордПресс и как его посмотреть
Первый шаг к исправлению ошибок на сайте – выяснить, при каких обстоятельствах они возникают. Кроме того, периодически могут появляться неявные ошибки и системные предупреждения, о которых вы не знаете, поскольку ваши действия их никогда не вызывали, но посетители сайта могли это заметить.
Чтобы просмотреть ошибки и предупреждения, необходимо записать их в специальный файл журнала. Ведение журнала логов является хорошей практикой, особенно если сайт находится в стадии разработки. Возможно, вам не удастся понять причину ошибки, когда она впервые возникнет, но как только вы получите больше информации при последующей работе, логи в журнале окажутся очень полезными для анализа ситуации.
Фактический журнал логов хранится в файле с именем debug.log в каталоге содержимого вашего сайта wp-content на сервере хостинг-провайдера. Как посмотреть логи? Один из способов просмотра и очистки журнала – прямой доступ к этому файлу. Скачайте файл с помощью файлового менеджера и откройте его любым текстовым редактором. Можно воспользоваться плагинами, которые упрощают работу с логами.
Можно ли удалять логи? Файл с отладочной информацией и уведомлениями об ошибках со временем может разрастись до внушительных размеров. Поэтому, если ваш сайт работает нормально, то старые логи можно удалить, чтобы освободить рабочее пространство.
Как включить/выключить логирование
Чтобы включить создание лог-журнала для сайта на WordPress, понадобится внести изменения в системный файл wp-config.php, который расположен на сервере хостинга.
- Запустите файловый менеджер и подключитесь к удаленному серверу со своей учетной записью, который вам предоставил хостинг-провайдер.
- Перейдите в корневой каталог, где установлен ваш сайт.
- Сделайте резервную копию файла 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. Обычно она называется 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 – этот плагин добавляет виджет, который видим только для администраторов. Он отображает последние сообщения из журнала логов, а также умеет отправлять уведомления по электронной почте о новых возникших ошибках. Частота уведомлений и количество отображаемых записей в журнале настраивается. Плагин оптимизирован для работы с очень большими лог-файлами.
Источник:
0
In a perfect world, you’d never have a single issue that required debugging. But in the real world, you’ll almost certainly run into issues on your WordPress site that require a look under the hood.
To help you do that, WordPress includes its own built-in debug mode and you can also find useful third-party tools to help you debug WordPress.
In this post, we’ll dig into the built-in WordPress debug mode and show you how to enable it. Then, we’ll also share some of the other ways in which you can debug your WordPress site.
Here’s everything that we’ll cover:
- An introduction to WordPress debug mode and the debug log
- How to enable WordPress debug mode (three methods)
- Some other ways to debug WordPress
What Does WP Debug Do?
The core WordPress software is written in PHP, as are plugins and themes.
If you’re having issues with your site, WordPress debug mode can help you find out what’s going wrong by displaying all PHP errors, notices, and warnings.
Once you enable debug mode, you’ll see messages like this whenever there’s an issue (even if it’s not causing immediate problems):
You can then fix the problem or report it to your developer or the theme/plugin’s developer.
What Is the WordPress Debug Log?
When you enable WordPress debug mode by itself, you’ll see messages like the example above on your site in the moment – but those messages won’t be saved anywhere.
If you want to save them, you can also enable the WordPress debug log to save all of those messages and errors to a file on your server.
When enabled by setting the WP_DEBUG_LOG
constant to true, WordPress will write all issues to the following file:
wp-content/debug.log
However, you can also specify a custom file path to write the log to a different location on your server.
If you want to save problems to the log but not publicly display them within the HTML of your pages (like the example screenshot above), you can also use the WP_DEBUG_DISPLAY
constant to keep debug mode enabled but not display messages on your site.
Typically, you’ll want to combine WP_DEBUG_DISPLAY
with WP_DEBUG_LOG
.
Ready to debug your #WordPress site? This guide has you covered 🐛Click to Tweet
How to Enable WordPress Debug Mode
To enable WordPress debug mode, you have several options. We’ll cover three methods to enable it:
How to Enable WordPress Debug Mode in MyKinsta
If you host your WordPress site at Kinsta, we built an easy tool that lets you enable the WordPress debug mode without needing to edit your wp-config.php file.
This tool is convenient for being able to quickly enable debug mode and display messages on your site, but it doesn’t let you control the WordPress debug log or whether or not to display messages on live pages. If you want to use just the debug log, you might prefer the plugin method in the next section.
To get started:
- Open your MyKinsta dashboard.
- Select the site where you want to enable debugging from the Sites list.
- Go to the Tools tab in that site’s dashboard.
- Click Enable under WordPress debugging.
You can use the tool on both your live and staging environments. Whenever possible, though, we’d recommend using it with your staging environment because enabling WordPress debug mode might display details about your site’s PHP code to visitors (which is confusing for visitors and also a security risk).
When you’re finished, you can disable debug mode by clicking the Disable button in your Kinsta dashboard:
How to Use a WordPress Debug Plugin
If you’re not hosting at Kinsta, you can also find free WordPress debug plugins that make it easy to enable debug mode. There are several options at WordPress.org, but we recommend the free WP Debugging plugin from Andy Fragen.
Once you install and activate the plugin, it starts working right away. By default, it sets the following constants to true (that is, it enables the following features):
WP_DEBUG
– enables debug mode.WP_DEBUG_LOG
– saves messages to a log file.SCRIPT_DEBUG
SAVEQUERIES
We’ll cover what the last two constants do a little later on in this post.
To configure a few options, you can go to Tools → WP Debugging:
Once you’re finished, make sure to disable the plugin to disable debug mode.
How to Manually Enable WordPress Debug Mode
Finally, you can also enable WordPress debug mode by manually adding the constants to your wp-config.php file.
To get started, connect to your server via FTP and edit the wp-config.php file. By default, this file is in the root folder of your site (unless you moved it for security reasons).
To enable just the basic WordPress debug mode, add the following code snippet above the line that says /* That’s all, stop editing! Happy blogging. */:
// Enable WP_DEBUG mode
define( 'WP_DEBUG', true );
You can also use some of the following constants according to your preferences:
// Enable Debug logging to the /wp-content/debug.log file
define( 'WP_DEBUG_LOG', true );
// Disable display of errors and warnings
define( 'WP_DEBUG_DISPLAY', false );
@ini_set( 'display_errors', 0 );
Once you’re finished, you can either set the constants to false or just remove the snippet to disable debug mode.
Make Sure to Disable Debug Mode in WordPress When You’re Finished
The debug mode is useful when you’re trying to troubleshoot problems with WordPress, but you shouldn’t leave it enabled 24/7 because it can reveal text from your PHP code to website visitors.
We mentioned this above – but this is just a reminder to always disable debug mode when you’re finished troubleshooting.
Other Ways to Debug WordPress
Beyond the built-in debug tool that we featured above, there are several other built-in and third-party tools to help you debug your WordPress site.
Script Debug
SCRIPT_DEBUG
is another built-in constant that forces WordPress to use the dev versions of core CSS and JavaScript files instead of the minified versions that it usually loads.
This can be helpful if you’re testing changes to the built-in .js or .css files.
To enable SCRIPT_DEBUG
, you can either:
- Use the free WP Debugging plugin from above, which enables it by default.
- Add the following constant to your wp-config.php file –
define( 'SCRIPT_DEBUG', true );
Database Query Debugging
If you’re having issues with your site’s database, you can enable database query logging using the SAVEQUERIES
constant to track:
- Each database query.
- The function that called the database query.
- How long the query took.
To enable query logging, you can either:
- Use the free WP Debugging plugin from above, which enables it by default.
- Add the following constant to your wp-config.php file –
define( 'SAVEQUERIES', true );
Note: this will impact your site’s performance so try to use it on a staging site whenever possible and disable it as soon as you’re finished.
Query Monitor Plugin
The Query Monitor plugin is a free plugin that’s helpful for debugging a number of different areas in WordPress including:
- Database queries.
- PHP errors.
- Hooks and actions.
- Block editor blocks.
- Enqueued scripts and stylesheets.
- HTTP API calls.
- User capabilities.
Overall, it’s one of the best WordPress debug tools that you’ll find, which is why it has almost a perfect 5-star rating on over 320 reviews.
Once you install and activate the plugin, you’ll get some new options on the WordPress toolbar that display debug information. When clicked, those options will open a new Query Monitor box that gives you more information:
For a more detailed look, we have an entire post on how to use the Query Monitor plugin.
New Relic
New Relic is a premium tool for analyzing and debugging your site’s performance. It can help you discover bottlenecks and issues that are affecting your site’s performance.
Kinsta already includes the built-in APM tool. However, you can still use New Relic in the MyKinsta dashboard, provided you have your own license.
Server Logs
Finally, your server logs can also be a useful tool in debugging WordPress.
If you host at Kinsta, you can view all of your server logs from the Logs tab in a site’s dashboard:
If you host elsewhere, you’ll need to consult your host’s documentation to learn where you can access your server logs.
It’s time to take a look under the hood and debug your #WordPress site 🐛 This guide has everything you need to get started 💪Click to Tweet
Summary
If you need to debug WordPress, the built-in WordPress debug mode provides a useful way to view PHP errors and notices.
If you host at Kinsta, you can enable it right from your dashboard. Otherwise, you can enable it with plugins or by adding code snippets to your site’s wp-config.php file.
For more help, you can also use other built-in tools or third-party tools like New Relic (your own license is required) and the free Query Monitor plugin.
Do you have any other questions about how to debug WordPress? Leave a comment and let us know!
Get all your applications, databases and WordPress sites online and under one roof. Our feature-packed, high-performance cloud platform includes:
- Easy setup and management in the MyKinsta dashboard
- 24/7 expert support
- The best Google Cloud Platform hardware and network, powered by Kubernetes for maximum scalability
- An enterprise-level Cloudflare integration for speed and security
- Global audience reach with up to 35 data centers and 275 PoPs worldwide
Test it yourself with $20 off your first month of Application Hosting or Database Hosting. Explore our plans or talk to sales to find your best fit.