Magento - Attach log correlation ID (aka Trace ID) to requests, monlog entries, and New relic transactions

Overview

magento2-log-correlation-id

Build Status

Magento 2 log correlation id for PHP requests/processes and magento logs.

This is useful when debugging issues on a production site as high amounts of traffic can cause many logs to be written and identifying which logs belong to a specific failing request can sometimes be difficult.

With this you should easily be able to find all associated logs for a given web request or CLI process.

  • From a web request you can look at the X-Log-Correlation-Id header then search all your magento log files for the logs corresponding to only that request.
  • You can also find the log correlation identifier attached to New Relic transactions.

Install

Composer install the module.

composer require ampersand/magento2-log-correlation-id

Add the additional dependency injection config necessary to boot early in the application flow

mkdir app/etc/ampersand_magento2_log_correlation
cp vendor/ampersand/magento2-log-correlation-id/dev/ampersand_magento2_log_correlation/di.xml app/etc/ampersand_magento2_log_correlation/

Run module installation

php bin/magento setup:upgrade

Uninstall

rm app/etc/ampersand_magento2_log_correlation/di.xml
php bin/magento module:disable Ampersand_LogCorrelationId

How it works

Entry point

This module creates a new cache decorator (src/CacheDecorator/CorrelationIdDecorator.php).

It needs to be here so that it's constructed immediately after Magento\Framework\Cache\Frontend\Decorator\Logger which is the class responsible for instantiating Magento\Framework\App\Request\Http and the Logger triggered after.

This is the earliest point in the magento stack where we can get any existing traceId from a request header (for example cf-request-id) and have it attached to any logs produced.

This cache decorator initialises the identifier which is immutable for the remainder of the request.

Exit points

  • The correlation ID is attached to web responses as X-Log-Correlation-Id in src/HttpResponse/HeaderProvider/LogCorrelationIdHeader.php
    • REST API requests work a bit differently in Magento and attach the header using src/Plugin/AddToWebApiResponse.php
  • Monolog files have the correlation ID added into their context section under the key amp_correlation_id via src/Processor/MonologCorrelationId.php
  • New Relic has this added as a custom parameter under the key amp_correlation_id

Example usage

Firstly you need to expose the header in your logs, this is an example for apache logs

Header always note X-Log-Correlation-Id amp_correlation_id
LogFormat "%t %U %{amp_correlation_id}n" examplelogformat
CustomLog "/path/to/var/log/httpd/access_log" examplelogformat

The above configuration would give log output like the following when viewing a page

[13/Jan/2021:11:34:37 +0000] /some-cms-page/ cid-61e04d741bf78

You could then search for all magento logs pertaining to that request

$ grep -ri 61e04d741bf78 ./var/log
./var/log/system.log:[2022-01-13 16:04:14] main.INFO: some_log_entry_61e04d7e2ed03 {"amp_correlation_id":"cid-61e04d741bf78","some":"context"} []

If the request was long-running, or had an error it may also be flagged in new relic with the custom parameter amp_correlation_id

Configuration and Customisation

Change the key name from amp_correlation_id

You can change the monolog/new relic key from amp_correlation_id using app/etc/ampersand_magento2_log_correlation/di.xml

<type name="Ampersand\LogCorrelationId\Service\CorrelationIdentifier">
    <arguments>
        <argument name="identifierKey" xsi:type="string">your_key_name_here</argument>
    </arguments>
</type>

Use existing correlation id from request header

If you want to use an upstream correlation/trace ID you can define one app/etc/ampersand_magento2_log_correlation/di.xml

<type name="Ampersand\LogCorrelationId\Service\CorrelationIdentifier">
    <arguments>
        <argument name="headerInput" xsi:type="string">X-Your-Header-Here</argument>
    </arguments>
</type>

If this is present on the request magento will use that value for X-Log-Correlation-Id, the monolog context, and the New Relic parameter. Otherwise magento will generate one.

For example

$ 2>&1 curl  -H 'X-Your-Header-Here: abc123' https://your-magento-site.example.com/ -vvv | grep "X-Log-Correlation-Id"
< X-Log-Correlation-Id: abc123
$ 2>&1 curl https://your-magento-site.example.com/ -vvv | grep "X-Log-Correlation-Id"
< X-Log-Correlation-Id: cid-61e4194d1bea5

Custom Loggers

By default this module hooks into all vanilla magento loggers.

