PHP Classes

File: docs/files/MessagePrepareTrait.php.txt

Recommend this page to a friend!
  Classes of Kiril Savchev   ITE Logger   docs/files/MessagePrepareTrait.php.txt   Download  
File: docs/files/MessagePrepareTrait.php.txt
Role: Documentation
Content type: text/plain
Description: Documentation
Class: ITE Logger
Log messages to different storage PSR-3 compliant
Author: By
Last change:
Date: 8 years ago
Size: 3,700 bytes
 

Contents

Class file image Download
<?php /** * MessagePrepareTrait file * * Copyright (c) 2016, Kiril Savchev * All rights reserved. * * @category Libs * @package Logger * * @author Kiril Savchev <k.savchev@gmail.com> * * @license https://opensource.org/licenses/BSD-3-Clause BSD 3 License * @link http://ifthenelse.info */ namespace Ite\Logger; /** * MessagePrepareTrait * * Provides basic message preparing with date and json encoded context * * @version 1.0 * * @author Kiril Savchev <k.savchev@gmail.com> * */ trait MessagePrepareTrait { /** * The log date format * * @var string */ protected $dateFormat = 'Y-m-d H:i:s T'; /** * Sets log date format * * @param string $dateFormat * @return self */ public function setDateFormat($dateFormat) { $this->dateFormat = $dateFormat; return $this; } /** * * @param \Trhowable|\Exception $e The exception to parse * @return array Parsed exception as an array * @throws InvalidArgumentException If the parameter is not exception or throwable object */ protected function parseException($e) { if ((interface_exists('\Throwable') && $e instanceof \Throwable ) || $e instanceof \Exception) { $exception = [ 'class' => get_class($e), 'message' => $e->getMessage(), 'code' => $e->getCode(), 'file' => $e->getFile(), 'line' => $e->getLine(), 'trace' => $e->getTraceAsString() ]; $prev = $e->getPrevious(); if ($prev) { $exception['previous'] = $this->parseException($prev); } return $exception; } else { throw new InvalidArgumentException("Invalid exception sent as context param"); } } /** * Prepares context * * Encodes context into json string * * @param array $context * @return string */ protected function prepareContext(array $context) { if (!$context) { return ''; } else { if (array_key_exists('exception', $context)) { $context['exception'] = $this->parseException($context['exception']); } return json_encode($context); } } /** * Prepares the log message for logging * * This methods adds the current datetime to the message and * the context if there is any. If there is an exception in * the context it will be parsed to. * * @param mixed $level * @param string $message * @param array $context * @return string */ protected function prepareMessage($message, array $context = []) { if (count($context)) { $message .= ', '.$this->prepareContext($context); } return '['.date($this->dateFormat).'] '.$message; } /** * Get log date format * * @return string */ public function getDateFormat() { return $this->dateFormat; } }