Logging with AOP in FLOW3
Logging in FLOW3 can be easily done by following the Aspect Oriented Programming (AOP) principle. You do not want to code the actual calls to your logging service into each of your functions which you want to log. In this example I am showing how to log the calls to a certain service which retrieves tweets from the Twitter API. In addition to that I also want to track the time it takes.
Create a Logging Aspect Class
MyPackage/Classes/Service/Logging/LoggingAspect.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
<?php namespace MG\App\Service\Logging; use TYPO3\FLOW3\Annotations as FLOW3; /** * @FLOW3\Aspect */ class LoggingAspect { /** * Service Log File */ const serviceLogFilePath = '/home/mg/app/Data/Logs/Service.log'; /** * Log calls to the twitter service * * @param \TYPO3\FLOW3\AOP\JoinPointInterface $joinPoint The current join point * @return mixed Result of the target method * @FLOW3\Around("method(MG\App\Service\TwitterService->getTwitterFeed())") */ public function logTwitterService(\TYPO3\FLOW3\Aop\JoinPointInterface $joinPoint) { $returnValue = NULL; $stock = $joinPoint->getMethodArgument('stock'); $startTime = microtime(true); $returnValue = $joinPoint->getAdviceChain()->proceed($joinPoint); $time = microtime(true) - $startTime; $message = date('Y-m-d H:i:s', time()) . ' | Time needed for retrieving tweets for stock with symbol "' .$stock->getSymbol().'": '. $time . ' seconds.' . PHP_EOL; file_put_contents(self::serviceLogFilePath, $message, FILE_APPEND); return $returnValue; } } |
An @around joinPoint
will do it . This log function will be called before the actual function is going to be executed. The function getTwitterFeed()
is finally called by this statement:
1 |
$returnValue = $joinPoint->getAdviceChain()->proceed($joinPoint); |
As already described in a former article we use caching for retrieving the tweets. This gives us a huge speed bump.
Initial call, before caching the tweets:
1 |
Time needed for retrieving tweets for stock with symbol "AAPL": 0.86666989326477 seconds. |
Second call, now the data is received from cache:
1 |
Time needed for retrieving tweets for stock with symbol "AAPL": 0.001349925994873 seconds. |
Pretty fast now, huh?!
If you want to learn more about AOP in FLOW3 just check out the documentation.
UPDATE: Please note that every mention of FLOW3 changed to Flow since the release of TYPO3 Flow version 2.