However third party modules may define additional loggers to write to custom files. If you want the correlation ID added to those logs as well you will need to create a module that depends on both Ampersand_LogCorrelation_Id and the module with the custom logger, you will then have to add the log handler in di.xml like so

<type name="This\Is\Some\Logger">
    <arguments>
        <argument name="processors" xsi:type="array">
            <item name="correlationIdProcessor" xsi:type="array">
                <item name="0" xsi:type="object">Ampersand\LogCorrelationId\Processor\MonologCorrelationId</item>
                <item name="1" xsi:type="string">addCorrelationId</item>
            </item>
        </argument>
    </arguments>
</type>

This module provides a command to try to help you keep track of the custom loggers in your system

$ php bin/magento ampersand:log-correlation-id:list-custom-loggers
Scanning for classes which extend Monolog\Logger
- You need to run 'composer dump-autoload --optimize' for this command to work
- Use this on your local environment to configure your di.xml
- See vendor/ampersand/magento2-log-correlation-id/README.md
--------------------------------------------------------------------------------
Dotdigitalgroup\Email\Logger\Logger
StripeIntegration\Payments\Logger\WebhooksLogger
Yotpo\Yotpo\Model\Logger
--------------------------------------------------------------------------------
DONE
Comments
  • Register shutdown function to set header

    Register shutdown function to set header

    This was added to catch "Allowed memory size of X bytes exhausted" type errors

    This is how the webapi requests handle errors and headers

    https://github.com/magento/magento2/blob/7c6b6365a3c099509d6f6e6c306cb1821910aab0/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php#L287-L291

    https://github.com/magento/magento2/blob/7c6b6365a3c099509d6f6e6c306cb1821910aab0/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php#L298-L308

    https://github.com/magento/magento2/blob/7c6b6365a3c099509d6f6e6c306cb1821910aab0/lib/internal/Magento/Framework/Webapi/ErrorProcessor.php#L221-L237

    So a similar approach can be used here to insert the header

    Closes #13

    opened by convenient 0
  • Add to database logs and earlier framework instantiation

    Add to database logs and earlier framework instantiation

    1. Added a plugin to add the correlation identifier to all database logs
    2. Moved the Magento\Framework\Logger\Monolog processor into the app/etc/*/di.xml file so that it is configured while the main di is loaded, rather than when the modules are loaded.
    3. Test di:compile
    opened by convenient 0
  • Add definition for new logger

    Add definition for new logger

    $ if [[ $TEST_GROUP = magento_latest ]]; then php bin/magento ampersand:log-correlation-id:list-custom-loggers --filter "Yotpo\Yotpo\Model\Logger" --filter "Klarna\Core\Logger\Logger" --filter "Dotdigitalgroup\Email\Logger\Logger" --filter "Amazon\Core\Logger\Logger" --filter "Amazon\Core\Logger\IpnLogger"; fi
    --------------------------------------------------------------------------------
    Scanning for classes which extend Monolog\Logger
    --------------------------------------------------------------------------------
    - You need to run 'composer dump-autoload --optimize' for this command to work
    - Use this on your local environment to configure your di.xml
    - See vendor/ampersand/magento2-log-correlation-id/README.md
    --------------------------------------------------------------------------------
    Magento\AdminAdobeIms\Logger\AdminAdobeImsLogger
    --------------------------------------------------------------------------------
    DONE
    The command "if [[ $TEST_GROUP = magento_latest ]]; then php bin/magento ampersand:log-correlation-id:list-custom-loggers --filter "Yotpo\Yotpo\Model\Logger" --filter "Klarna\Core\Logger\Logger" --filter "Dotdigitalgroup\Email\Logger\Logger" --filter "Amazon\Core\Logger\Logger" --filter "Amazon\Core\Logger\IpnLogger"; fi" exited with 1.
    
    

    https://app.travis-ci.com/github/AmpersandHQ/magento2-log-correlation-id/jobs/580861819

    opened by convenient 0
  • Update composer.json

    Update composer.json

    In PluginManager.php line 762:
                                                                                   
      magento/composer-dependency-version-audit-plugin contains a Composer plugin  
       which is blocked by your allow-plugins config. You may add it to the list   
      if you consider it safe.                                                     
      You can run "composer config --no-plugins allow-plugins.magento/composer-de  
      pendency-version-audit-plugin [true|false]" to enable it (true) or disable   
      it explicitly and suppress this exception (false)                            
      See https://getcomposer.org/allow-plugins                                    
                                                                                   
    install [--prefer-source] [--prefer-dist] [--prefer-install PREFER-INSTALL] [--dry-run] [--dev] [--no-suggest] [--no-dev] [--no-autoloader] [--no-progress] [--no-install] [-v|vv|vvv|--verbose] [-o|--optimize-autoloader] [-a|--classmap-authoritative] [--apcu-autoloader] [--apcu-autoloader-prefix APCU-AUTOLOADER-PREFIX] [--ignore-platform-req IGNORE-PLATFORM-REQ] [--ignore-platform-reqs] [--] [<packages>...]
    The command "composer install --no-interaction" failed and exited with 1 during .
    
    
    opened by convenient 0
  • Define third party loggers

    Define third party loggers

    There are loggers bundled in the magento core other than the vanilla framework logger.

    This PR

    • adds definitions for the ones bundled in the core so that we have the correlation ID on all of them
      • If the module is not present or is disabled the di.xml values seem ignored
    • adds a CLI script to analyse your installed modules and find any that extend the monolog logger, report this as output.
      • Update README.md explaining how to use it
      • Added extra capability to use travis as a way of keeping up to date with new loggers as they're bundled into the magento core, travis for this module will now fail if a new one is added
    opened by convenient 0
  • Earlier instantiation of correlation ID

    Earlier instantiation of correlation ID

    • Instantiate the correlation ID logic as soon as possible after magento instantiates the logger and the request object.
    • Update docs
    • Add incoming correlation ID header, so that we could for example have a header come from aws or cloudflare and use that identifier in our magento logs
    opened by convenient 0
  • Handle cron transactions

    Handle cron transactions

    Crons have multiple transactions (when fixed)

    https://github.com/magento/magento2/issues/34108

    This module only attaches it to the first transaction

    Probably worthwhile adding a plugin that watches setTransactionName and ensuring we're setting the parameter, or more likely startTransaction

    help wanted 
    opened by convenient 0
  • Fatal `SOAP-ERROR` missing correlation ID

    Fatal `SOAP-ERROR` missing correlation ID

    PHP Fatal error:  SOAP-ERROR: Encoding: Violation of encoding rules
    

    Need to figure out how to reproduce this and ensure the correlation ID is attached

    opened by convenient 0
  • ci: add unit, install and integration test workflows

    ci: add unit, install and integration test workflows

    opened by damienwebdev 2
Releases(v1.3.1)
  • v1.3.1(Oct 24, 2022)

    What's Changed

    • Register shutdown function to set header by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/15

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.3.0...v1.3.1

    Source code(tar.gz)
    Source code(zip)
  • v1.3.0(Oct 18, 2022)

    What's Changed

    • Update prepare_phpunit_config.php by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/12
    • Add to database logs and earlier framework instantiation by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/14

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.5...v1.3.0

    Source code(tar.gz)
    Source code(zip)
  • v1.2.5(Sep 1, 2022)

    What's Changed

    • Fix code style by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/11

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.4...v1.2.5

    Source code(tar.gz)
    Source code(zip)
  • v1.2.4(Sep 1, 2022)

    What's Changed

    • Update composer.json by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/8
    • Add definition for new logger by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/10

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.3...v1.2.4

    Source code(tar.gz)
    Source code(zip)
  • v1.2.3(Apr 22, 2022)

    What's Changed

    • Update .travis.yml by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/5
    • Fix travis compat php 8.1 and magento 2.4.4 by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/6

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.2...v1.2.3

    Source code(tar.gz)
    Source code(zip)
  • v1.2.2(Jan 31, 2022)

    What's Changed

    • Update ListCustomLoggersCommand.php by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/4

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.1...v1.2.2

    Source code(tar.gz)
    Source code(zip)
  • v1.2.1(Jan 27, 2022)

    What's Changed

    • Improve ListCustomLoggersCommand debug output by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/3

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.2.0...v1.2.1

    Source code(tar.gz)
    Source code(zip)
  • v1.2.0(Jan 27, 2022)

    What's Changed

    • Define third party loggers by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/2

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.1.1...v1.2.0

    Source code(tar.gz)
    Source code(zip)
  • v1.1.1(Jan 20, 2022)

    • Fix composer php version dependency >=7.3

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.1.0...v1.1.1

    Source code(tar.gz)
    Source code(zip)
  • v1.1.0(Jan 17, 2022)

    What's Changed

    • Earlier instantiation of correlation ID by @convenient in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/1

    New Contributors

    • @convenient made their first contribution in https://github.com/AmpersandHQ/magento2-log-correlation-id/pull/1

    Full Changelog: https://github.com/AmpersandHQ/magento2-log-correlation-id/compare/v1.0.1...v1.1.0

    Source code(tar.gz)
    Source code(zip)
  • v1.0.1(Jan 13, 2022)

  • v1.0.0(Jan 13, 2022)

Owner
Ampersand
We architect & deliver retail technology solutions that create better customer experiences and positive operational change.
Ampersand
A PHP implementation of the Unleash protocol aka Feature Flags in GitLab.

A PHP implementation of the Unleash protocol aka Feature Flags in GitLab. This implementation conforms to the official Unleash standards and implement

Dominik Chrástecký 2 Aug 18, 2021
This car rental project system project in PHP focuses mainly on dealing with customers regarding their car rental hours and certain transactions.

Car-Rental Online Car Rental Management System This car rental project system project in PHP focuses mainly on dealing with customers regarding their

Adarsh Kumar Singh 2 Sep 29, 2022
Sends log messages to the Logentries log management service

Phalcon Logentries Phalcon library to connect and make log entries using Logentries. You can adapt it to your own needs or improve it if you want. Ple

Phalcon Orphanage 10 Apr 15, 2019
Yab copy to new - A Textpattern plugin. Copies the current article content to a new one.

yab_copy_to_new Displays a new button in article write tab to copy the current article to a new one. Version: 0.2 Table of contents Plugin requirement

Tommy Schmucker 2 Dec 15, 2017
Magento extension which makes it impossible for a customer to log in until the account has been activated by the administrator.

This Magento 1 extension is orphaned, unsupported and no longer maintained. If you use it, you are effectively adopting the code for your own project.

Vinai Kopp 120 Oct 10, 2022
Magento 2 module to log to Sentry

Magento 2 Sentry Logger This Magento 2 module integrates the Sentry sdk into magento 2. Depending on the log level configured in the backend of magent

JustBetter 134 Dec 19, 2022
A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2

Simple Import / Export tool A tool that allows to quickly export data from Magento 1 and Magento 2 store and import it back into Magento 2. Table data

EcomDev B.V. 51 Dec 5, 2022
Quickly and easily preview and test your Magento 2 order confirmation page, without hacks or spending time placing new order each time

Preview Order Confirmation Page for Magento 2 For Magento 2.0.x, 2.1.x, 2.2.x and 2.3.x Styling and testing Magento's order confirmation page can be a

MagePal :: Magento Extensions 71 Aug 12, 2022
New Ultimate Module Creator for Magento 1.7 +

Ultimate Module Creator 1.9.6.0 Notice Because of lack of time, motivation and because Magento2 is already a mature platform, I'm deciding to pull the

Marius Strajeru 247 Nov 22, 2022
Issue tracking application extending GitHub's issues and pull requests for the Joomla! project.

Requirements The issue tracker application requires a server running: PHP 7.2 or 7.3 PHP's ext/curl and ext/intl should also be installed MySQL 5.5.3

Joomla! 68 Oct 27, 2022
It allows frontend developer to send ajax requests and return a custom information from the server without a php developer help

[Magento 1 Extension] It allows frontend developer to send ajax requests and return a custom information from the server without a php developer help (without any php code).

Vladimir Fishchenko 62 Apr 1, 2022
Issue trackers, feature requests, and translation for all of my NamelessMC products

NamelessMC Products In this repository you can find current issues for each of my NamelessMC products, progress on solving them, feature requests, and

Coldfire 1 Mar 25, 2022
⚓️ Easily test HTTP webhooks with this handy tool that displays requests instantly.

Webhook.site With Webhook.site, you instantly get a unique, random URL that you can use to test and debug Webhooks and HTTP requests, as well as to cr

Webhook.site 3.7k Jan 9, 2023
Easily build Eloquent queries from API requests

Build Eloquent queries from API requests This package allows you to filter, sort and include eloquent relations based on a request. The QueryBuilder u

Spatie 3.5k Jan 7, 2023
An alternative to run cron jobs that uses simple HTTP requests

SilverStripe Simple Jobs An alternative to run cron jobs that uses simple HTTP requests. This module require SilverStripe CronTask. Why? Configuring c

Thomas Portelange 1 Jul 4, 2022
A simple package for idempotent requests in Laravel.

?? Replay A simple package for handling idempotent requests in Laravel. Any routes using the Replay middleware will check for whether an incoming requ

Kieran Marshall 2 Dec 9, 2022