例として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を継承し新規作成が必要。