How can I create log messages in a dry way?

I use the event manager to create events that need to be logged (this is the Phalcon event manager, but this is not very important for this question). Phalcon Event Manager allows you to register a listener for events generated by another object. When event a occurs, the Phalcon event manager calls Listener::a() .

The reason I use events is because I don't want my business logic cluttered with log operators.

So, for my sample script, suppose you have a UserService object that has methods like signUp() , signIn() , grantPermission() , revokePermission() , etc. Each of them triggers an event that has its own data, which means that I need different data to create a log message, so different things are transmitted. For example, my log signUpSuccessful message is โ€œUser # 4 Createdโ€. To create this message I need a user ID, so my UserService will do:

 $eventManager->fire('signUpSuccessful', $this, $user); 

And my listener will have:

 public function signUpSuccessful($event, $source, $data) { $this->logger->log(Logger::info, 'User #' . $data->getId() . ' created.'); } 

Now, as you can imagine, if I continue the trend, this class will contain many functions that do nothing but use the $data property to create a log message.

How can I create messages without creating many functions? Is there a design template for this? I was thinking about overriding __call() , but that would mean I have to embed the logic for creating log messages inside strings in a static array, and then eval() those strings that don't seem like an elegant solution to me.

0
source share

Source: https://habr.com/ru/post/972705/


All Articles