Redirecting PHP Errors to Docker Console or Linux Console

Tiempo de lectura: 2 minutos

Today we’re going to learn how to create a handler to redirect PHP errors to the Linux or Docker console.

The first thing we need to do is to create a handler, we can call it exception_handler.php.

And let’s add the following:

<?php

function manejarExcepcion($excepcion)
{
    // Obtener información sobre la excepción
    $mensaje = 'ERR: Se ha producido un error en el sitio web.' . "\n\n";
    $mensaje .= 'ERR: Mensaje de error: ' . $excepcion->getMessage() . "\n";
    $mensaje .= 'ERR: Archivo: ' . $excepcion->getFile() . "\n";
    $mensaje .= 'ERR: Línea: ' . $excepcion->getLine() . "\n";
    $mensaje .= 'ERR: Código de estado HTTP: ' . http_response_code() . "\n";
    

    $fechaActual = date('Y-m-d H:i:s');
    $cadenaError = $fechaActual . " IP: [" . $_SERVER['REMOTE_ADDR'] . "] " .  $mensaje;
    file_put_contents('php://stdout', $cadenaError . "\n");
}

// Establecer la función de manejo de excepciones personalizada
set_exception_handler('manejarExcepcion');

 

This function will give us all the necessary information to identify the error, the error message, the file, the line, and the error code. In addition to the date and the IP from where the call was made.

NOTE: you must put $_SERVER[‘HTTP_X_REAL_IP’] if you use a reverse proxy, instead of $_SERVER[‘REMOTE_ADDR’];

Now we just have to include this file in the files that we want to audit errors by doing an include:

include_once('../extras/exception_handler.php');

Console redirect:

<?php

function logConsola($mensaje)
{
    // Registrar el mensaje en la consola
    error_log($mensaje);
}

// Ejemplo de uso
logConsola("Este es un mensaje informativo.");
logConsola("Este es un mensaje de advertencia.");
logConsola("Este es un mensaje de depuración.");

Leave a Comment