<?php
namespace Engine\Logger; class Csv extends \Engine\Logger\File { protected $fileHeader = [ ]; public function setFileHeader(array $fileHeader) { $this->fileHeader = $fileHeader; return $this; } public function getFileHeader() { return $this->fileHeader; } public function writeRawMessage($fields) { $fullFilePath = $this->getRealFullFilepath($fields['level'], $fields['logSession']).".csv"; $errMessage = $this->composeErrorMessage($fields['level'], $fields['message'], $fields['context'], $fields['stacktrace'], $fields['idUser'], $fields['addTime'], $fields['logSession']); if (!\Engine\File::check($fullFilePath)) { \Engine\File::create($fullFilePath); $fh = fopen($fullFilePath, "a+"); if (!$fh) { throw new \Exception("Cannot write to {$fullFilePath}"); } fputcsv($fh, array_keys($errMessage), ",", "\"", ""); fclose($fh); } $fh = fopen($fullFilePath, "a+"); if (!$fh) { throw new \Exception("Cannot write to {$fullFilePath}"); } fputcsv($fh, array_values($errMessage), ",", "\"", ""); fclose($fh); return true; } protected function composeErrorMessage($level, $message, $context, $stacktrace, $idUser, $addTime, $logSession) { $ret = []; $ret['level'] = $level; $ret['message'] = $message; $ret['idUser'] = $idUser; $ret['addTime'] = $addTime; $ret['logSession'] = $logSession; foreach ($this->fileHeader as $contextItem) { $ret[$contextItem] = (isset($context[$contextItem])?$context[$contextItem]:''); unset($context[$contextItem]); } $ret['context'] = ($context?json_encode($context, true): ''); return $ret; } } 