Как посмотреть лог ошибок 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 зонах

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

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

What is error logging and why is it important?

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

How to enable error logging

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

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

1. Connect to your website via sFTP

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

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

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

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

3. Edit the wp-config.php file

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

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

define( ‘WP_DEBUG’, true );

if ( WP_DEBUG ) {

        @error_reporting( E_ALL );

        @ini_set( ‘log_errors’, true );

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

        define( ‘WP_DEBUG_LOG’, true );

        define( ‘WP_DEBUG_DISPLAY’, false );

        define( ‘CONCATENATE_SCRIPTS’, false );

        define( ‘SAVEQUERIES’, true );

}

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

define( ‘WP_DEBUG’, false );

How to view the error log manually

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

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

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

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

How to view the error log using a plugin 

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

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

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

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

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

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

Apr 20, 15:08:59

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

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

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

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

In this case, the error is a notice.

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

How to fix errors

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

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

Troubleshooting with the WordPress error log

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

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

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

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

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

How to Find and Access WordPress Error Logs

How and When Can WordPress Error Logs Help?

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

What Is an Error Log?

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

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

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

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

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

Enabling WordPress Debug Mode With a Plugin

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

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

WP Debugging plugin

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

Enabling WordPress Debug Mode Using Code

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

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

Edit Your Website's wp-config.php File

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

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

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

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

How to Find and Access WordPress Error Logs

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

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

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

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

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

Download, View, or Edit the debug.log File

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

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

Debug.log Contains Error Messages and Time Stamps

How to Fix Issues Found in WordPress Error Logs

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

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

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

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

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

Disabling WordPress Debug Mode

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

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

Deactivate the WP Debugging Plugin

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

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

Deactivate WordPress Debug Mode

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

/cta

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

Editorial Staff

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


The continuation of the Troubleshooting Basics workshop is aimed at a beginner audience. The workshop will cover the following topics:

Debug Logs
* How to enable debug logs
* How to catch errors in the debug log.

Console Logs
* An introduction to the browser console
* Finding errors using the browser console.
* Troubleshooting using the errors found in the browser console.

Learning outcomes

  1. How to enable debugging on a WordPress site.
  2. Using debug messages to identify issues on a site
  3. Using the browser console to find front-end errors on a site.

Comprehension questions

  • How can you enable debugging on a WordPress site?
  • What can you do to ensure that debug errors do not show up in the site front end?
  • What type of errors can be discovered using the browser console?

Transcript

0:04
Hello folks, my name is Hari Shanker. I’m a deputy with the WordPress community team. Welcome to part two of the WordPress troubleshooting basics workshop. This workshop is a continuation of the WordPress publishing basics workshop part one, where we discussed in detail about the approach to troubleshooting issues. We also talked a bit about some common troubleshooting techniques such as conflict tests, refreshing permalinks, taking backups and creating staging sites. In this workshop, we will cover the following topics, which is one, troubleshooting with the help of debug logs in WordPress and to using console logs to help troubleshoot WordPress issues. Alright, folks, without further ado, let’s dive in and dig deeper. WordPress comes with specific debug systems designed to simplify the debugging or the troubleshooting process as well as to standardize the code across the core plugins and ithemes. programmers can use these debugging tools for development. Whereas for non programmers, or general users these options can be used to show error information in detail. Now, what is WP debug? WP debug is a PHP constant are a permanent global variable that can be used to trigger the debug mode throughout WordPress. It is assumed to be false by default, and is usually set to true in the WP config dot PHP file on development copies of WordPress. Let’s take a look at the back end of a server to see how the debug mode can be enabled on a server with with the WP config or PHP. So as you can see right now we on the cPanel or the control panel of an Apache server the site that I host. So what I’m going to do is I’m going to open the file manager. Now, just to be clear, even though I’m using a server here, you don’t really need to use a file manager which comes with the hosting. If you have FTP access to your site or if your site runs on a local server, you can directly go to the site’s folder but I’m just using this example to give up more real world experience to your Alright, so I’m now going to navigate to the public HTML folder over there. I’m going to scroll down and as you can see this WP config PHP file. Now I’m not going to open the WP config dot PHP file for security reasons I’m going to open the WP config sample PHP file. What I’m going to do is I’m going to select it and then we’ll click the Edit button. Yes, now as you can see, it has populated some information. Now please note this is the sample file in the real world. You should be opening the WP config dot PHP file. That’s why you need to make the edits but the WP config dot PHP file contains a lot of sensitive information regarding the site so I’m not going over that I’m going to open the config sample dot PHP file instead. Alright, so when you scroll down over there, underneath you see this line. It says define WP underscore debug false. So we learned that WP underscore debug is a variable. It’s a constant rather, it’s not a variable, and it is set to false. If we want to enable debugging in our site, we will need to set this to true and then we will need to save changes. By doing so we are enabling debugging mode in our praecipe. Let’s get back to exploring WP debug. And over here you can see several other functions along with WP debug. Let’s explore each one by one. Before that I’d like to talk a bit about the true and false values in WP debug. So what happens when you set WP debug to true? So first thing that you need to keep in mind is that the true and false values are not to be surrounded by apostrophes. That’s because these are Boolean. So the only options here are true or false. So if you want to enable WP debug, enter the value true if you want to disable it, enter the value false. All right. So it is actually not recommended to use WP debug on any of these debug tools on live sites. That’s that’s one thing that I actually forgot to say earlier, but this is extremely important. These tools are essentially meant for local testing, and for working on staging installs. So it is strongly not recommended to enable debugging on a live site so this is for you to keep in mind. Enabling WP debug will cause all PHP errors, notices and warnings to be displayed. This is likely to modify the default behavior of PSP, which only displays fatal errors and our shows a white screen of death when errors are reached.

