LoginSignup

This article is a Private article. Only a writer and users who know the URL can access it.
Please change open range to public in publish setting if you want to share this article with other users.

More than 5 years have passed since last update.

【CakePHP3】標準搭載のログ出力機能

Posted at

例としてshell上で、以下2つのメソッドを呼び出すとログが出力されます。

namespace App\Shell;

use Cake\Console\Shell;

/**
 * Test shell command.
 */
class TestShell extends Shell
{   
    /**
     * デバッグログ
     */
    public function debuglog()
    {
        $this->log("debug log", "debug");
        $this->out("success");
    }

    /**
     * エラーログ
     */
    public function errorlog()
    {
        $this->log("error log", "error");
        $this->out("success");
    }

}

デフォルト設定では、DocumentRoot/Project/logs配下に出力されます。

//cli-debug
2017-04-04 04:47:37 Debug: debug log

//cli-error
2017-04-04 04:47:42 Error: error log

標準で用意されているログ機能の定義は、app.phpに記載されてます。

'Log' => [
    'debug' => [
        'className' => 'Cake\Log\Engine\FileLog',
        'path' => LOGS,
        'file' => 'debug',
        'levels' => ['notice', 'info', 'debug'],
        'url' => env('LOG_DEBUG_URL', null),
    ],
    'error' => [
        'className' => 'Cake\Log\Engine\FileLog',
        'path' => LOGS,
        'file' => 'error',
        'levels' => ['warning', 'error', 'critical', 'alert', 'emergency'],
        'url' => env('LOG_ERROR_URL', null),
    ],
],

logメソッドの第二引数にdebug、もしくはerrorを指定すればログが出力。

出力フォーマットは、vendor配下のCake\Log\Engine\FileLogで定義されてます。

/**
 * FileLogクラスのlogメソッド
 */
public function log($level, $message, array $context = [])
{
    $message = $this->_format($message, $context);
    $output = date('Y-m-d H:i:s') . ' ' . ucfirst($level) . ': ' . $message . "\n";
    $filename = $this->_getFilename($level);
    if (!empty($this->_size)) {
        $this->_rotateFile($filename);
    }

    $pathname = $this->_path . $filename;
    $mask = $this->_config['mask'];
    if (empty($mask)) {
        return file_put_contents($pathname, $output, FILE_APPEND);
    }

    $exists = file_exists($pathname);
    $result = file_put_contents($pathname, $output, FILE_APPEND);
    static $selfError = false;

    if (!$selfError && !$exists && !chmod($pathname, (int)$mask)) {
        $selfError = true;
        trigger_error(vsprintf(
            'Could not apply permission mask "%s" on log file "%s"',
            [$mask, $pathname]
        ), E_USER_WARNING);
        $selfError = false;
    }
    return $result;
}

出力形式等、特別なカスタマイズは、BaseLogを継承し新規作成が必要。

0

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