Manual:Como depurar
Esta página fornece uma introdução básica à depuração do software MediaWiki.
Uma das primeiras coisas que você vai notar é que o "eco" geralmente não funciona; isso é parte do projeto geral.
There are several configuration options to aid debugging. The following are all false
by default.
Enable them by setting them to true
in your LocalSettings.php :
$wgShowExceptionDetails
Enable more details (like a stack trace) to be shown on the "Fatal error" page.$wgDebugToolbar
Shows a toolbar on the page with profiling, log messages and more.$wgShowDebug
Adds log messages as a raw list to the bottom of the page.$wgDevelopmentWarnings
MediaWiki will throw notices for some possible error conditions and for deprecated functions.
Example line to be added in your LocalSettings.php :
$wgShowExceptionDetails = true;
Erros do PHP
Para visualizar os erros de PHP, cole o seguinte código na parte inferior do arquivo $localsettings:
error_reporting( -1 );
ini_set( 'display_errors', 1 );
Ou defina no arquivo php.ini :
error_reporting = E_ALL
display_errors = On
Ou defina no .htaccess:
php_value error_reporting -1
php_flag display_errors On
Isto fará os erros de PHP serem mostrados na página. Isto pode se tornar mais fácil para possíveis ataques no ser servidor, portanto desative quando você encontrar o problema
Note that fatal PHP errors may happen before the lines above are ever executed, or may prevent them from being shown.
Fatal PHP errors are usually logged to Apache's error log – check the error_log
setting in php.ini
(or use phpinfo()
).
Turning display_startup_errors on
Some providers turn display_startup_errors
off, which hides the errors even if you raise the error_reporting
level.
Turning it on within the program is too late! Instead you'll have to create a wrapper file around your file.
In the case of MediaWiki you can just add this on top of mediawiki/index.php:
--- index.php
error_reporting( -1 );
ini_set( 'display_startup_errors', 1 );
ini_set( 'display_errors', 1 );
Em outros ambientes:
--- myTestFile.php
error_reporting( -1 );
ini_set( 'display_startup_errors', 1 );
ini_set( 'display_errors', 1 );
require 'your_file.php';
Erros de SQL
To log all SQL queries, rather than just the one that raised the exception, set $wgDebugDumpSql in LocalSettings.php
:
$wgDebugDumpSql = true;
Versões do MediaWiki: | 1.16 – 1.31 |
Prior to MediaWiki 1.32, you needed to set $wgShowSQLErrors and $wgShowDBErrorBacktrace to see details of database exceptions in the HTML output:
$wgShowSQLErrors = true;
$wgShowDBErrorBacktrace = true;
Depuração em profundidade
Debugger
You can debug your code step-by-step with XDebug . For some common setups, see:
- MediaWiki-Docker
- mwcli
- Vagrant with PHPStorm
- Vagrant with other IDEs
- MacOS
- Local dev quickstart (Linux, macOS, Windows) on bare metal
MediaWiki-Vagrant has built in settings for this. If you're not using MediaWiki-Vagrant, but your setup is similar, you can reuse those values. In some cases (e.g. due to a firewall), you may have to use the IDE on the same machine as the web server. In this case, simply set:
xdebug.remote_enable = 1
xdebug.remote_host = 'localhost'
See the XDebug documentation for more information.
To debug a command-line script (e.g. PHPUnit, or a maintenance script) on MediaWiki-Vagrant, use:
xdebug_on; php /vagrant/mediawiki/path/to/script.php --wiki=wiki ; xdebug_off
Adjust the script, parameters, and remote host (it should be the IP of the computer where your IP is, 10.0.2.2 should work for MediaWiki-Vagrant) as needed.
Logging
Para maiores detalhes, você precisa criar um perfil e registrar erros.
$wgMWLoggerDefaultSpi
, for example to enable the psr3
role on a vagrant box, these settings will probably be ignored. In this case, see the documentation of your logger, for example, Manual:MonologSpi .
Criação de um arquivo de log de debug
To save errors and debugging information to a log, add $wgDebugLogFile
to the LocalSettings.php
file. Change the value to a text file where you want to save the debug trace output.
The MediaWiki software must have permissions from your operating system to create and write to this file, for example in a default Ubuntu install it runs as user & group www-data
:www-data
.
Here's a sample setting:
/**
* The debug log file must never be publicly accessible because it contains private data.
* But ensure that the directory is writeable by the PHP script running within your Web server.
* The filename is with the database name of the wiki.
*/
$wgDebugLogFile = "/var/log/mediawiki/debug-{$wgDBname}.log";
This file will contain much debug information from MediaWiki core and extensions. Some subsystems write to custom logs, see #Creating a custom log file to capture their output.
Criação de um arquivo de log personalizado
Versão MediaWiki: | ≤ 1.31 |
Prior to MediaWiki 1.32, to create a custom log file that only holds your specific debug statements, use the wfErrorLog()
function.
This function takes two arguments, the text string to log and the path to the log file:
wfErrorLog( "An error occurred.\n", '/var/log/mediawiki/my-custom-debug.log' );
Criação de grupos de log personalizados
If you're debugging several different components, it may be useful to direct certain log groups to write to a separate file. See $wgDebugLogGroups for more information.
To set up custom log groups, use the following to LocalSettings.php:
/**
* The debug log file should not be publicly accessible if it is used, as it
* may contain private data. However, it must be in a directory to which PHP run
* within your web server can write.
*
* Contrary to wgDebugLogFile, it is not necessary to include a wiki-id in these log file names
* if you have multiple wikis. These log entries are prefixed with sufficient information to
* identify the relevant wiki (web server hostname and wiki-id).
*/
// Groups from MediaWiki core
$wgDBerrorLog = '/var/log/mediawiki/dberror.log';
$wgDebugLogGroups = array(
'exception' => '/var/log/mediawiki/exception.log',
'resourceloader' => '/var/log/mediawiki/resourceloader.log',
'ratelimit' => '/var/log/mediawiki/ratelimit.log',
// Extra log groups from your extension
#'myextension' => '/var/log/mediawiki/myextension.log',
#'somegroup' => '/var/log/mediawiki/somegroup.log',
);
To log to one of these groups, call wfDebugLog
like this:
if ( $module->hasFailed ) {
wfDebugLog( 'myextension', "Something is not right, module {$module->name} failed." );
}
/tmp
directory may not generate any log file at all, even if the /tmp directory is supposed to be writable by anyone. This could happen if your system is using one of the systemd features that create a virtual /tmp directory for that process. If that's the case, configure your log file to be written into a different directory, like /var/log/mediawiki
Structured logging
Versão MediaWiki: | ≥ 1.25 |
Structured logging allows you to include fields in your log records. See Structured logging for more information.
JavaScript error logging
Versão MediaWiki: | ≥ 1.36 |
See the documentation of the mediawiki.errorLogger ResourceLoader module.
Statistics
Advanced client-side logging can be performed with Extension:EventLogging , which requires a complex setup and careful inspection of privacy issues.
Simple counting of certain kind of events is possible (since MediaWiki 1.25) using StatsD. StatsD offers meters, gauges, counters, and timing metrics.
Usage example:
$stats = $context->getStats();
$stats->increment( 'resourceloader.cache.hits' );
$stats->timing( 'resourceloader.cache.rtt', $rtt );
The metrics can be sent to a StatsD server, which may be specified via the wgStatsdServer
configuration variable.
(If not set, the metrics are discarded.)
You can work with StatsD locally (without needing a Graphite server) by starting a StatsD server and configuring it with the "backends/console" backend, which will output metrics to the console.
As of MediaWiki 1.25, wfIncrStats()
is a shortcut for the increment()
method on the main RequestContext::getStats()
instance.
Enviar dados de depuração em um comentário HTML na saída
This may occasionally be useful when supporting a non-technical end-user. It's more secure than exposing the debug log file to the web, since the output only contains private data for the current user. But it's not ideal for development use since data is lost on fatal errors and redirects. Use on production sites is not recommended. Debug comments reveal information in page views which could potentially expose security risks.
$wgDebugComments = true;
Trabalhando com objetos do MediaWiki
eval.php é um script interativo para avaliar e interagir com objetos e funções do MediaWiki em um ambiente totalmente inicializado.
$ php maintenance/eval.php > print wfMessage("Recentchanges")->plain(); Recent changes
A máquina virtual portátil $vagrant integra o shell interativo PHP phpsh
.
Callable updates
Code embedded in the DeferredUpdates::addCallableUpdate()
function, such as $rc->save()
in RecentChange.php
, is not executed during the web request, so no error message will be displayed if it fails.
For debugging, it may be helpful to temporarily remove the code from within the function so that it is executed live.
Interactive shell
Client side debugging (JavaScript)
Wikipedia offers a rich set of tools for debugging client side JavaScript. In addition to the MediaWiki tools, other techniques are available to assist with diagnosing client interactions.
Tools:
- Resource Loader offers a means to ensure JavaScript is easily viewable by client-side tools.
- Open your browser's console.
Many client side mediawiki scripts log error messages to the console using ResourceLoader, which provides a safety oriented way to log to the client console. Beyond the native JavaScript logging function, it provides a check to ensure that a console is available and that logging does not produce its own error. ResourceLoader/Architecture#Debug_mode also describes this feature.
- Browser tools may provide native functionality to debug client side script.
- Network tracers, like Wireshark can provide insight into the script that is being provided by a page.
- You can add
?debug=true
to your URL as in https://www.mediawiki.org/wiki/MediaWiki?debug=true to get more detailed information for debugging via your browser's console
Ver também
- Manual:Profiling
- ResourceLoader: ResourceLoader/Developing with ResourceLoader
- Todas as variáveis de configuração relacionadas com depuração/logging: Manual:Configuration settings#Debug/logging
- Função de depuração útil:
[$globalfunc wfDebugDieBacktrace()]
(encerra com uma mensagem opcional e imprime a pilha de chamadas) - Manual:Errors and Symptoms
- All configuration variables related to debugging/logging: Manual:Configuration settings#Debug/logging
- Useful debugging tip:
throw new MWException( 'foo' );
(dies with the given message and prints the callstack)
- Manual:Errors and symptoms
- Categoria:Variáveis de depuração
- wikitech:Debugging in production - Debugging on Wikimedia's production cluster
- Help:Locating broken scripts