For debugging / performance tests I would like to dynamically add logging code to all event handlers of components of a given type at run time.
For example, for all Datasets in a Datamodule, I need to run code in the BeforeOpen
and AfterOpen
events to capture the start time, and to log the elapsed time in AfterOpen.
I would prefer to do this dynamically (no component subclassing), so that I can add this to all existing datamodules and forms with minimal effort only when needed.
Iterating all components and filtering by their type is easy, but for the components which already have event handlers assigned, I need a way to store the existing event handlers, and assign a new modified event handler which first does the logging and then will invoke the original code which was already present.
So this code
procedure TMyDatamodule.OnBeforeOpen(Sender: TDataset);
begin
SomeProc;
end;
at run time would become
procedure TMyDatamodule.OnBeforeOpen(Sender: TDataset);
begin
StoreStartTime(Sender); // injected code
SomeProc;
end;
Is there a design pattern which can be applied, or even some example code which shows how to implement this in Delphi?