Now, keep this in mind showing all PHP notices and warnings often results in error messages for Things that do not seem to be broken. But they do not. They might be things that do not always follow proper data validation standards or conventions since ipsp. These warnings are easy to fix once the relevant code has been identified, which is most likely from coming from WordPress theme or plugin, and the resulting code is almost always more bug resistant and easier to maintain. Enabling WP debug will also cause notices about deprecated functions and arguments within WordPress that are being used on your site. These are functions or function arguments that have not been removed from the core code yet, but are slated to be deleted in the near future. deprecation notices often indicate that a new function should be used instead. Let’s move on to the next constant which is called The WB underscore debug log. WP debug log is a companion to WP debug that costs all errors to be saved into a debug log file. This is useful if you want to review all notices later, or need to view notices generated off screen. For instance, let’s say you’re doing an AJAX request during a web con run. So in such cases, it allows you to write to log the log file using the PHP is built in error log function. Why is it useful? This could be useful in specific instances when debugging attacks events. When set to true, the log is saved to debug that log file in the content in the content directory, which typically is in WP hyphen content underscore slash debug dot log or so if there’s a WP content folder, I mean that all would resize our WP content folder right? So the debug log will live in a Ruby in the WP content folder if you set WP debug to true. Alternatively, you can set it to a valid file path to have the file saved elsewhere. How do you do that? So let’s say you want to you want to set it on a sub folder. In that case, you can simply change this, change the value instead of true. You can set it something like I’m going to set a temporary address here. So yeah, I can set it so in this case, it gets stored to are stored under underneath a folder called TMP on a file called WP hyphen errors dot log. So yes, but if you don’t do anything if you just set it to true. We just set WP underscore debug debug underscore log to true. It gets stored in your WP content directory. Now there’s a mistake here I’ve set quotation marks which is not something that I should be doing. Since it’s Boolean I should not set quotation marks it just it should just be true. Now, please keep this in mind. If for the for the for WP debug log to do anything, WP debug must be enabled. Now moving on, there’s another function called WP debug display. And as you can see here, it is set to false. It’s pretty evident as you can see in this tooltip it means that it disables display of errors and warnings. Now, it this function this content is basically companion another companion like WP debug log. So it controls essentially controls whether the debug messages are shown inside the HTML basis or not. This is set to true by default, but we can set it to false. And this should be this should be used in conjunction WP debug log for errors that can be reviewed later. Now if it is set to false, no error will be shown in the side panel. So if you do not want any errors in your site to show up in your site’s dashboard, you can simply turn it, turn it off or set it false. But if you do want to display errors, you can tell the truth. So I’m going to set it to false for the time being. This another content that we are going to learn today it’s called script debugger. But before we get to that, as I mentioned earlier for WP debug display to do anything, WP debug must be enabled. Now this applies to both WP debug log as well as WP debug display. So for both of them to work, you would need to enable WP debug now in this example, it doesn’t really work because I’ve said WP debug defaults. So I’m going to set it to true. So if I want WP debug log to work and if one WP debug display to work, I should set WP debug to true. Moving on to the next debug script. It’s called script debug.

