Где посмотреть ошибки 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.

If you are trying to understand how the WordPress error logs works, you are in the right place! In this guide, we will cover all what you should know about it.

Monitoring PHP errors is something you need to do if you want to keep your WordPress website secure, healthy, and fast. If not fixed, PHP errors can indeed reduce your website performance and increase your website vulnerability to downtime and hackers.

That’s why, in this article, I’ll explain to you what you need to know about the PHP error logs in WordPress: from how to enable WordPress Error Log to implementing a reliable PHP monitoring solution.

error logs wordpress

Let’s get started with two definitions! If you are in a hurry, you can directly go to the PHP monitoring plugins section.

Table of contents

  • What Are PHP Errors?
    • What Is a WordPress Error Log?
      • Using WordPress Error Logs to Troubleshoot PHP Errors
        • How to Check PHP Error Logs in WordPress?
          • Monitor WordPress PHP errors logs with a plugin
            • Editing the configuration file for Debugging (enabling error log in WordPress)
            • How to Fix The PHP Errors That You Found in The Error Log?

              TL;DR

              A WordPress website can be affected by a variety of errors, including permission issues and PHP issues. If you don’t have any technical experience, it can be challenging to diagnose these problems on your site.

              You can turn your wp-config.php file into a debugging tool by adding a few lines of code. Once you’ve identified the problem, it will be easier to troubleshoot it.

              To activate WordPress error logs add define( ‘WP_DEBUG’, true ); above “Stop editing! Happy blogging”. in wp-config.php file.

              What Are PHP Errors?

              PHP is the coding language WordPress is built on. When a user requests a web page that contains PHP code, the code is processed by the PHP module (Apache or Nginx) installed on the server.

              Processing a request can generate PHP errors. This means that something is wrong with the PHP code. The error can be as simple as a missing semicolon, or as complex as calling an incorrect variable.

              PHP errors can be triggered by theme, plugins, database, or server configuration. That’s one of the reasons why you should not install too many plugins on your WordPress websites.

              Note that, the most PHP errors that you can see on your WordPress site are usually warnings and notices. This being said, some of them (fatal errors, internal server error, etc) can stop your website from loading.

              Here are some of the PHP errors you can encounter.

              What Is a WordPress Error Log?

              Indeed, even if your website seems to be working well, it may in fact be suffering from undetected PHP errors that should be fixed ASAP. The WordPress error log gives you the list of these errors.

              PHP error logs

              Error logs provide you with information such as the error type, the error line, and the file concerned. You should use WordPress error logs to troubleshoot arising issues or understand why they’ve happened.

              Using WordPress Error Logs to Troubleshoot PHP Errors

              If my explanation still looks blurry and if you don’t see the point of enabling the debugging mode for WordPress, here are some situations where you might really need it:

              • When your WordPress website doesn’t load (blank page);
              • When your web browser displays a warning with a PHP error code;
              • If a plugin isn’t working properly;
              • In case of downtime;
              • If your website is really slow;
              • If you want to improve your website performance & security;

              How to Check PHP Error Logs in WordPress?

              There are two ways to access PHP error logs in WordPress: manually or with a monitoring plugin. I’d personally advise to use WP Umbrella to monitor your PHP errors. It’s clearly the easiest way.

              Monitor WordPress PHP errors logs with a plugin

              Step 1: Get WP Umbrella Monitoring Plugin

              WP Umbrella is a all-in-one solution to manage WordPress sites. It embed a PHP errors monitoring feature for WordPress.

              WP Umbrella is interesting because it also checks your website’s uptime rate and provide you with automatic backups.

              You need to install the plugin, create an account and connect your API key.

              wp umbrella php errors monitoring plugin

              Step 2: Go to the PHP errors monitoring tab

              Then, go to WP Umbrella’s application >> PHP issues.

              PHP issues

              From here, click on the “view error” to get all the information related to the PHP errors such as:

              Error detail

              • The type of PHP error
              • The plugin or theme responsible
              • The environnement information (PHP version, plugin version, WordPress version)
              • When the PHP error happened

              PHP error message

              That’s it, easy peasy!

              PHP error information

              Editing the configuration file for Debugging (enabling error log in WordPress)

              If you don’t want to use an error log plugin like WP Umbrella or Query monitor, you can enable WordPress error log and retrieve PHP errors from here.

              Step 1: Access the wp-config.php file

              The wp-config.php file contains important WordPress settings like how to connect to your database. This is the file you need to edit in order to enable WordPress debugging mode and access WordPress error logs where you will find your PHP errors.

              wp-config.php

              First, you need to connect to your website using an FTP client. Then, download the wp-config.php file to make a backup of it. Then you can start editing it with your favorite HTML editor.

              Step 2: Edit the wp-config.php file

              Just before the line “That’s all, stop editing! Happy blogging” add this:

              define( ‘WP_DEBUG’, true );
              define( ‘WP_DEBUG_LOG’, true );

              Or write true instead of false if the WP_debug function is already defined.

              WP_DEBUG will allow you to enable debug mode and WP_DEBUG_LOG will allow you to send all errors to a file, so PHP errors are not displayed on your pages.

              Save your changes and upload the file back to your website. The errors will then get logged to the debug.file within your wp-content folder. If you don’t see the file, you can create one.

              This is where your WordPress error logs will be stored.

              How to Fix The PHP Errors That You Found in The Error Log?

              Regrettably, there’s no magic and universal approach to fixing issues that you discovered in your WordPress website’s error log. Every PHP error will need to be troubleshot on its own.

              If the PHP error is created by a third-party plugin you need to contact the plugin editor support so it can be fixed permanently. If you try to fix it yourself, the error might just happen again the next time the plugin is updated.

              If you are looking for further information, you should check the official documentation of PHP.

              If you like this article, you might be interested in our section “troubleshoot WordPress errors“.

              Introduction

              When you develop the website, it is not a bad idea to control the possible errors or check other information the server replies to your queries. One of the best ways to do that is to set up and read the WordPress logs. In the article, we are going to explain what are the types of log files, and how to set them up on different servers and read them to analyze the different aspects of your website.



              WordPress error log
              WordPress error log

              There are two main server types: Apache and Nginx. Let’s see how to set up a WordPress error log for each of them.

              Apache is a powerful open-source solution for web servers. The logging capabilities in Apache are very flexible. Most log setting options are applicable to any operating system, but some of them are specific only for Unix or Linux.

              Apache by default is pretty well configured for logging one’s site. The standard httpd.conf file must have a section of logs with detailed comments for each directive. The default log directory is usually located in /etc/httpd/logs. Now let’s look at the log settings section:

              ErrorLog logs/error_log
              LogLevel warn
              LogFormat "%h %l %u %t "%r" %>s %b "%{Referer}i" "%{User-Agent}i"" combined
              LogFormat "%h %l %u %t "%r" %>s %b" common
              LogFormat "%{Referer}i -> %U" referer
              LogFormat "%{User-agent}i" agent
              CustomLog logs/access_log combined


              Apache WordPress Error Log

              The WordPress error log contains messages from Apache like errors, notifications, warnings, etc. This log is very useful for finding and fixing server-side problems. It is written in the site’s Apache config file usually placed in /etc/apache/sites-available/ folder. Let’s see how to set up it:

              If you want to store all information about errors in one log, this directive will suffice. However, you can specify a WordPress error log file for each domain. This is done in the <VirtualHost> sections approximately as follows:

              <VirtualHost 10.0.0.2>
              DocumentRoot "/home/sites/domain1/html/"
              ServerName domain1.com
              ErrorLog /home/sites/domain1/logs/error.log
              </VirtualHost>

              If you are a system administrator or have root access to the server, you should be able to monitor these logs. We recommend using one file. And if you provide hosting for clients, it is more convenient to set a separate error log for each client so that they can track their errors.

              The level of errors entering the log is set as follows:

              Types of Errors

              The following error levels are defined in Apache:

              • emerg — emergency – the system does not function;
              • alert — the error must be immediately corrected;
              • crit is a critical error;
              • error;
              • warn — warning;
              • notice — notification (normal operation);
              • info — information message;
              • debug — debug message.

              Keep in mind that all subsequent levels include previous ones. That is if we set the warning level, the log will get errors from the following classes: emerg, alert, crit, error, and warn.


              WordPress Error Log Nginx

              Log files are the first place to look for errors. Especially if it relates to a web server. In Nginx, there are only two main logs: error log and access log.

              Logging of the Nginx errors occurs in a specific file, stderr, or Syslog. It collects all the errors that occurred during the operation of the webserver. By default, it is enabled globally:

              To log only certain errors, you need to place a directive in the HTTP, server, stream, or location section. And so you can only log critical errors and alarms

              Nginx: Types of logs

              An error log is very useful when debugging site issues, configuring new plugins, and installing themes. So, for example, if you see a “White Screen of Death” Error when you open your site, the first thing to do is to open an error log for this site in your account. The error log is the most optimal way to monitor and detect errors when working or configuring a site.

              The Access log shows the IP addresses and which URL has been accessed, along with a timestamp for each domain. This can be useful for the detection and analysis of third-party log analyzers and for identifying security issues like DDOS attacks.

              Next, remember that the logs are included in the total quota of disk space for the account. If you have little space on your server, then you need to periodically clean these logs or turn them off.

              With the correct operation of the site (without errors) and a small number of visitors, your logs will be small. That’s why you can clean them periodically if there is not enough disk space.

              But there are cases when the error log or the access log becomes very large. The error log can be large in size if some script does not work correctly and every time it is accessed, an error occurs that is noted in the log — such a log will have many entries and, accordingly, a large size.

              The access log can be of a large size if a site is under attack like a DDoS ​​attack.


              How to enable WordPress Error logs (Nginx)

              In order to enable a dedicated and separate Error and Access log for a single site, we need to add the following code in its Nginx site config file. This file is usually present in the ‘/etc/nginx/sites-available/‘ folder.

              access_log /srv/www/test.com/logs/access.log;
              error_log /srv/www/test.com/logs/error.log;


              How to enable logs using wp-config.php

              The wp-config file contains basic parameters and settings for your site on WordPress. It stores such important data as connection settings to the database, a prefix for the database tables, and an address for logging into the admin area if WordPress is installed in a subdirectory.

              But in addition to the basic settings, wp-config can also be used to set other parameters. For example, you can enable debugging mode (wp_debug) and write all the received data to the error log. In most cases, this helps to identify and fix problems on the site.

              First of all, you need access to the wp-config.php file itself. The file is located in the root directory of WordPress, and in order to edit it, we need an FTP client or File Manager if you have access to cPanel.

              Open the file wp-config.php and find there the line “That’s all, stop editing! Happy blogging.”

              Just before this line, add a new line of code:

              define ('WP_DEBUG', true);

              Perhaps this line is already present in the file with the “FALSE” value. In that case, you do not need to duplicate it, just change FALSE to TRUE.

              With this code, you will enable WordPress to debug mode. Be ready that WordPress will display all warnings and errors on the site at the top of the page, both in the admin panel and on the site itself.

              Therefore, the general recommendation is not to leave debug mode on permanently, use it only when necessary.

              Now, in order to additionally include the record of all detected errors and warnings in the log file, add one more line of code in the same wp-config file, just below the line with WP_DEBUG:

              define ('WP_DEBUG_LOG', true);


              How to view WordPress Error logs

              From command line

              To view the logs from the SSH console or command line, we will use the ‘tail‘ command in this example.

              The tail command allows you to view the last 10 lines of the file, in this case, the error or access log.

              tail  /srv/www/test.com/logs/error.log

              In case you need to see more number of lines, For example, 25, then we can use the ‘n’ flag :

              tail -n 25  /srv/www/test.com/logs/error.log

              Or the following way:

              tail -25 /srv/www/test.com/logs/error.log

              The second useful parameter that you can pass is -f. With this parameter, the tail displays the specified number of last lines and continues to read the lines to add, until you press Ctrl+C.

              It means that you can live-track the changes in the log file. This is particularly helpful when trying to pinpoint the exact URL which is causing the error. You can reload the page and see exactly which errors it is throwing :

              tail -5f /srv/www/test.com/logs/error.log

              Here is a sample output for a tail command:

              2018/07/07 10:34:21 [error] 11738#11738: *128307 FastCGI sent in stderr: "PHP message: PHP Warning: json_decode() expects parameter 1 to be string, array given in /srv/www/test.com/public_html/wp-content/plugins/wpbase-cache/wpbase-cache.php on line 74" while reading upstream, client: 124.40.251.253, server: test.com, request: "POST /wp-admin/plugins.php?plugin_status=all&paged=1&s HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.com", referrer: "https://test.com/wp-admin/plugins.php?plugin_status=all&paged=1&s"

              2018/07/10 02:12:44 [error] 29169#29169: *16240 FastCGI sent in stderr: "PHP message: PHP Fatal error: Out of memory (allocated 14680064) (tried to allocate 4096 bytes) in /srv/www/test.com/public_html/wp-content/plugins/jetpack/class.jetpack.php on line 2097" while reading response header from upstream, client: 185.85.191.201, server: test.com, request: "GET /wp-login.php HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.com"

              2018/07/10 07:01:31 [error] 32488#32488: *2605 recv() failed (104: Connection reset by peer) while reading response header from upstream, client: 66.249.79.10, server: test.com, request: "GET /mlebusik/?action=lostpassword HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.com"

              2018/07/11 03:59:43 [error] 10455#10455: *27706 FastCGI sent in stderr: "PHP message: PHP Fatal error: Out of memory (allocated 2097152) (tried to allocate 16384 bytes) in /srv/www/test.com/public_html/wp-includes/general-template.php on line 1507" while reading response header from upstream, client: 66.249.79.31, server: test.com, request: "GET /robots.txt HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.com"

              Let’s breakdown one error log entry and see what it means:

              2018/07/11 03:59:43 [error] 10455#10455: *27706 FastCGI sent in stderr: "PHP message: PHP Fatal error: Out of memory (allocated 2097152) (tried to allocate 16384 bytes) in
              /srv/www/test.com/public_html/wp-includes/general-template.php on line 1507" while reading response header from upstream, client: 66.249.79.31, server: test.com, request:
              "GET /robots.txt HTTP/1.1", upstream: "fastcgi://127.0.0.1:9000", host: "test.com"

              • 2018/07/11 03:59:43— Timestamp, when the error occurred
              • [error] —Type – Error. This can also be a Notice, Warning, etc;
              • “PHP Fatal error: Out of memory  ….” — Error message;
              • “66.249.79.31” — IP from where the request originated;
              • [07/Aug/2013:23:04:22 +0000] — request date and time;
              • GET /robots.txt HTTP/1.1 — the request;
              • host: “test.com” — The Domain name;

              Apache Error Log Example :

              site.com [Sat May 31 12:07:10 2008] [error] [client 127.0.0.1] File does not exist: /srv/www/test.com/public_html/favicon.ico
              site.com [Fri Aug 05 13:50:37 2011] [alert] [client 127.0.0.1] /srv/www/test.com/public_html/.htaccess: RewriteRule: cannot compile regular expression '^edit_serv/(.*):([0-9]{2,20}+)/

              The logs include the domain name to which the request was registered, the time of the request, the IP address from which the access was made, and, directly, the error text.

              View WordPress Error log using FTP

              WordPress error log
              WordPress error log

              If you have an FTP user credential that has sufficient permissions to access the WordPress Error log and access log files, then you can simply log in using an FTP Client like FileZilla and then navigate to the Error log Directory and download it or open it directly in an editor of your choice.

              The WordPress error log is a great way to control the website processes. How often do you use them?

              The logs include the domain name to which the request was registered, the time of the request, the IP address from which the access was made, and, directly, the error text.


              Summary

              The WordPress error log is a great way to control the website processes. It contains all the warnings and error messages does your website has gone through. So it is very important for you to know how you can set up and access them from time to time.

              However, if you have already set up WordPress error logs on your website, then How often do you use them? Do let us know in the comment section below!


              Frequently Asked Questions

              How do I find my WordPress error log?

              You can find WordPress error logs in the site’s Apache config file usually placed in /etc/apache/sites-available/ folder or you can go to File Manager and look out for the wp-content folder and locate the debug.log file.

              What is WordPress error log?

              Error logs are generally a collection of all the tracks and records that contains possible error reports and information the server replies to your queries.

              How do I create a WordPress error log?

              1. First you need to access the wp-config.php file itself. The file is located in the root directory of WordPress.
              2. And in order to edit it, we need an FTP client or File Manager if you have access to cPanel.
              3. Open the file wp-config.php and find there the line “That’s all, stop editing! Happy blogging.”
              4. Just before this line, add a new line of code:
              define (‘WP_DEBUG’, true);
              5. Perhaps this line is already present in the file with the “FALSE” value. In that case, you do not need to duplicate it, just change FALSE to TRUE.
              6. Now WordPress will display all warnings and errors on the site at the top of the page, both in the admin panel and on the site itself


              WordPress log files are one of the most important aspects of the entire WP ecosystem that you may have never heard of. Or at least, may have never thought of. Log files are essentially records of everything that your website and server has done over its life (or a specific time frame). Unfortunately, many people see log files as being hard to understand and use. We want to break through that misconception and show you how to use WordPress log files and what that knowledge can do to improve your website.

              Subscribe To Our Youtube Channel

              • 1
                What Can You Do with WordPress Log Files?

              • 2
                WordPress Debug Log Files

                • 2.1
                  Step 1: Finding wp-config.php

                • 2.2
                  Step 2: Editing wp-config.php

                • 2.3
                  Step 3: Finding, Reading, and Understanding the Log File

              • 3
                Wrapping Up

              What Can You Do with WordPress Log Files?

              The use of WordPress log files differs depending on your role. A user will find different things useful than an admin would than a developer would and so on. But there are a number of things that these very same log files do, and many of the purposes can overlap.

              • finding errors
              • aid troubleshooting
              • auditing security
              • assessing accessibility standards
              • monitoring user experience and customer journey
              • track user activity
              • check plugin performance
              • explore themes

              And a lot more. Plus, there are a lot of different kind of log files. Some are specific to WordPress itself, while others may be generated by individual plugins. Let’s look at some of them in particular to see what you can expect.

              WordPress Debug Log Files

              Strangely enough, the default WordPress log file itself is disabled for new WP installations. You have to go into the wp-config.php file and manually enable it. The debug logs are disabled by default because logging everything that your WP installation does takes some of your server resources. Instead of running the site, it’s logging how it runs the site.

              We recommend that you enable logging only for a short period as issues arise to fix them. Unless you’re working in a development environment, of course.

              Now, you can enable logs in multiple ways. Via FTP using a program like FileZilla and editing the file in a code editor. By cPanel, or even via a plugin such as WP File Manager. Regardless, the process is simple. You are going to find the wp-config.php file in your installation’s root directory and add two lines of code to it.

              • define( ‘WP_DEBUG’, true );
              • define( ‘WP_DEBUG_LOG’, true );

              Step 1: Finding wp-config.php

              Wherever your root directory is, connect there. Most likely it will be under /public_html/example.com/ (the .com part may or may not be there).

              WordPress Log Files

              Step 2: Editing wp-config.php

              Once there, open it up in your editor of choice. Sublime Text, VS Code, and Atom are all popular choices. Scroll until you find the line that reads /* That’s all, stop editing! Happy blogging. */ Once there,paste the two lines of code above directly above it. You might even have one marked false already in the file.

              WordPress Log Files

              The top line enables debugging to occur, while the second generates the log file itself. In this format, the snippet saves the WordPress log file to wp-content/debug.log, but you can replace true with a relative path in single quotes to specify a different place. For example, define( ‘WP_DEBUG_LOG’, ‘/tmp/wp-errors.log’ ); as specified in the WordPress Codex entry on debug logs.

              Step 3: Finding, Reading, and Understanding the Log File

              Be aware, your log file might not appear immediately. It is not a real-time log of the server’s activities, but a log of the errors that occur within it. Hence why we recommended earlier that you only enable it when something is going wrong. So if the debug.log file doesn’t exist yet, give it time. Something will break, eventually.

              WordPress Plugin Page

              When you finally get the debug.log file, you can open it either in the file manager or in the code editor of your choice. But you will see something similar to this.

              WordPress Support Forums

              For a typical WordPress user, this looks like gobbledygook. For a developer, though, they would see the PHP issues in a couple of plugins being unable to perform certain tasks.

              Step 4: Get Help

              As we said above, most WP users would have no idea what to do with these errors. However, when your site isn’t performing optimally, you need these thing fixed. That’s when you have to find someone to help you.

              You have a few choices in this particular path, the most obvious of which is to download the entire debug.log file and send it via Slack or email to your systems administrator. Most of the time, this is the best choice. Even if you’re a dev and have this log, you’ll probably be sending it up the chain (or maybe down it, if you’re a senior dev and delegating tasks).

              But if you’re not part of a team, you will also likely need to take the file and send it somewhere. But where? Stack Overflow. Or maybe even more specifically, WordPress Stack Exchange (the subforum from SO based around WP). If you can’t get an answer on Stack Overflow or Stack Exchange about your tech problem, you should go buy a lottery ticket. Because those are some crazy odds.

              Additionally, you could send the debug logs to the developers of the plugin directly, or even post on the official WordPress help forums over at WordPress.org. While the issues may be with individual plugins, the logs are from WP and folks have likely run into these particular issues before.

              On top of that, there are plugin support pages on each plugin’s repo page.

              WordPress Log Files

              These take you to the direct support forum on WP.org for that specific plugin.

              WordPress Log Files

              Using these forums can get some individualized help for your problems.

              Wrapping Up

              As you can see, WordPress error logs are incredibly dense. They can be intimidating, and even getting them set up (outside of using a plugin) can be scary for some folks. But if you keep the debugging limited to either a development environment or shut it off after grabbing the logs on a public server, they are a fantastic troubleshooting tool to see what’s going wrong under the hood of your site. So the next time your users have an issue, or even your staff has an issue with the backend of the site not performing as expected, WordPress log files can be a fantastic line of defense.

              What kind of situations have monitoring WordPress log files have you been able to fix or prevent?

              Article featured image by fatmawati achmad zaenuri / shutterstock.com

              Use WordPress logs to fix problems that arise on your WordPress instance — or, more accurately, to figure out why they’ve occurred. This feature tracks errors and records them in one easy-to-locate file, so you can get started on the troubleshooting process.

              There are three basic steps to enable WordPress error logs:

              1. Access your website’s files using FTP.
              2. Edit your wp-config.php file.
              3. Locate your new WordPress logs.

              In this article, we’ll talk a little more about why WordPress logs are so useful and go through step-by-step on how to activate and use them on your own site.

              Why You Might Need to Enable Error Logs in WordPress

              The WordPress troubleshooting forums.

              Using the information from your WordPress logs, you can easily get help in the official forums.

              No software is perfect, after all, which means there might come a time when you run into problems or bugs with WordPress. Most users extend the platform with a variety of themes and plugins and while beneficial (and essential) for the most part, this can result in compatibility issues and other unforeseen problems.

              There are many places online to seek help when you run into WordPress bugs or errors, but in order to get assistance, you’ll need to know what the problem actually is. As a result, it’s crucial to know how to perform some basic troubleshooting.

              To carry out troubleshooting, you’ll often need to enable WordPress logs. This will help you find out what errors are causing the problems you’re experiencing, and track them to their source. Once you’re armed with that knowledge, actually solving the issue will be much simpler.

              How to Enable WordPress Logs to Track Website Errors (In 3 Steps)

              While WordPress has error log functionality — also known as the ‘debugging mode’ — it’s turned off by default. Fortunately, changing this is easy. Let’s walk through how to activate and use your WordPress logs.

              However, before proceeding to the first step, you’ll want to have a recent backup of your website in place. You’ll be making an edit to a core WordPress file, which should be safe if you’re careful. However, there’s always the potential for something to go wrong, and a backup ensures you have a way to restore your site if the worst happens.

              Finally, it’s also smart to perform troubleshooting on a staging site. Creating a staging site isn’t difficult, and it’s a very useful resource to have, so we recommend doing this before moving on.

              Step 1: Access Your Website’s Files

              To activate your WordPress logs, you’ll need direct access to your site’s files. This can be done in a few ways, but we recommend using File Transfer Protocol (FTP). Using an FTP client you can log directly into your site. Then you can add to, edit, or delete files whenever the need arises.

              If you don’t have a favorite FTP tool already, the FileZilla client is a solid choice. It’s free and simple to use:

              The FileZilla website header.

              After downloading and installing FileZilla, you’ll just need to enter your FTP credentials to access your site. These are provided by your web host, and can usually be found in your control panel.

              Once you have your credentials in hand, you can enter them into FileZilla. You’ll need a Host, Username, and Password (you can leave the Port field empty):

              Adding credentials in FileZilla.

              Then, click on the Quickconnect button. When the client has connected successfully to your site, you’ll see a success message along with several new folders and files.

              Step 2: Edit Your wp-config.php File

              At this point, FileZilla should look something like this:

              The main FileZilla window.

              There are four main quadrants here — check out the one in the top right corner. This window should contain a few folders, including the primary (or ‘root’) directory for your WordPress website. This folder might be called root or www, or it may have the same name as your site’s domain. Either way, open it up.

              In the bottom right quadrant, a long list of folders and files will appear:

              The wp-config.php file in FileZilla.

              Scroll down until you find the one called wp-config.php. This is an important file containing key information about your site’s configuration and database.

              Right-click on it, and select the View/Edit option. Doing this will open the file in your computer’s default text editor:

              The wp-config.php file in a text editor.

              Scroll down the file, looking for a line reading: /* That’s all, stop editing! Happy blogging. */. You’ll need to paste in the following line of code before this:

              define( 'WP_DEBUG', true );

              This snippet tells WordPress to activate the debug mode. It may actually be present in your wp-config.php file already, in which case you’ll simply need to change false to true.

              Right underneath that line, you should add one more snippet:

              define( 'WP_DEBUG_LOG', true );

              This is what tells WordPress to keep a log of any errors that occur on your site. Together, these two lines are what set up your WordPress logs. At this point, you can save the file and close it. FileZilla will ask if you want to replace the old version of wp-config.php on your server with the new version — you should answer “Yes”.

              Step 3: Locate Your New WordPress Logs

              Your WordPress logs are now ready to go. Before we wrap up, however, let’s talk about how to use them.

              Your new error log isn’t going to track problems that have occurred in the past. Therefore, if you’re trying to troubleshoot a specific issue, you’ll need to trigger it again by interacting with the element or performing the action that caused it in the first place. This should prompt WordPress to log the error.

              You can find the record of this error by logging into your site again using FTP. In your site’s root folder, navigate to the wp-content folder, and look for a new file called debug.log:

              The error log file in FileZilla.

              If you open it up, you’ll see a list of any errors, warnings, and other issues that have occurred on your site since activating your WordPress logs:

              An error log open in a text editor.

              At this point, you have a few choices. If you’re reasonably tech-savvy, you can attempt to figure out what the problem is on your own and fix it. In some cases, your WordPress logs might help you understand what’s causing the error, such as by naming the element at fault. However, performing your own troubleshooting can still be challenging if you aren’t a developer (or don’t have one on hand).

              If you need help, visit the WordPress forums and create a post asking for assistance. Be sure to include the text from your WordPress logs, and you should be able to get the help you need quickly. You can also try doing a Google search on the error, to see anyone has put together a guide for how to solve it.

              Finally, it’s a good idea to turn your WordPress logs off when you’ve finished your troubleshooting and found a solution. This is less important if you’re working with a staging site, but vital if you ever activate error logs on a live site. Leaving the log functionality on can slow down your otherwise fast WordPress site and expose sensitive information to potential hackers. To turn it off, you’ll simply need to open up wp-config.php once again, change true to false in both lines you added earlier, then save it.

              Wrapping up the Overview of WordPress Logs

              When errors occur, you may find yourself needing a little assistance. This is when WordPress logs come in very handy since they let you pinpoint the source of an error so you can search for a solution or ask for help.

              Before enabling WordPress logs on your site, it’s smart to have a recent backup in place and set up a staging site. Then, you can follow these three steps to create and use an error log:

              1. Access your website’s files using FTP.
              2. Edit your wp-config.php file.
              3. Locate your new WordPress logs.

              Questions about how to use WordPress logs to troubleshoot errors on your site? Ask in the comments section below. And for current Pagely clients needing help with logs, please review ‘Debugging Errors on WordPress & Viewing Logs.’

              Last updated: June 6, 2023

              WordPress error log

              Logs can be very helpful when troubleshooting and debugging issues on your WordPress sites. Viewing your access and WordPress error logs is pretty simple. Just follow the instructions below.

              How to View Access and WordPress Error Logs

              There are a couple of different ways to view your access and WordPress error logs, one is via the MyKinsta dashboard, and the other is simply downloading the raw log files.

              • Option 1 – MyKinsta dashboard
              • Option 2 – View raw WordPress logs
              • Option 3 – Enable Debug Mode in MyKinsta
              • Option 4 – Enable error logs in wp-config.php file

              Option 1 – MyKinsta Dashboard

              You can access your logs in the MyKinsta dashboard. This is a fast way to quickly debug something without having to spin up your FTP client or command line.

              Simply click into one of your WordPress sites and, on the left-hand menu, click on Logs. You can view your error.log, kinsta-cache-perf.log, and access.log files by selecting your preference in the dropdown menu.

              error.log file

              error.log file in MyKinsta Log viewer.

              error.log file in MyKinsta Log viewer.

              kinsta-cache-perf.log file

              kinsta-cache-perf.log file in MyKinsta Log viewer.

              kinsta-cache-perf.log file in MyKinsta Log viewer.

              access.log file

              access.log file in MyKinsta Log viewer.

              access.log file in MyKinsta Log viewer.

              Option 2 – View Raw Access and WordPress Error Logs via FTP

              The second way to view your logs is simply downloading the raw log files. First, you will want to connect to your site via SFTP. Then in the root, you will see a folder called “logs”.

              wordpress error logs folder sftp

              Within the folder are your access logs, WordPress error logs, and also your Kinsta cache logs.

              • access.log
              • error.log
              • kinsta-cache-perf.log

              logs wordpress

              Gzip (.gz) backups are automatically created for older logs archives. You can see the codex for additional debugging information in WordPress.

              Option 3 – Enable Debug Mode in MyKinsta

              For Kinsta users, WordPress debug mode can be enabled right in the MyKinsta dashboard. Simply navigate to the Tools tab and click the Enable button under WordPress debugging.

              Enable WordPress debug mode in MyKinsta.

              Enable WordPress debug mode in MyKinsta.

              Option 4 – Enable Error Logs in wp-config.php File

              Your final option to view your WordPress error logs is to enable them in your wp-config.php file. First, you will want to connect to your site via SFTP. Then download your wp-config.php so you can edit it. Note: Always make a backup of this file first!

              Download wp-config.php file

              Download wp-config.php file

              Find the line that says /* That's all, stop editing! Happy blogging. */ and just before it, add the following (as seen below):

              define( 'WP_DEBUG', true );

              WP_DEBUG

              WP_DEBUG

              If the above code already exists in your wp-config.php file but is set to “false,” simply change it to “true.” This will enable debug mode. Note: You will also see warnings or error in your WordPress admin if they exist.

              You can then enable the debug log to send all errors to a file by adding the following code just after the WP_DEBUG line (as seen below):

              define( 'WP_DEBUG_LOG', true );

              WP_DEBUG_LOG

              WP_DEBUG_LOG

              Save your changes and re-upload this to your server. The errors will then get logged to the debug.log file within your /wp-content/ folder. If for some reason you don’t see this file, you can always create one.

              Important: If you have WP_DEBUG enabled in the Kinsta environment, all errors will be routed to the debug.log file and nothing would go to the error.log in the MyKinsta dashboard.

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