All Projects → samsonasik → ErrorHeroModule

samsonasik / ErrorHeroModule

Licence: MIT license
💎 A Hero for your Zend Framework/Laminas, and Expressive/Mezzio application to log ( DB and Mail ) and handle php errors & exceptions during Mvc process/between request and response

Programming Languages

PHP
23972 projects - #3 most used programming language

Projects that are alternatives of or similar to ErrorHeroModule

petstore
A simple skeleton to build api's based on the chubbyphp-framework, mezzio (former zend-expressive) or slim.
Stars: ✭ 34 (-27.66%)
Mutual labels:  doctrine, zend-expressive, mezzio
zend-di-config
PSR-11 PHP-DI container configurator for Laminas, Mezzio, ZF, Expressive applications or any framework that needs a PSR-11 container
Stars: ✭ 19 (-59.57%)
Mutual labels:  zend-expressive, laminas, mezzio
Kimai2
Kimai v2 is a web-based multiuser time-tracking application. Free for everyone: freelancers, agencies, companies, organizations - all can track their times, generate invoices and more. SaaS version available at https://www.kimai.cloud
Stars: ✭ 1,216 (+2487.23%)
Mutual labels:  twig, doctrine
User Bundle
A new Symfony user bundle
Stars: ✭ 116 (+146.81%)
Mutual labels:  twig, doctrine
laminas-dependency-plugin
Replace zendframework and zfcampus packages with their Laminas Project equivalents.
Stars: ✭ 32 (-31.91%)
Mutual labels:  laminas, mezzio
Fossdroid Core
Fossdroid Core is a web frontend of F-Droid: an alternative software repository comprising only free, open source software for Android. This repo is the open source version of fossdroid.com.
Stars: ✭ 329 (+600%)
Mutual labels:  twig, doctrine
Flextype
Hybrid Content Management System with the freedom of a headless CMS and with the full functionality of a traditional CMS
Stars: ✭ 436 (+827.66%)
Mutual labels:  twig, doctrine
Msgphp
Reusable domain layers. Shipped with industry standard infrastructure.
Stars: ✭ 182 (+287.23%)
Mutual labels:  twig, doctrine
error
Makes handling and debugging PHP errors suck less
Stars: ✭ 17 (-63.83%)
Mutual labels:  error-handler, exception-handler
Core
🧿 Bolt 4 core
Stars: ✭ 243 (+417.02%)
Mutual labels:  twig, doctrine
Core
Zikula Core Framework
Stars: ✭ 213 (+353.19%)
Mutual labels:  twig, doctrine
backtrace-unity
First-class error reporting for the Unity game engine.
Stars: ✭ 99 (+110.64%)
Mutual labels:  error-handler, exception-handler
symfony recipes
Я буду писать здесь рецепты для Symfony на русском
Stars: ✭ 90 (+91.49%)
Mutual labels:  twig, doctrine
MostGenerator
Transformation cartridges for generating Symfony bundles from ModuleStudio models.
Stars: ✭ 21 (-55.32%)
Mutual labels:  twig, doctrine
Idea Php Symfony2 Plugin
IntelliJ IDEA / PhpStorm Symfony Plugin
Stars: ✭ 797 (+1595.74%)
Mutual labels:  twig, doctrine
DoctrineMongoODMModule
Laminas Module for Doctrine MongoDB ODM
Stars: ✭ 83 (+76.6%)
Mutual labels:  doctrine, laminas
Symfony Demo App
A Symfony demo application with basic user management
Stars: ✭ 122 (+159.57%)
Mutual labels:  twig, doctrine
ApigilityConsumer
🍃 Zend Framework/Laminas and Expressive/Mezzio Apigility/Laminas API Tools Client Module to consume API Services
Stars: ✭ 15 (-68.09%)
Mutual labels:  laminas, mezzio
SlmMail
Send mail from Laminas or Mezzio using external mail services.
Stars: ✭ 107 (+127.66%)
Mutual labels:  laminas, mezzio
Grav
Modern, Crazy Fast, Ridiculously Easy and Amazingly Powerful Flat-File CMS powered by PHP, Markdown, Twig, and Symfony
Stars: ✭ 13,067 (+27702.13%)
Mutual labels:  twig, doctrine