9:47
As you can see, it’s set to true. The tooltip explains it but if I were to explain in detail this is a related concept that will force WordPress to use the dev versions of core CSS and JavaScript files. Rather than the minified versions, which are normally loaded, what does this mean? So WordPress uses minified functions minified JavaScript libraries, open faces libraries to save space. So when we enable to debug what receives does not use the minified libraries, it uses the entire libraries, what does the minified library, a minified library means the file is compressed, to reduce the space. So when this setting is set to true WordPress loads the entire libraries, which are called so some of these libraries include jQuery. So it loads the non minified library directly. And this is very helpful in troubleshooting. This is extremely useful when you are testing modifications to any built in JS or CSS files. So this is false by default, but I’m for the time being I’m set to true. In other option that I’ve not really added to this file, which I can I can actually do it right away for you is the Save queries option. I’m going to I’m going to quickly add it here. So this is save queries, save queries definition essentially saves the database queries to an array. And that array can be displayed to help to analyze those queries. So in short, when you when you set save queries to true, WordPress saves all the database queries that happen on your WordPress site into a PHP variable. Now, WordPress essentially uses a MySQL database to show content, right. So there’s a lot of database activity happening. So when you even when you open a page, there’s there’s a database, there are database queries happening in the backend, do get all the data from the databases and showed you one of them page. So all those queries that happen underneath the hood, they get stored in a variable. So typically, it gets stored in a variable called queries. And so this is for the developers in here. So there’s a there’s, there’s a global WP Db object. So the WP Db object has, has a query variable, so the query is variable, that’s where all the data gets stored. So this is not for lay users. But if you are an advanced user, and if you would like to see all the queries, you can make a reference to the WP Db queries variable to get all the data stored on that variable.

12:23
Now, please start enabling save queries is going to have a very significant performance improvement on your site. So it is strongly recommended to set it to false unless you have a real need for it. So I’m following that advice and I’m going to set it to false, then I’m going to save the changes. So this essentially explains all the WP debug actions that we can use to troubleshoot WordPress, it’s time for us to quickly see WP debug in action. So I’m going to I have the ID Akismet plugin installed on my site, I’m going to deliberately make some changes to the files in here. Let’s, let’s see if that has any effect on our site. So this is a case where it’s dot Roderick dot PHP. And this is the blog input. So this is this is a local server that I have on my computer. And as you can see, so we are on the local plugin folder, I’m going to go to WP content, I’m going to go to plugins. When a guest ma.tt I’m going to open the Akismet or PHP file. So there’s this line. I’m just going to comment it out. I’m going to comment out the slide. Alright, I’ve saved the changes. And this is the same WP config file that we checked earlier. I’ve set WP debug to true I’ve set WP debug log to true. Now WP debug display here as false. Alright, so let’s see. Let’s take a look at the site to see what actually happens when you try visiting the site. site URL is WP desktop test. I’m going to try logging into its back end who I can see that that’s been in pretty good. Invalid press. It says please check your site email admin inbox for instructions.

14:03
Why could that have happened? let’s actually take a look to see why that would have happened. So if you look at the Akismet file, it happened because I commented this file to that cost of login error. And let’s look back at the debug files. I’ve set WP debug display to false. I’m going to set it to true and I’m going to save changes. Let me try re refreshing the phone. Yes. Now I can see better message it says spots errors. indexer. unexpected. Right brace expecting end of file in. Yeah, so it’s on line 38. Let’s take a look at line 30 to see what actually happened. So let’s see, I guess my dot PHP file that’s been drafted that’s being referred to WP content plugins goetzmann Akismet dot PHP file. Let’s take a look at line 38. Yes, it says there’s a there’s an unnatural Bass. Why did the unnatural right bass come? That’s because I added a comment here. So I’m going to remove the comment, I’m going to save it. And I’m going to try refreshing this page to see yes, we are back in the dashboard. So folks, you just saw how to debug something what recite with WP debug enabled. Now let’s check one more thing.

