Hi,
Can any one provide complete steps to add logging in yii3 using di and Psr\Log\LoggerInterface
Thanks,
Hi,
Can any one provide complete steps to add logging in yii3 using di and Psr\Log\LoggerInterface
Thanks,
1: Install Logger (Monolog)
Yii3 uses PSR-3, so we install Monolog:
composer require monolog/monolog
2: Configure Logger in DI Container
Open your DI config (usually):
config/common/di.php
Add this:
use Psr\Log\LoggerInterface;
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
return [
LoggerInterface::class => function () {
$logger = new Logger('app');
// logs will be saved in runtime/logs/app.log
$logger->pushHandler(
new StreamHandler(__DIR__ . '/../../runtime/logs/app.log', Logger::DEBUG)
);
return $logger;
},
];
3: Use Logger in Controller / Service
Now you can inject logger anywhere using DI:
use Psr\Log\LoggerInterface;
class SiteController
{
private $logger;
public function __construct(LoggerInterface $logger)
{
$this->logger = $logger;
}
public function actionIndex()
{
$this->logger->info('This is info log');
$this->logger->error('Something went wrong');
echo "Check log file!";
}
}
4: Log File Location
After running, check:
runtime/logs/app.log
You’ll see logs like:
[2026-04-09] app.INFO: This is info log
[2026-04-09] app.ERROR: Something went wrong
5: Different Log Types (Easy)
$this->logger->debug(‘Debug message’);
$this->logger->info(‘Info message’);
$this->logger->warning(‘Warning message’);
$this->logger->error(‘Error message’);
$this->logger->critical(‘Critical issue’);
composer require yiisoft/auth yiisoft/user
// User.phpclass User{ private int $id; private string $username; private string $password; public function getId(): int { return $this->id; } public function getUsername(): string { return $this->username; } public function getPassword(): string { return $this->password; }}
$passwordHash = password_hash('123456', PASSWORD_DEFAULT);
Save $passwordHash in database.
<form method="post" action="/login"> <input type="text" name="username" placeholder="Username"> <input type="password" name="password" placeholder="Password"> <button type="submit">Login</button></form>
public function login(ServerRequestInterface $request): ResponseInterface{ $data = $request->getParsedBody(); $username = $data['username']; $password = $data['password']; $user = $this->userRepository->findByUsername($username); if ($user && password_verify($password, $user->getPassword())) { $identity = new Identity( $user->getId(), $user->getUsername() ); $this->auth->login($identity); return $this->responseFactory ->createResponse(302) ->withHeader('Location', '/dashboard'); } echo "Invalid Login";}
Route::post('/login', [LoginController::class, 'login']);
Open:
http://localhost/login
Login with:
username: adminpassword: 123456
$this->auth->logout();
if ($this->auth->isAuthenticated()) { echo "Logged In";}