from aspectify.aop import Aspect
from random import RandomFirst example. Logging.
At this moment, we want to modify the randint method to log a message.
ADVICE: Trying to be as clean as possible, we strongly recomend you to create a new
aspects.pyfile and add theAspects to this file.
Library import
First of all, we need to import to the Aspects file (aspects.py from now on) the libraries and modules that will be used. In this case, random.
Additionally, we need to define the get_classes method. This method is always needed in order to get all the available classes to add Advices.
def get_classes():
return [element for element in list(globals().items())]Aspect definition
As a first AOP example, we can define our first Aspect. We call it log_aspect, and it will send a message when the function is being called.
To do so, we add the before advice defined below. Here you can use defined functions or lambda.
log_aspect = Aspect()
log_aspect.set_before(lambda *a, **k: print("catched!"))Now, we create an Advice to define which methods will show this message. The methods are named as follows:
module.Class.method_nameSo, as we want to only change the random.Random.randint method, we use its fullname.
NOTE: if we wanted to select several methods at once, we could have used a regular expression. For example,
.*\.Random\..*will catch all the methods within aRandomclass, regardless of their modules.
log_aspect.create_pointcut(get_classes(), "random.Random.randint")Captured method: random.Random.randint
create_pointcut method has a default parameter called logging set to true in order to show the captured methods. You can deactivate it if you wish.
After the PointCut is created, every method catched (random.Random.randint) will be modified by the defined PointCuts.
From now on, when randint is used, we will see the “catched!” message.
Results
r = Random()
r.randint(1, 10)catched!
9
Conclusion
This simple example shows how to add logging functionality to the defined code, even when the code is a black box (a library not developed by the user that is using Aspectify).
In the next example we will explain why you should be strictly accurate using the create_pointcut patter syntax.