ErrorHeroModule

Latest Version ci build Code Coverage PHPStan Downloads

This is README for version ^4.0 which only support Laminas Mvc version 3 and Mezzio version 3 with php ^8.0.

For version ^3.0, you can read at version 3 readme which only support Laminas Mvc version 3 and Mezzio version 3 with php ^7.1.

For version ^2.0, you can read at version 2 readme which only support ZF3 and ZF Expressive version 3 with php ^7.1.

For version 1, you can read at version 1 readme which still support ZF2 and ZF Expressive version 1 and 2 with php ^5.6|^7.0 support.

Introduction

ErrorHeroModule is a module for Error Logging (DB and Mail) your Laminas Mvc 3 Application, and Mezzio 3 for Exceptions in 'dispatch.error' or 'render.error' or during request and response, and PHP E_* Error.

Features

  • Save to DB with Db Writer Adapter.
  • Log Exception (dispatch.error and render.error) and PHP Errors in all events process.
  • Support excludes PHP E_* Error (eg: exclude E_USER_DEPRECATED or specific E_USER_DEPRECATED with specific message) in config settings.
  • Support excludes PHP Exception (eg: Exception class or classes that extends it or specific exception class with specific message) in config settings.
  • Handle only once log error for same error per configured time range.
  • Set default page (web access) or default message (console access) for error if configured 'display_errors' = 0.
  • Set default content when request is XMLHttpRequest via 'ajax' configuration.
  • Set default content when there is no template service via 'no_template' configuration (Mezzio 3).
  • Provide request information ( http method, raw data, body data, query data, files data, cookie data, and ip address).
  • Send Mail
    • many receivers to listed configured email
    • with include $_FILES into attachments on upload error (configurable to be included or not).

Installation

1. Import the following SQL for Mysql

DROP TABLE IF EXISTS `log`;

CREATE TABLE `log` (
  `id` bigint(20) UNSIGNED NOT NULL AUTO_INCREMENT,
  `date` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP,
  `type` int(11) NOT NULL,
  `event` text NOT NULL,
  `url` varchar(2000) NOT NULL,
  `file` varchar(2000) NOT NULL,
  `line` int(11) NOT NULL,
  `error_type` varchar(255) NOT NULL,
  `trace` text NULL,
  `request_data` text NULL,
  PRIMARY KEY (`id`)
) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=latin1;

If you use other RDBMS, you may follow the log table structure above.

2. Setup your Laminas\Db\Adapter\AdapterInterface service or your Doctrine\ORM\EntityManager service config

You can use 'db' (with Laminas\Db) config or 'doctrine' (with DoctrineORMModule) config that will be transformed to be usable with Laminas\Log\Writer\Db.

<?php
// config/autoload/local.php
return [
    'db' => [
        'username' => 'mysqluser',
        'password' => 'mysqlpassword',
        'driver'   => 'pdo_mysql',
        'database' => 'mysqldbname',
        'host'     => 'mysqlhost',
        'driver_options' => [
            \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
        ],
    ],
];

OR

<?php
// config/autoload/local.php
return [
    'doctrine' => [
        'connection' => [
            'orm_default' => [
                'driverClass' => 'Doctrine\DBAL\Driver\PDO\MySql\Driver',
                'params' => [
                    'user'     => 'mysqluser',
                    'password' => 'mysqlpassword',
                    'dbname'   => 'mysqldbname',
                    'host'     => 'mysqlhost',
                    'port'     => '3306',
                    'driverOptions' => [
                        \PDO::MYSQL_ATTR_INIT_COMMAND => 'SET NAMES \'UTF8\'',
                    ],
                ],
            ],
        ],
    ]
];

If you use other RDBMS, you may configure your own db or doctrine config.

