Manual:Cómo depurar

From mediawiki.org
This page is a translated version of the page Manual:How to debug and the translation is 36% complete.
Outdated translations are marked like this.

Aquí te damos una introducción básica sobre depurar el software MediaWiki

Una de las primeras cosas que encontrarás es que las instrucciones echo por lo general no funcionarán. Esto es parte del diseño general.

Existen algunas variables de configuración que ayudan a depurar errores. Las siguientes tienen valor false de forma predeterminada. Actívalas estableciendo su valor a true en $localsettings: Enable them by setting them to true in your LocalSettings.php :

  • $wgShowExceptionDetails Activa más detalles (como la pila de llamadas) que se mostrarán en la página de "Error fatal".
  • $wgDebugToolbar Muestra una barra de herramientas en la página con datos de perfilado, registro de mensajes y más.
  • $wgShowDebug Agrega la parte de "log messages" de wgDebugToolbar como una lista en crudo en la página.
  • $wgDevelopmentWarnings MediaWiki lanzará avisos sobre algunas posibles condiciones de error y de funciones obsoletas.

Example line to be added in your LocalSettings.php :

$wgShowExceptionDetails = true;

Errores PHP

Para mostrar errores PHP, añade esto en la segunda línea desde el inicio (justo después de <?php) de LocalSettings.php :

error_reporting( -1 );
ini_set( 'display_errors', 1 );

O configúralo en php.ini :

error_reporting = E_ALL
display_errors = On

O configura en .htaccess:

php_value error_reporting -1
php_flag display_errors On

Esto causará que los errores de PHP se muestren directamente en la página. Esto podría facilitar a un atacante el encontrar alguna manera de comprometer tu servidor, así que desactívalo en cuanto hayas encontrado el problema.

Ten en cuenta que los errores fatales pueden suceder antes de que las líneas de código anteriores se hayan podido ejecutar, o prevengan que estos se muestren. Los errores fatales de PHP normalmente quedan registrados en el registro de errores de Apache. Revisa la configuración [$errorlog error_log] en php.ini (o consúltalo en [$phpinfo phpinfo()]). Fatal PHP errors are usually logged to Apache's error log – check the error_log setting in php.ini (or use phpinfo()).

Activar display_startup_errors

Algunos proveedores establecen display_startup_errors en off, causando que los errores queden ocultos incluso si aumentas el nivel de error_reporting. Activar esta configuración durante la ejecución del programa es demasiado tarde. En su lugar, debes crear un contenedor sobre tu archivo. En el caso de MediaWiki, bastará con añadir lo siguiente al inicio de mediawiki/index.php: 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 );

En otros entornos:

--- myTestFile.php
    error_reporting( -1 );
    ini_set( 'display_startup_errors', 1 );
    ini_set( 'display_errors', 1 );
    require 'your_file.php';

Errores SQL

Para registrar todas las sentencias SQL, en lugar de la que generó la excepción, establece $dumpsql en LocalSettings.php:

$wgDebugDumpSql = true;
Versiones de MediaWiki:
1.16 – 1.31

En versiones anteriores a MediaWiki 1.32, es necesario establecer $wgShowSQLErrors y $wgShowDBErrorBacktrace para ver detalles de las excepciones SQL en la salida HTML:

$wgShowSQLErrors = true;
$wgShowDBErrorBacktrace = true;

Depuración profunda

Depurador

You can debug your code step-by-step with XDebug . For some common setups, see:

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.

Registros

Para un mayor detalle, necesitas perfilar y registrar los errores.

Las instrucciones a continuación solo son válidas para la configuración predeterminada. If you change $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 .

Configurar un registro de depuración

Para guardar errores e información de depuración en un archivo, agrega $wgDebugLogFile al archivo LocalSettings.php. Establece su valor a la ruta de un archivo de texto donde quieras guardar la salida del registro de errores.

El software de MediaWiki debe tener el permiso del sistema operativo para crear y escribir a este fichero. Por ejemplo, en una instalación estándar de Ubuntu, se ejecutará con el usuario y grupo www-data:www-data. Este sería un ejemplo de configuración: 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";

Este archivo contendrá gran cantidad de información de depuración del núcleo de MediaWiki y sus extensiones. Algunos subsistemas escriben en registros especializados, consulta #Creating a custom log file para capturar su salida. Some subsystems write to custom logs, see #Creating a custom log file to capture their output.


Advertencia Advertencia: El registro de depuración puede contener información privada y sensible como credenciales de inicio de sesión, cookies de sesión, y los valores de los formularios enviados. Si esta información resulta accesible públicamente, un atacante puede acceder y comprometer tu máquina y tu cuenta de usuario. Si necesitas compartir el registro de depuración con alguien para diagnosticar un problema, accede al wiki sin haber iniciado sesión, y elimina del registro de depuración las líneas COOKIE, y no captures ningún intento de inicio de sesión.

Crear un registro de depuración personalizado

Versión de MediaWiki:
1.31

Para crear un registro de depuración personalizado que solo contenga sentencias de depuración específicas, usa la función wfErrorLog() (el uso de wfErrorLog está obsoleto en MediaWiki 1.25). Esta función toma dos argumentos: la cadena de texto a escribir, y la ruta al archivo de registro. 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' );

Creating custom log groups

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." );
}
If you have carefully followed the instructions above but nothing gets written to your logging file(s), and if your system is using SELinux, have a look at the logging section on the SELinux page to get around this SELinux context issue.
Escribir archivos de registro en el directorio /tmp podría no generar ningún archivo, incluso si aparentemente cualquiera puede escribir en el directorio /tmp. Esto puede suceder si tu sistema usa una de las funcionalidades de systemd, que crea un directorio /tmp virtual para cada proceso. Si este es tu caso, configura la ruta del archivo de registro para que esté en otro directorio, como por ejemplo /var/log/mediawiki.

Registro estructurado

Versión de MediaWiki:
1.25

Structured logging allows you to include fields in your log records. Véase Structured logging para más información.

You will need to configure a better logger to collect the extra fields, for example Monolog.

JavaScript error logging

Versión de MediaWiki:
1.36

See the documentation of the mediawiki.errorLogger ResourceLoader module.

Estadísticas

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.

Ejemplo de uso:

$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.

Send debug data to an HTML comment in the output

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;

Working live with MediaWiki objects

eval.php is an interactive script to evaluate and interact with MediaWiki objects and functions in a fully initialized environment.

 $ php maintenance/eval.php
 > print wfMessage("Recentchanges")->plain();
 Recent changes

The MediaWiki-Vagrant portable virtual machine integrates the interactive PHP shell phpsh (when using Zend).

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

You can use shell.php as a PHP REPL with full access to MediaWiki internals.

Depuración del lado del cliente (JavaScript)

Wikipedia ofrece una amplia gama de herramientas para depurar desde el lado del cliente con JavaScript. Además de las herramientas de MediaWiki, hay otras técnicas disponibles para asistir con el diagnóstico de interacciones del cliente.

Herramientas:

  • 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.

Véase también

  • Useful debugging tip: throw new MWException( 'foo' ); (dies with the given message and prints the callstack)