15:22
So as I mentioned, this is essentially my local site, I’m going to navigate to the WP content folder. Yes, I’m here. So as you can see, this WP content folder already has a debug dot log file which has been generated, essentially, because I enabled it here. So WP debug log is set to true so that because of that, I can see debug dot log file, which also contains all the errors that we were talking about. So I hope you got to know how WP debug log works. Let’s move on to the next section. Couple of useful WordPress plugins that are going to help us debug first among that is the debug bar plugin, which as you can see has been created by wordpress.org itself. What does this do? So if you have your debug mode enabled, if you’ve set both these constants true in your, in your web config file as we’ve done our example. So in our case, yes, I’ve not said save grace to true, I’m going to set it to true. So if both these queries are set to true, we can use the debug bar plugin to troubleshoot things in our So what does this do, essentially as the Debug menu to our site’s admin bar, which shows the query the cache and other helpful debugging information. It is extremely useful for developers but even non developers can use it. It’s extremely helpful in troubleshooting. There’s also a debug bar console login. So if you really want to see what’s happening on the console, as you browse to your site, this is going to be a very useful add on to the debug bar plugin. In other plugins that I really wanted to suggest to you folks is the query monitor plugin, the query monitor plugin, it’s similar to the debug log plugin. So what it does is it helps you debugging database queries, PHP has hooks and actions, etc. So when this plugin is enabled, you get an overview of everything that happens on every action in WordPress. So that includes database queries, template file names, PSP, Rs blocks, rewrite rules, you name it. So this is for very advanced users. If you are a lay use, I would not recommend it. But if you know your what does that mean, if you want to see how things work, how, how, how the user flow, or how the site load flow takes place in WordPress, this is a very useful plugin. And I’m going to quickly show what are these plugins in action for you. The query monitor plugin enabled in my install it enabled my site right now, let’s take a look at to see it see how it works. So as you can see, it adds this bar this bar to your top. So this shows the time it has taken for the queries the data at a slower at the time it is taken to load and the number of queries that’s being executed. And so when you are on each pay when you’re logged in as an admin, when you’re on each page of the site, it shows a set of functions that are being called. So it even shows the HTTP API calls, the scripts, the hooks and actions, let’s quickly take a look at the queries. So as you can see, it shows the list of queries that are being used. So it’s very, very helpful in troubleshooting. As you can see, I’m going to quickly take a look at the hooks and actions. Yes, it shows that as well. And you can keep changing things. So it shows that it’s calling the WordPress API. It shows the styles that are being loaded. And this this actually, you can see all this data for each page that you navigate. So it shows the queries by competent shows. So right now it’s getting the WP query get posts. So we are on a we are on a static page. So it shows it shows really that it shows the headers that are being requested. You can see the scripts in action. You can see the hooks and action. Yes. So there will be no scripts WP praying for the flip. So these are the scripts, the hooks for the scripts in action, you can see the styles that are being enforced. So these are the CSS file styles that are being used. And yes, this is a full list of the total number of folks that are, you know currently showing him so hooks and actions. They are for an advanced researcher, but essentially they are functions in WordPress, which are used to drive things in WordPress. So yes, this this is a tool that can be used for a very advanced troubleshooting. But even if you are a lay user if you want to check something for an exam queries, this is extremely helpful. Now, let’s take a look at different plugin. Let’s take a look at I’m going to deactivate this for now I’m going to take a look at the debug bar plugin. So what does the debug bar plugin do? Let’s take a quick look at it. You see this quaint little debug option on the top right of your site. You can click on it and it shows a lot of information. So You can see the queries that are being used, you can see the current set of WP queries, you can see the object cache. So it’s a wealth of information really. So it’s a great way to test things in your site. So let’s see, let’s take a look at the site front end, it really shows a lot of information. So yeah, you can see the number of queries that are currently being executed. So that’s a lot of queries. So chose wb options, it shows the meta keys that are being used.