3. Require this module uses composer.

composer require samsonasik/error-hero-module

4. Copy config

a. For Laminas Mvc application, copy error-hero-module.local.php.dist config to your local's autoload and configure it

source destination
vendor/samsonasik/error-hero-module/config/error-hero-module.local.php.dist config/autoload/error-hero-module.local.php

Or run copy command:

cp vendor/samsonasik/error-hero-module/config/error-hero-module.local.php.dist config/autoload/error-hero-module.local.php

b. For Mezzio application, copy mezzio-error-hero-module.local.php.dist config to your local's autoload and configure it

source destination
vendor/samsonasik/error-hero-module/config/mezzio-error-hero-module.local.php.dist config/autoload/mezzio-error-hero-module.local.php

Or run copy command:

cp vendor/samsonasik/error-hero-module/config/mezzio-error-hero-module.local.php.dist config/autoload/mezzio-error-hero-module.local.php

When done, you can modify logger service named ErrorHeroModuleLogger and error-hero-module config in your's local config:

<?php
// config/autoload/error-hero-module.local.php or config/autoload/mezzio-error-hero-module.local.php

use Laminas\Db\Adapter\AdapterInterface;

return [

    'log' => [
        'ErrorHeroModuleLogger' => [
            'writers' => [

                [
                    'name' => 'db',
                    'options' => [
                        'db'     => AdapterInterface::class,
                        'table'  => 'log',
                        'column' => [
                            'timestamp' => 'date',
                            'priority'  => 'type',
                            'message'   => 'event',
                            'extra'     => [
                                'url'          => 'url',
                                'file'         => 'file',
                                'line'         => 'line',
                                'error_type'   => 'error_type',
                                'trace'        => 'trace',
                                'request_data' => 'request_data'
                            ],
                        ],
                        'formatter' => [
                            'name' => 'db',
                            'options' => [
                                'dateTimeFormat' => 'Y-m-d H:i:s',
                            ],
                        ],
                    ],
                ],

            ],
        ],
    ],

    'error-hero-module' => [
	// it's for the enable/disable the logger functionality
        'enable' => true,

        // default to true, if set to true, then you can see sample:
        // 1. /error-preview page ( ErrorHeroModule\Controller\ErrorPreviewController )
        // 2. error-preview command (ErrorHeroModule\Controller\ErrorPreviewConsoleController) via
        //       php public/index.php error-preview
        //
        // for Mezzio ^3.0.0, the disable error-preview page is by unregister 'error-preview' from config/routes
        //
        //
        // otherwise(false), you can't see them, eg: on production env.
        'enable-error-preview-page' => true,

        'display-settings' => [

            // excluded php errors ( http://www.php.net/manual/en/errorfunc.constants.php )
            'exclude-php-errors' => [

                // can be specific error
                \E_USER_DEPRECATED,

                // can be specific error with specific message
                [\E_WARNING, 'specific error message'],

            ],

            // excluded exceptions
            'exclude-exceptions' => [

                // can be an Exception class or class extends Exception class
                \App\Exception\MyException::class,

                // can be specific exception with specific message
                [\RuntimeException::class, 'specific exception message'],

                // or specific Error class with specific message
                [\Error::class, 'specific error message'],

            ],

            // show or not error
            'display_errors'  => 0,

            // if enable and display_errors = 0, the page will bring layout and view
            'template' => [
                // non laminas-view (plates, twig) for Mezzio not need a layout definition
                // as layout defined in the view
                'layout' => 'layout/layout',
                'view'   => 'error-hero-module/error-default'
            ],

            // for Mezzio, when container doesn't has \Mezzio\Template\TemplateRendererInterface service
            // if enable, and display_errors = 0, then show a message under no_template config
            'no_template' => [
                'message' => <<<json
{
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Internal Server Error",
    "status": 500,
    "detail": "We have encountered a problem and we can not fulfill your request. An error report has been generated and sent to the support team and someone will attend to this problem urgently. Please try again later. Thank you for your patience."
}
json
            ],

            // if enable and display_errors = 0, the console will bring message for laminas-mvc
            'console' => [
                'message' => 'We have encountered a problem and we can not fulfill your request. An error report has been generated and sent to the support team and someone will attend to this problem urgently. Please try again later. Thank you for your patience.',
            ],
            // if enable, display_errors = 0, and request XMLHttpRequest
            // on this case, the "template" key will be ignored.
            'ajax' => [
                'message' => <<<json
{
    "type": "http://www.w3.org/Protocols/rfc2616/rfc2616-sec10.html",
    "title": "Internal Server Error",
    "status": 500,
    "detail": "We have encountered a problem and we can not fulfill your request. An error report has been generated and sent to the support team and someone will attend to this problem urgently. Please try again later. Thank you for your patience."
}
json
            ],
        ],

        'logging-settings' => [
            // time range for same error, file, line, url, message to be re-logged
	        // in seconds range, 86400 means 1 day
            'same-error-log-time-range' => 86400,
        ],

        'email-notification-settings' => [
            // set to true to activate email notification on log error event
            'enable' => false,

            // Laminas\Mail\Message instance registered at service manager
            'mail-message'   => 'YourMailMessageService',

            // Laminas\Mail\Transport\TransportInterface instance registered at service manager
            'mail-transport' => 'YourMailTransportService',

            // email sender
            'email-from'    => 'Sender Name <[email protected]>',

            // to include or not $_FILES on send mail
            'include-files-to-attachments' => true,

            'email-to-send' => [
                '[email protected]',
                '[email protected]',
            ],
        ],
    ],
    // ...
];

