CakePHP4でエラーログを表示する方法

CakePHP4でエラーログを表示する方法

115 回閲覧されました

みなさんこんにちは、jonioです。

CakePHPの4系でエラーログを表示したかったのですがネットでやり方を探してもなかなか見つけることができなくて時間がかかったので次回ログを表示したい時の為の自分へのメモをこの記事で残します。

CakePHPのバージョン

4.5.4です。

getErrors()を使う

エラーログを表示する前のコードは下記になります。

public function add()
{
  $post = $this->Posts->newEmptyEntity();
    if ($this->request->is('post')) {
      $post = $this->Posts->patchEntity($post, $this->request->getData());
      if ($this->Posts->save($post)) {
        $this->Flash->success(__('The post has been saved.'));

        return $this->redirect(['action' => 'index']);
      }else{
        $this->Flash->error(__('The post could not be saved. Please, try again.'));
     }
            
   }

   $users = $this->Users->find('list');      

   $this->set(compact('post', 'users'));
}

コードを書きに変更します。

public function add()
{
  $post = $this->Posts->newEmptyEntity();
    if ($this->request->is('post')) {
      $post = $this->Posts->patchEntity($post, $this->request->getData());
      if ($this->Posts->save($post)) {
        $this->Flash->success(__('The post has been saved.'));

        return $this->redirect(['action' => 'index']);
      }else{
        $this->Flash->error(__('The post could not be saved. Please, try again.'));
        $this->log(print_r($post->getErrors(),true),LOG_DEBUG);             //この行を追加
     }
            
   }

   $users = $this->Users->find('list');      

   $this->set(compact('post', 'users'));
}

12行目の「$post」は3行目の$postのことです。

これで「CakePHPのプロジェクト > logs」の下の階層にエラーログのファイルが作成されるのでそれを見るとエラーが表示されています。