Laravel Lumen service provider for Understand.io

Overview

The service provider is deprecated - it does not support error grouping.


Laravel Lumen service provider for Understand.io

Build Status Latest Stable Version Latest Unstable Version License HHVM Status Scrutinizer Code Quality

You may also be interested in our Laravel 4, Laravel 5 service provider or Monolog Understand.io handler

Introduction

This packages provides a full abstraction for Understand.io and provides extra features to improve Lumen's default logging capabilities. It is essentially a wrapper around our Understand Monolog handler to take full advantage of Understand.io's data aggregation and analysis capabilities.

Quick start

  1. Add this package to your project via composer:

    composer require understand/understand-lumen
    
  2. In bootstrap/app.php enable Dotenv (around line 5) AND $app->withFacades(); (around line 22):

    Dotenv::load(__DIR__.'/../'); // around line 5
    
    ...
    
    $app->withFacades(); // around line 22
  3. In bootstrap/app.php register the UnderstandLumenServiceProvider:

    $app->register(Understand\UnderstandLumen\UnderstandLumenServiceProvider::class);
  4. Create a new file as config/understand_lumen.php (note that you may need to create the config directory) with the following contents:

    [ 'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId', 'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId', 'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier', 'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl', 'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp', //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp', //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent', //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment', //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod', ], ]; ">
    
    
    return [
    
        /**
         * Specify which handler to use - sync or async.
         *
         * Note that the async handler will only work in systems where
         * the CURL command line tool is installed
         */
        'handler' => env('UNDERSTAND_HANDLER', 'sync'),
    
        /**
         * Your input token from Understand.io
         */
        'token' => env('UNDERSTAND_INPUT_KEY'),
    
        /**
         * Specifies whether logger should throw an exception of issues detected
         */
        'silent' => env('UNDERSTAND_SILENT', true),
    
        /**
         * Specify additional field providers for each log
         * E.g. sha1 version session_id will be appended to each "Log::info('event')"
         */
        'meta' => [
            'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId',
            'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId',
            'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier',
            'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl',
            'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp',
            //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp',
            //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent',
            //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment',
            //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod',
        ],
    ];
  5. Set your input key (from Understand.io) in your .env file as UNDERSTAND_INPUT_KEY

    UNDERSTAND_INPUT_KEY=your-input-key-from-understand
  6. Open app/Exceptions/Handler.php and adjust the report method:

    public function report(Exception $e)
    {
        $encoder = new \UnderstandMonolog\Encoder\ExceptionEncoder();
    
        app('Psr\Log\LoggerInterface')->error($e->getMessage(), $encoder->exceptionToArray($e));
    }
  7. Send your first event

    $app->get('/', function () use ($app) {
    
        Log::info('test log 123');
    
        return $app->welcome();
    });

Additional meta data (field providers)

You may wish to capture additional meta data with each event. For example, it can be very useful to capture the request url with exceptions, or perhaps you want to capture the current user's ID. To do this, you can specify custom field providers via the config.

[ 'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId', 'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId', 'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier', 'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl', 'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp', //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp', //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent', //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment', //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod', ], ">
/**
 * Specify additional field providers for each log
 * E.g. sha1 version session_id will be appended to each "Log::info('event')"
 */
'meta' => [
    'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId',
    'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId',
    'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier',
    'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl',
    'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp',
    //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp',
    //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent',
    //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment',
    //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod',
],

The Understand.io service provider contains a powerful field provider class which provides default providers, and you can create or extend new providers.

dd(Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId());
// output: c624e355b143fc050ac427a0de9b64eaffedd606

Default field providers

The following field providers are included in this package:

  • getSessionId - return sha1 version of session id
  • getUrl - return current url (e.g. /my/path?with=querystring).
  • getRequestMethod - return request method (e.g. POST).
  • getServerIp - return server IP.
  • getClientIp - return client IP.
  • getClientUserAgent - return client's user agent.
  • getEnvironment - return Lumen environment (e.g. production).
  • getProcessIdentifier - return unique token which is unique for every request. This allows you to easily group all events which happen in a single request.
  • getUserId - return current user id. This is only available if you make sure of the default Laravel Lumen auth or the cartalyst/sentry package. Alternatively, if you make use of a different auth package, then you can extend the getUserId field provider and implement your own logic.

How to extend create your own methods or extend the field providers

Understand\UnderstandLumen\UnderstandFieldProviderFacade::extend('getMyCustomValue', function()
{
    return 'my custom value';
});

dd(Understand\UnderstandLumen\UnderstandFieldProviderFacade::getMyCustomValue());

Example

Lets assume that you have defined a custom field provider called getMyCustomValue (as above). You should then add this to your config file as follows:

'meta' => [
    ...
    'custom_value' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getMyCustomValue',
    ...
]

This additional meta data will then be automatically appended to all of your Lumen log events (Log::info('my_custom_event')), and will appear as follows:

{
  "message": "my_custom_event",
  "custom_value":"my custom value"
}

How to send data asynchronously

Async handler

By default each log event will be sent to Understand.io's api server directly after the event happens. If you generate a large number of logs, this could slow your app down and, in these scenarios, we recommend that you make use of a async handler. To do this, change the config parameter handler to async.

/**
 * Specify which handler to use - sync or async.
 *
 * Note that the async handler will only work in systems where
 * the CURL command line tool is installed
 */
'handler' => 'async',

The async handler is supported in most of the systems - the only requirement is that CURL command line tool is installed and functioning correctly. To check whether CURL is available on your system, execute following command in your console:

curl -h

If you see instructions on how to use CURL then your system has the CURL binary installed and you can use the async handler.

Keep in mind that Lumen allows you to specify different configuration values in different environments. You could, for example, use the async handler in production and the sync handler in development.

Configuration

[ 'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId', 'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId', 'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier', 'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl', 'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp', //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp', //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent', //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment', //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod', ], ]; ">
return [

    /**
     * Specify which handler to use - sync or async.
     *
     * Note that the async handler will only work in systems where
     * the CURL command line tool is installed
     */
    'handler' => env('UNDERSTAND_HANDLER', 'sync'),

    /**
     * Your input token from Understand.io
     */
    'token' => env('UNDERSTAND_INPUT_KEY'),

    /**
     * Specifies whether logger should throw an exception of issues detected
     */
    'silent' => env('UNDERSTAND_SILENT', true),

    /**
     * Specify additional field providers for each log
     * E.g. sha1 version session_id will be appended to each "Log::info('event')"
     */
    'meta' => [
        'user_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUserId',
        'session_id'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getSessionId',
        'request_id' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getProcessIdentifier',
        'url'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getUrl',
        'client_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientIp',
        //'server_ip'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getServerIp',
        //'user_agent' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getClientUserAgent',
        //'environment' => 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getEnvironment',
        //'request_method'=> 'Understand\UnderstandLumen\UnderstandFieldProviderFacade::getRequestMethod',
    ],
];

Requirements

UTF-8

This package uses the json_encode function, which only supports UTF-8 data, and you should therefore ensure that all of your data is correctly encoded. In the event that your log data contains non UTF-8 strings, then the json_encode function will not be able to serialize the data.

http://php.net/manual/en/function.json-encode.php

License

The Laravel Lumen Understand.io service provider is open-sourced software licensed under the MIT license

You might also like...
A Laravel and Lumen Badges Generator

Laravel and Lumen Badge Generator That package is a easy wrapper to Badges/Poser. #Installing composer require vluzrmos/laravel-badge-poser Laravel co

 Provides a Eloquent query builder for Laravel or Lumen
Provides a Eloquent query builder for Laravel or Lumen

This package provides an advanced filter for Laravel or Lumen model based on incoming requets.

Laravel and Lumen Auto Hard Deleter
Laravel and Lumen Auto Hard Deleter

Laravel Auto Hard Deleter This package deletes soft deleted rows automatically after a time interval that you define. For Laravel and Lumen 6, 7, 8 In

🔐 JSON Web Token Authentication for Laravel & Lumen
🔐 JSON Web Token Authentication for Laravel & Lumen

Documentation Documentation for 1.* here For version 0.5.* See the WIKI for documentation. Supported by Auth0 If you want to easily add secure authent

Cascade delete and restore when using the Laravel or Lumen SoftDeletes feature.
Cascade delete and restore when using the Laravel or Lumen SoftDeletes feature.

Cascade delete and restore when using the Laravel or Lumen SoftDeletes feature.

Simple Video is a automated H264 encryption system built on Lumen Laravel Framework

Simple Video is a automated H264 encryption system built on Lumen Laravel Framework

Enable/disable query logger in Laravel/Lumen

Enable/disable query logger in Laravel/Lumen

Teste dos mano do pay lá ft. Lumen Framework

Teste dos caras lá pay Avisos antes de começar Crie um repositório no seu GitHub sem citar nada relacionado a empresa dos cara lá. (CHECK) Faça seus c

Stripe integration in Lumen

Lumen Boilerplate/Starter App for Stripe payment processing Core Features return all available subscription plans create a subscription check subscrip

Releases(v1.0.1)
Owner
null
A simple Laravel service provider for easily using HTMLPurifier inside Laravel

HTMLPurifier for Laravel 5/6/7/8 A simple Laravel service provider for easily using HTMLPurifier inside Laravel. From their website: HTML Purifier is

MeWebStudio - Muharrem ERİN 1.7k Jan 6, 2023
A package to keep track of your pages & understand your audience

A clean way to track your pages & understand your user's behavior Installation You can install the package via composer: composer require coderflexx/l

Coderflex 178 Jan 4, 2023
Mollie API client wrapper for Laravel & Mollie Connect provider for Laravel Socialite

Mollie for Laravel Laravel-Mollie incorporates the Mollie API and Mollie Connect into your Laravel or Lumen project. Accepting iDEAL, Apple Pay, Banco

Mollie 289 Nov 24, 2022
Driver for managing cash payments in the Cashier Provider ecosystem

Cash Driver Provider Installation To get the latest version of Cash Driver Provider, simply require the project using Composer: $ composer require cas

Cashier Provider 4 Aug 30, 2022
UnifiedPush provider for Nextcloud - server application

NextPush - Server App UnifiedPush provider for Nextcloud - server application This is still a WIP version Requirement It require the nextcloud server

NextPush 38 Jan 5, 2023
Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud Messaging (FCM).

Laravel-FCM Introduction Laravel-FCM is an easy to use package working with both Laravel and Lumen for sending push notification with Firebase Cloud M

Rahul Thapa 2 Oct 16, 2022
Laravel Responder - a package for building API responses, integrating Fractal into Laravel and Lumen

A Laravel Fractal package for building API responses, giving you the power of Fractal with Laravel's elegancy.

Alexander Tømmerås 776 Dec 25, 2022
📦 Adds Laravel Packages Support to Lumen and Vendor Publish Artisan Command.

Laravel Package Support for Lumen: Makes Lumen compatible with Laravel Packages. You can use any Laravel Packages in Lumen by installing Larasupport Package.

Irfaq Syed 127 Dec 17, 2022
A collection of generators for Lumen and Laravel 5.

Lumen generators A collection of generators for Lumen and Laravel 5. Contents Why ? Installation Quick Usage Detailed Usage Model Generator Migration

Amine Ben hammou 349 Mar 24, 2022
CORS (Cross-Origin Resource Sharing) support for Laravel and Lumen

Description This package adds Cross-Origin Resource Sharing (CORS) support to your Laravel application. The package is based on Framework agnostic (PS

null 48 Feb 1, 2020