Logging user/customer actions in Magento

Featured Image

Recently I wrote a Magento extension called ActionLogger, inspired (thematically) by the “Logging of Administrator Actions” feature available in Magento Enterprise. ActionLogger is pretty simple extension, working on pretty simple but powerful concept of Magento controllers predispatch action.

All you need to do is to create event observer/observers for “controller_action_predispatch” event. This event is fired on every controller action call.

For example, if your store is located on url http://magento-1501.net url, and you go to url like http://magento-1501.net/electronics/cell-phones this will call action “view” from controller “category” from module “Mage_Catalog“. Simple logic/tracing would point this to be app\code\core\Mage\Catalog\controllers\CategoryController.php file and its viewAction().

Adding an event observer like the one shown below will trigger your code upon calling such url.

<frontend>
	<events>
		<controller_action_predispatch>
			<observers>
				<activecodeline_actionlogger_controller_action_predispatch>
					<class>activecodeline_actionlogger/observer</class>
					<method>hookToFrontendControllerActionPredispatch</method>
				</activecodeline_actionlogger_controller_action_predispatch>
			</observers>
		</controller_action_predispatch>
	</events>
</frontend>

Same goes for the admin section, for example if you open a link like http://magento-1501.net/index.php/admin/sales_order/index/key/9c13e78eecdc3d5805f6426be9f56254/. This one would call action “index” from controller “sales_order” from module “Mage_Adminhtml“. Simple logic/tracing would point this to be app\code\core\Mage\Adminhtml\controllers\Sales\OrderController.php file and its indexAction().

Adding an event observer like the one shown below will trigger your code upon calling such url.

<adminhtml>
	<events>
		<controller_action_predispatch>
			<observers>
				<activecodeline_actionlogger_controller_action_predispatch>
					<class>activecodeline_actionlogger/observer</class>
					<method>hookToAdminhtmlControllerActionPredispatch</method>
				</activecodeline_actionlogger_controller_action_predispatch>
			</observers>
		</controller_action_predispatch>
	</events>
</adminhtml>

All this is fine & etc., but what’s the point? We already know this, you might say.

The point is, the concept is very simple but enables you to add powerful logging mechanism on top of it. All you need to do is to add few lines of code that would record given action, controller, current user/customer, possibly entire parameters passed to controller, etc.

Then you can store it either in database or in some file.

For example, in ActionLogger extension I created a special models, called Admin and Frontend that handle writing logged values to database from observer.

public function hookToFrontendControllerActionPredispatch($observer = null)
{
	if (!Mage::helper('activecodeline_actionlogger')->_canLogFrontendActions()) {
		return;
	}
	$log = Mage::getModel('activecodeline_actionlogger/frontend');
	$log->setActionName(Mage::app()->getRequest()->getActionName());
	$log->setControllerName(Mage::app()->getRequest()->getControllerName());
	if (Mage::helper('activecodeline_actionlogger')->_canLogRequestParams()) {
		if($params = Mage::app()->getRequest()->getParams()) {
			$log->setParams(Mage::helper('core')->encrypt(serialize($params)));
		}
	}
	$log->setClientIp(Mage::app()->getRequest()->getClientIp());
	$log->setControllerModule(Mage::app()->getRequest()->getControllerModule());
	if ($customer = Mage::getSingleton('customer/session')->getCustomer()) {
		$log->setCustomerId($customer->getId());
	} else {
		$log->setCustomerId(0);
	}
	try {
		$log->save();
	} catch (Exception $e) {
		Mage::log('file: '.__FILE__.', line: '.__LINE__, 'msg: '.$e->getMessage());
	}
}

On top of that you can create a nice grid in Magento for listing these. Combine this with built in Magento roles, and you can have your grid shown only to certain role.

Concept like this can be used for development/debugging purposes and possibly for some user/customer behaviour profiling. Although “profiling” can mostly be done via Google Analytics these days, there are still admin part of sites that are not suppose to get analyzed by Google.

Thinking further down the road, one can build truly dynamic user specific menus based on the logged data statistics, etc.

Hope I got you thinking.

