LoginSignup
5
6

More than 5 years have passed since last update.

CakePHP3でログをデータベースに書き込む

Last updated at Posted at 2015-05-07

CakePHP3では、error/debug/infoなどのログをファイルだけじゃなく、データベースにもinsertすることができます。

詳しくは
http://book.cakephp.org/3.0/en/core-libraries/logging.html
に書いてあります

テーブルの作成

 CREATE TABLE `logs` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `datetime` datetime NOT NULL,
  `level` varchar(10) NOT NULL,
  `message` text,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM DEFAULT CHARSET=utf8

モデルの作成

$ ./bin/cake bake model logs

DatabaseLogクラスの作成

src/Log/Engine/DatabaseLog.php
<?php
namespace App\Log\Engine;

use Cake\Log\Engine\BaseLog;
use Cake\ORM\TableRegistry;

class DatabaseLog extends BaseLog
{
    protected $_defaultConfig = [
        'types' => null,
        'levels' => [],
        'scopes' => [],
        'user_id' => null
    ];

    /**
     * {@inheritDoc}
     */
    public function __construct(array $config = [])
    {
        parent::__construct($config);
    }

    /**
     * {@inheritDoc}
     */
    public function log($level, $message, array $context = [])
    {
        $model = TableRegistry::get($this->_config['model']);
        $entity = $model->newEntity([
            'datetime' => date('Y-m-d H:i:s'),
            'level' => ucfirst($level),
            'message' => $message
        ]);
        $model->save($entity);
    }
}

configの追加

config/app.php
    'Log' => [
        'database' => [
            'className' => 'App\Log\Engine\DatabaseLog',
            'model' => 'Logs',
            'levels' => ['notice', 'info', 'debug', 'warning', 'error', 'critical', 'alert', 'emergency'],
        ],
    ],

以上のようにすると、ログがデータベースにも記録されるようになります。

5
6
2

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
6