psysh
psysh copied to clipboard
Logging the code run via psysh
We currently use psysh in production to do custom debugging and sometimes run one off scripts for mini migrations or gathering data via our framework.
However, since people can essentially run anything via the console, it would be really nice to be able to get some kind of audit log of what people have actually run via the console and especially if some sort of accidents happen.
I tried to go through the documentation, but couldn't find any way to currently achieve this.
So, would it be possible to implement, for example, some kind of configuration option like logCallback
, that could take a callback as a value that is simply called for each piece of code that is run via psysh?
@Riimu You can use loop listeners to achieve that but it requires you to extend PsySH Shell
class. See example:
<?php
use Psy\ExecutionLoop\AbstractListener;
use Psy\Shell;
class LoggerLoopListener extends AbstractListener
{
public function onExecute(Shell $shell, $code)
{
print $code;
}
public static function isSupported()
{
return true;
}
}
class MyShell extends Shell
{
protected function getDefaultLoopListeners()
{
$listeners = parent::getDefaultLoopListeners();
$listeners[] = new LoggerLoopListener();
return $listeners;
}
}
Then create an instance of your shell and run it:
(new MyShell())->run();
Please note that you can easily override other methods from AbstractListener
to log the session start and end too. It's possible to add user context to the logs too - just ask the developer about his name before starting the shell session, pass it to your LoggerLoopListener
and log it together with the code executed.
This is actually related to #565 because there is currently no way to customize loop listeners without extending the Shell
class and overriding getDefaultLoopListeners()
method.
People can run essentially anything through their shell access, too, right? Would it be better to instrument input at that level rather than just inside PsySH?