20:26
Yeah, there’s a web query section. So it shows the pages that are being loaded. It shows the requests, if any that are being loaded. It also checks if there is an object cache, yes, it seems that some object cache, which is being used here, and it shares all the data, all the all the data of my server as well, which is essentially a local server. So yeah, it’s very helpful plugin. You can even see a JavaScript console. So yes, it says resize observer loop limit exceeded that that’s an error, it shows that as well. So it’s extremely helpful in troubleshooting a lot of things as well. The other thing that I really wanted to cover today is about debugging JavaScript errors. So often, you run into issues with it, which could be related to JavaScript are, these are essentially front end errors. So what is the front end, you, you may not exactly see a PHP error in the front end, but something in the front end just stops working. So it could be a lot of things. It could be a button in your site that just stops working, or your flying menus may be broken. There are metal boxes on the side back in, they will just stop dragging or your ad media buttons are not working. So it’s a variety of things. So essentially, it seems like one of the functionalities in the front end is broken. In that case, there is a very good possibility that it is a JavaScript error. So how do you test out our suitors, the first step in doing that is to try another browser. So there are chances that such as could be browser errors. So if you have different browsers in your computer, please test with another one. So if you’re using Google Chrome, or Firefox, or Safari, test with Oprah, doesn’t Microsoft Edge, see if you can see the same error in those browsers. Now, if the site is not having the same issue in a new browser, you know that the error is browser specific. So let’s say you You fought your site, let’s say there’s a button in your site, or there’s a menu in your site, which does not work on Google Chrome, but it is working properly. in Firefox, it is working properly in opera, it is working properly in Microsoft Edge, it means that the problem is most likely with Google Chrome. The other thing that you can do is to enable script debugger. So we saw what script debugger is, you need to enable it manually in in your WP config dot PHP file. So you would need to add a constant define script debug true. So and enables to debug, as I mentioned earlier, when you enable script debugging means that what first calls a non minified versions of the JavaScript files. So in many cases, this could fix the issue, do that and come back to your site, see if that fixes the problem. If the issue is fixed, there are still debugging, you might want to report a silver possible form because there could be something wrong. But if the issue persists, that’s when we move on to the browser console. So in the beginning of this workshop, I spoke of debugging console issues. And this is where we really get our hands dirty. And we look into the browser console to see how we can fix those issues. We are on one of my test sites, which has WooCommerce installed, I just opened it to essentially show you how to use the browser console. So let’s say this Add to Cart button is not working. In this case, it is working properly. But let’s just assume that. So if issues like this happen when there is a clear childhood error, so when that doesn’t happen, what I’m going to do is we’re going to set this browser before I start for start, I’d like to say that I’m using Google Chrome, this is Google Chrome. So I’m going to right click, I’m going to go to inspect. So it shows it shows different HTML elements on the on the on the screen. So I’m going to I’ve as you as you can see, I’ve faithlegg type chosen inspect, then I choose the option console. So if there are any errors, it should ideally show up here. So in this case, there are no errors. So that means that things are working properly in the site, I actually wanted to show you an error here, but there are no errors. But you get the idea. So the typically, if there’s some error, it really shows those error messages here. And based on those error messages, it will help you identify the problem. So for instance, let’s see I’m using a payment gateway in the site to process payments. Yeah, so I’ve been I moved to the checkout page. And you can see some information here this we’re getting noticed this from Google Chrome, but for error messages, they definitely they generally show up in in the red color. So there’s an e commerce site. So let’s say if I see a red message which says there’s a problem with stripe, stripe is a payment gateway that I’ve used in the site. So that means that the payment gateway is not working properly. And I would need to contact the support folks of the payment gateway.

25:00
At the least, I really do probably do something, it could be anything like debating the payment gateway to the latest version or doing a Google search based on the error that might even lead us to the cause of the problem. So this is a very quick and simple way to debug things. Now, I mentioned that in in Google Chrome, you can watch get your control by clicking right click in try clicking in we are going to inspect. So the similar procedure for almost all of the process, you can do the same for Safari, you can similarly access the browser console for Google Chrome, the process essentially remains the same. But this helps you identify any JavaScript errors, and it will help you troubleshoot further, I’ve basically use a screenshot for reference. So I’ve arrived at the same place by clicking on right click and inspect element and go into the console tab here. So it shows a bunch of errors. It so let’s take a quick look at this, it says attach the banner invalid block. So this could have happened because probably there’s a block called a Tachibana, or a plugin called Apache Manor, which is probably triggering this error. So essentially, by by looking at these error messages, you can identify what is causing the problem. So in this case, it’s very clear to us that the error is coming from the Apache banner blog, which which is probably plugin so we can maybe deactivate the plugin and the error would go away. So this is one way to identify and troubleshoot console errors with WordPress. With that, we come to the end of the part two of WordPress troubleshooting workshops. We’ll be posting more of these workshops very soon and part three of the troubleshooting workshop will be coming in a short while. We’ll also be posting several workshops on using and troubleshooting WordPress. So stay tuned for more. Thank you so much, and I’ll see you around. Bye.



Presenters

I am an Open Source Program Manager at Automattic. I work full-time on WordPress, and I am a Community Deputy on the Make/WordPress Community Team. My current focus is on making the contributor experience for the WordPress open source software the best it can be. I’m currently leading the Contributor Working Group of WordPress, and together, we are trying to launch a Projectwide Mentorship Program for WordPress!

WordPress is one of the biggest passions in my life, and I strongly believe that open source tech and the open web have the potential to make the world a better place.

I have had a rather diverse career with significant experience in the domains of Retail Banking, Print & Web Journalism, Web Development, Entrepreneurship, Event Management, Professional Blogging, and Education.

Outside of work, I enjoy writing (blogging) as a hobby, and I’m a compulsive bibliophile. I’m also a happily married pet parent to three cats.

Диагностика проблем, возникающих на сайте 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. Обычно она называется 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

Понравилась статья? Поделить с друзьями:
  • Как посмотреть лог ошибки игры
  • Как посмотреть критическую ошибку win 10
  • Как посмотреть критические ошибки виндовс
  • Как посмотреть критические ошибки windows 10
  • Как посмотреть коды ошибок на шевроле круз