P.S. Unlike my usual way of packing up the code into the zip archive, this time I decided to actually submit extension to Magento connect. This was done yesterday and is waiting to be approved :) . Once approved, I’ll post a link to extension for those who are interested. Extension is now live at Magento Connect here.

Cheers.

20
Top

Enjoyed this post?

Subscribe to our RSS Feed, Follow us on Twitter and spread it to your friends!

Author

CTO / Magento Certified Developer Plus @inchoo. Father, husband!

Other posts from this author

Discussion 20 Comments

Add Comment
  1. Thank you for the excellent post. I’d definitely be interested in this.

  2. Hey Branko, Nice tip – you could combine it with this guide to auditing changes in models, to audit all changed records by a particular user:

    http://magebase.com/magento-tutorials/using-a-backend-model-to-customize-magento-a-tip-from-magento-developers-paradise/

    I’m sure there would be some industries where that level of audit is required/useful.

  3. Anatoly A. Kazantsev

    Hello, I see white coloured code on gray background. Very uncomfortable to read.

  4. Appydiff

    Hi & thank you for this extension.
    I have a problem in admin when i want to see the frontend or admin grid i go to 404 page not found.
    I have a custom admin url.
    Any idea ? Thank in advance

  5. cr3pt

    Maybe you can prepare version for 1.4.2?
    regards
    cr3pt

  6. I have been thinking about this for a while, like your work. It’s worth saying, this adds a few ‘script calls’ to a page so is likely to affect performance if left on on a busy site.

    I was also looking to add a dump of $_SESSION and $_COOKIE to help with debugging customers issues. Though Mage makes good use of sessions so the DB could get large quickly. I am going to play with the source and ‘upgrade’ into a more debugging module than a logging one.

    The first steps are easy just add,

    $log->setSessionData(serialize($_SESSION));
    $log->setCookieData(serialize($_COOKIE));
    

    to ActiveCodeline/ActionLogger/Model/Observer.php -> hookToFrontendControllerActionPredispatch

    and then add the two fields to the sql install ActiveCodeline/ActionLogger/sql/activecodeline_actionlogger_setup

    `session_data` TEXT NULL,
    `cookie_data` TEXT NULL,
    

    NOTE: this should be done before the module is installed.

    I’ll post more work when I’ve had a play.
    Alan

  7. Philip Ortiz

    Hi,

    I tried to download this but Magento Connect is reporting that the file is no longer there. Is there a way to download a zip file of this extension and just install it manually? Also, I might modify it a bit to fit our shop.

    Regards,
    Philip

  8. Jens Schneider

    Download in Magento Connect is dead. Could you reupload the extension?

    Regards,
    Jens

  9. Guilherme

    As Philip and Jens mentioned, the files are gone on Magento Connect, could you please reupload the extension?

    Thanks!

  10. Vladimir Vidinliev
  11. arun

    I installed this extension. This is really good.

    But, Under Developer section there is option for front end and admin options. Also, under System->Logger there are no sub-menus.

    Am I missing anything?

    Thanks.

  12. Michal

    After installing the module to version 1.6.1 (1.7.1-beta as well) I received after clicking “Inchoo Logger” message: “Inchoo_Logger seems to be disabled under System > Configuration > Advanced > Developer > Inchoo Logger > Enabled [Yes | No]. Please enable it in order to see the logger grid.”
    But it is allowed.

  13. Many thanks for creating and sharing this extension. Will it work on 1.7.0.2 by any chance?

  14. Sajid

    Hi,

    Thank you for this great extension. I need it desperately for ver 1.4.0.1. Can I have a zip which I can install myself?

  15. Can i disable front end logging. i only wanted backend log’s. how to do this ?

  16. marco

    Seems to be not available anymore ad MagentoConnect. 404 Page not found.

  17. Hi Branko, thank you for this excelent post. Your module is not available under magento connect. Could you post a link to download it? Cheers ;)

  18. ups, not available

  19. Lance

    Can you please upload your plugin to github with the rest of our plugins? I would really like to take a look =)

  20. You can find improved version of the module here https://github.com/ajzele/Inchoo_Logger. Its rewrite actually, so its different then the original one mentioned in this post. Cheers.

Add Your Comment

Please wrap all source codes with [code][/code] tags.
Top