5. Lastly, enable it

a. For Laminas Mvc application

// config/modules.config.php or config/application.config.php
return [
    'Application',
    'ErrorHeroModule', // <-- register here
],

b. For Mezzio application

For laminas-mezzio-skeleton ^3.0.0, you need to open config/pipeline.php and add the ErrorHeroModule\Middleware\Mezzio::class middleware after default ErrorHandler::class registration:

$app->pipe(ErrorHandler::class);
$app->pipe(ErrorHeroModule\Middleware\Mezzio::class); // here

and also add error-preview routes in config/routes.php (optional) :

// for use laminas-router
$app->get('/error-preview[/:action]', ErrorHeroModule\Middleware\Routed\Preview\ErrorPreviewAction::class, 'error-preview');

// for use FastRoute
$app->get('/error-preview[/{action}]', ErrorHeroModule\Middleware\Routed\Preview\ErrorPreviewAction::class, 'error-preview');

to enable error preview page. To disable error preview page, just remove it from routes.

Give it a try!

Web Access

URl Preview For
http://yourlaminasormezzioapp/error-preview Exception
http://yourlaminasormezzioapp/error-preview/error Error
http://yourlaminasormezzioapp/error-preview/warning PHP E_WARNING
http://yourlaminasormezzioapp/error-preview/fatal PHP Fatal Error

You will get the following page if display_errors config is 0:

error preview in web

For production env, you can disable error-preview sample page with set ['error-hero-module']['enable-error-preview-page'] to false.

Console Access

If you use laminas-mvc v3, you need to have laminas/laminas-mvc-console in your vendor, if you don't have, you can install it via command:

composer require laminas/laminas-mvc-console --sort-packages
Command Preview For
php public/index.php error-preview Exception
php public/index.php error-preview error Error
php public/index.php error-preview warning PHP E_WARNING

You will get the following page if display_errors config is 0:

error preview in console

For production env, you can disable error-preview sample page with set ['error-hero-module']['enable-error-preview-page'] to false.

For Mezzio, there is no default console implementation, so, if you want to apply it in your console in Mezzio, you may need to custom implementation error handler that utilize ErrorHeroModule\Handler\Logging service (see detailed usage at ErrorHeroModule\Middleware\Mezzio class)

Contributing

Contributions are very welcome. Please read CONTRIBUTING.md

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].