/** * @return Logger */ public function getLogger() { if (!isset($this->_logger)) { $this->_logger = \Yii::getLogger(); } return $this->_logger; }
/** * Adds the current LDAP-authenticated user to the 'internal_staff_auth' permissions group. */ public function assignInternalStaffAuth() { $logger = \Yii::getLogger(); $logger->init(); $logger->flushInterval = 1; $logger->traceLevel = 0; $this->setIsNewRecord(True); $this->item_name = "internal_staff_auth"; $this->user_id = (string) strval($this->user_id); if (intval($this->user_id) > 0) { $this->created_at = time(); $this->created_by = "system"; $this->updated_by = "system"; $this->save(); } $msg = "gms: assignInternalStaffAuth() for UserId: " . $this->user_id; \Yii::trace($msg . " (YT)", __METHOD__); //Use the convenience method 'TRACE' $logger->log($msg . " (LG)", 4); if (!empty($this->getErrors())) { $errs = $this->getErrors(); foreach ($errs as $err) { foreach ($err as $item) { $msg = "gms: ERR in assignInternalStaffAuth() -- " . $item; //\Yii::trace($msg . " (YT)", __METHOD__); //Use the convenience method 'TRACE' //$logger->log($msg . " (LG)", 4); } } } $logger->flush(); return null; }
protected function afterAction($action) { $time = sprintf('%0.5f', Yii::getLogger()->getExecutionTime()); $memory = round(memory_get_peak_usage() / (1024 * 1024), 2) . "MB"; echo '<!-- Time: ' . $time . 'ms, memory: ' . $memory . '-->'; parent::afterAction($action); }
public static function getDBLogs() { $results = array(); $n = 0; foreach (Yii::getLogger()->getLogs() as $row) { if ($row[1] == CLogger::LEVEL_PROFILE && strpos($row[2], 'system.db.CDbCommand') === 0) { // echo CVarDumper::dumpAsString($row, 10, true); $message = $row[0]; if (strncasecmp($message, 'begin:', 6) === 0) { $row[0] = substr($message, 6); $row[4] = $n; $stack[] = $row; $n++; } else { if (strncasecmp($message, 'end:', 4) === 0) { $token = substr($message, 4); if (($last = array_pop($stack)) !== null && $last[0] === $token) { $delta = $row[3] - $last[3]; $results[$last[4]] = array($token, $delta, count($stack)); } else { throw new CException(Yii::t('app', 'Mismatching code block "{token}". Make sure the calls to Yii::beginProfile() and Yii::endProfile() be properly nested.', array('{token}' => $token))); } } } } } $now = microtime(true); while (null !== ($last = array_pop($stack))) { $results[$last[4]] = array($last[0], $now - $last[3], count($stack)); } ksort($results); return array_map(array(__CLASS__, 'formatLog'), $results); }
public function run() { $dbStat = Yii::app()->db->getStats(); $memory = round(Yii::getLogger()->memoryUsage / 1024 / 1024, 3); $time = round(Yii::getLogger()->executionTime, 3); echo "<div class='stat' id='stat'>\n <div style='float:left;padding-right:5px'> запросов: {$dbStat[0]} </div>\n <div style='float:left;padding-right:5px'> время: {$dbStat[1]} </div>\n <div style='float:left;padding-right:5px'> память: {$memory} </div>\n <div style='float:left;padding-right:5px'> выполнение: {$time} </div>\n </div>"; }
protected function afterAction($action) { $time = sprintf('%0.5f', Yii::getLogger()->getExecutionTime()); $memory = round(memory_get_peak_usage() / (1024 * 1024), 2) . "MB"; echo "Time: {$time}, memory: {$memory}"; parent::afterAction($action); }
public function register() { if ($this->getIsNewRecord() == false) { throw new \RuntimeException('Calling "' . __CLASS__ . '::' . __METHOD__ . '" on existing user'); } if ($this->module->enableConfirmation == false) { $this->confirmed_at = time(); } if ($this->module->enableGeneratingPassword) { $this->password = Password::generate(8); } $this->trigger(self::USER_REGISTER_INIT); if ($this->save()) { $this->trigger(self::USER_REGISTER_DONE); if ($this->module->enableConfirmation) { $token = \Yii::createObject(['class' => Token::className(), 'type' => Token::TYPE_CONFIRMATION]); $token->link('user', $this); $this->mailer->sendConfirmationMessage($this, $token); } else { \Yii::$app->user->login($this); } if ($this->module->enableGeneratingPassword) { $this->mailer->sendWelcomeMessage($this); } \Yii::$app->session->setFlash('info', $this->getFlashMessage()); \Yii::getLogger()->log('User has been registered', Logger::LEVEL_INFO); return true; } \Yii::getLogger()->log('An error occurred while registering user account', Logger::LEVEL_ERROR); return false; }
/** * Overrided Confirm action * * @param int $id * @param string $code * @return string * @throws NotFoundHttpException * @throws \Exception */ public function actionConfirm($id, $code) { $user = $this->finder->findUserById($id); //$mailer = \Yii::$container->get(dektriumMailer::className()); $mailer = new \common\helpers\Mandrill($user->email, 'Welcome to Razzd!', 'welcome', $sender = null, ['user' => $user, 'mandrill_template_name' => 'welcome']); if ($user === null || $this->module->enableConfirmation == false) { throw new NotFoundHttpException(); } /** @var Token $token */ $token = $this->findToken($id, $code, Token::TYPE_CONFIRMATION); if ($token === null || $token->isExpired) { \Yii::$app->session->setFlash('danger', \Yii::t('user', 'The confirmation link is invalid or expired. Please try requesting a new one.')); } else { $token->delete(); $user->confirmed_at = time(); \Yii::$app->user->login($user); \Yii::getLogger()->log('User has been confirmed', Logger::LEVEL_INFO); if ($user->save(false)) { \Yii::$app->session->setFlash('success', \Yii::t('user', 'Thank you, registration is now complete.')); $mailer->sendMessage(); } else { \Yii::$app->session->setFlash('danger', \Yii::t('user', 'Something went wrong and your account has not been confirmed.')); } } return $this->render('/message', ['title' => \Yii::t('user', 'Account confirmation'), 'module' => $this->module]); }
/** * {@inheritdoc} */ public function run() { $resources = array(YiiDebug::t('Page Load Time') => sprintf('%0.3F s.', $this->getLoadTime()), YiiDebug::t('Elapsed Time') => sprintf('%0.3F s.', $this->getRequestLoadTime()), YiiDebug::t('Memory Usage') => number_format(Yii::getLogger()->getMemoryUsage() / 1024) . ' KB', YiiDebug::t('Memory Peak Usage') => number_format(memory_get_peak_usage() / 1024) . ' KB'); if (function_exists('mb_strlen') && isset($_SESSION)) { $resources[YiiDebug::t('Session Size')] = sprintf('%0.3F KB', mb_strlen(serialize($_SESSION)) / 1024); } $this->render('resource_usage', array('resources' => $resources)); }
/** * Logs a message. * @param int $level The logging level. * @param string $message The message to be logged. * @param array $context The log context. * @throws InvalidParamException The specified logging level is unknown. */ public function log($level, $message, array $context = []) { if (!isset(static::$levels[$level])) { $values = implode(', ', (new \ReflectionClass('\\Mustache_Logger'))->getConstants()); throw new InvalidParamException("Invalid enumerable value \"{$level}\". Please make sure it is among ({$values})."); } \Yii::getLogger()->log($message, static::$levels[$level], __METHOD__); }
/** * Initialize the command object. */ public function init() { // Tell yii to flush the logs every message (instead of buffering for the default 10,000) // Without this, you cannot use the log to find out where the script has got to in it's current run. Yii::getLogger()->autoFlush = 1; Yii::getLogger()->autoDump = true; parent::init(); }
public function init() { parent::init(); $logger = Yii::getLogger(); $logger->autoFlush = $this->autoFlush; $logger->detachEventHandler('onFlush', array($this, 'collectLogs')); $logger->attachEventHandler('onFlush', array($this, 'processLogs')); }
protected function getQueryCount() { $logger = Yii::getLogger(); if ($logger === null) { $this->markTestSkipped('I have not a logger'); } return $logger->getDbProfiling()[0]; }
/** * Les logs ne sont pas enregistrés lors des tests avec PHPUnit. * Cette méthode permet de les réactiver. * @see http://www.yiiframework.com/wiki/271/how-to-re-enable-logging-during-unit-testing/ */ public static function enableLogging() { // automatically send every new message to available log routes Yii::getLogger()->autoFlush = 1; // when sending a message to log routes, also notify them to dump the message // into the corresponding persistent storage (e.g. DB, email) Yii::getLogger()->autoDump = true; }
public function testMiddleware() { \Yii::getLogger()->flush(); $this->commandBus->addMiddleware(new TestMiddleware()); $result = $this->commandBus->handle(new TestCommand()); $this->assertEquals('test ok', $result); $this->assertNotFalse(array_search('middleware test 1 ok', \Yii::$app->getLog()->logger->messages[1])); $this->assertNotFalse(array_search('middleware test 2 ok', \Yii::$app->getLog()->logger->messages[2])); }
private function sysAssign($obj) { $obj->assign("TIME", sprintf('%0.5f', Yii::getLogger()->getExecutionTime())); $obj->assign("MEMORY", round(Yii::getLogger()->getMemoryUsage() / (1024 * 1024), 2) . " MB"); $obj->assign('userHostAddress', Yii::app()->request->userHostAddress); //$obj->assign('dateFormatter', Yii::app()->dateFormatter); //$obj->assign('Yii', Yii::app()); return $obj; }
public static function logFile($msg, $level = CLogger::LEVEL_INFO, $category = 'application') { $logger = Yii::getLogger(); if ($logger === null) { $logger = new CLogger(); Yii::setLogger($logger); } $logger->log($msg, $level, $category); }
/** * @param ActiveRecord $owner */ public function attach($owner) { parent::attach($owner); if (!$owner->getTableSchema()->getColumn($this->attribute)) { $logger = \Yii::getLogger(); $logger->log(sprintf('Error in % class %s don\'t have a property named ', __CLASS__, get_class($owner), $this->attribute), $logger::LEVEL_ERROR); $this->detach(); } }
/** * @param $termName * @return BaseTerm * @throws InvalidConfigException * @throws TermNotDefinedException */ public function getTerm($termName, $reload = false) { if (!isset($this->_taxonomy[$termName]) || $reload) { $tax = TaxonomyDef::findOne(['name' => $termName]); \Yii::getLogger()->log("Initialising term {$termName}", Logger::LEVEL_INFO, 'nkostadinov.taxonomy.terms'); $this->_taxonomy[$termName] = \Yii::createObject($tax->attributes); } return $this->_taxonomy[$termName]; }
/** * Ping * * @param string $siteName * @param string $homepage * @param string $url * @param string $rss * @param string $encoding * @return boolean */ public function ping($siteName, $homepage, $url, $rss, $encoding = 'UTF-8') { $request = xmlrpc_encode_request('weblogUpdates.extendedPing', array($siteName, $homepage, $url, $rss), ['encoding' => $encoding]); $response = $this->post($this->serverUrl, $request); $result = strpos($response, "<boolean>0</boolean>") ? true : false; if ($result) { \Yii::getLogger()->log('Ping Yandex success.', Logger::LEVEL_WARNING); } else { \Yii::getLogger()->log('Ping Yandex failure.', Logger::LEVEL_WARNING); } }
function afterRequest() { $attr = ['datetime' => gmdate(DATE_MYSQL, round_time(time(), self::TIME_INTERVAL, PHP_ROUND_DOWN)), 'action' => Yii::app()->request->requestUri]; if (!StatRequest::model()->findByAttributes($attr)) { $stat = new StatRequest(); $stat->setAttributes($attr, false); $stat->save(); } $time = (int) (Yii::getLogger()->getExecutionTime() * 1000); StatRequest::model()->updateByPk($attr, ['count' => new CDbExpression('count + 1'), 'time_min' => new CDbExpression("least(time_min, {$time})"), 'time_max' => new CDbExpression("greatest(time_max, {$time})"), 'time_last' => $time, 'time_total' => new CDbExpression("time_total + {$time}")]); }
/** * @inheritDoc */ public function save($file, $content) { try { $file = $this->normalizeFile($file); $this->getClient()->putObject($this->bucket, $file, $content); return true; } catch (OssException $e) { \Yii::getLogger()->log($e->getMessage(), Logger::LEVEL_ERROR); return false; } }
public function attemptConfirmation($code) { /** @var Token $token */ $token = $this->finder->findToken(['user_id' => $this->id, 'code' => $code, 'type' => Token::TYPE_CONFIRMATION])->one(); if ($token !== null && !$token->isExpired) { $token->delete(); $this->confirmed_at = time(); \Yii::getLogger()->log('User has been confirmed', Logger::LEVEL_INFO); $this->save(false); } }
public function testLogException() { $exc = new Exception('Dummy Exception'); $logCategory = 'dummy category'; YiiLogWrapper::logException($exc, \CLogger::LEVEL_ERROR, $logCategory); $logs = \Yii::getLogger()->logs; $lastLog = array_pop($logs); $this->assertEquals(array_merge(array('message' => $exc->getMessage(), 'trace' => $exc->getTraceAsString()), array(YiiLogWrapper::JSON_ENCODED => true)), json_decode($lastLog[0], true)); $this->assertEquals(\CLogger::LEVEL_ERROR, $lastLog[1]); $this->assertEquals($logCategory, $lastLog[2]); }
/** * * @param array $data */ private function renderSummary($data) { $this->renderSQLStats(); $table = array(array('Procedure', 'Count', 'Total (s)', 'Avg. (s)', 'Min. (s)', 'Max. (s)')); foreach ($data as $entry) { $table[] = array($entry[0], $entry[1], sprintf('%0.5f', $entry[4]), sprintf('%0.5f', $entry[4] / $entry[1]), sprintf('%0.5f', $entry[2]), sprintf('%0.5f', $entry[3])); } $tableLabel = 'Profiling Summary Report (' . 'Time: ' . sprintf('%0.5f', \Yii::getLogger()->getExecutionTime()) . 's, ' . 'Memory: ' . number_format(\Yii::getLogger()->getMemoryUsage() / 1024) . 'KB' . ')'; $firephp = \FirePHP::getInstance(true); $firephp->table($tableLabel, $table); }
public function processLogs($event) { static $routes; $logger = \Yii::getLogger(); $routes = isset($routes) ? $routes : \Yii::app()->log->getRoutes(); foreach ($routes as $route) { if ($route->enabled) { $route->collectLogs($logger, true); $route->logs = []; } } }
/** * {@inheritdoc} */ public function run() { $data = array(); $data[] = array('i' => 'b', 'value' => sprintf('%0.4F', $this->getLoadTime()), 'unit' => 'seconds'); $data[] = array('i' => 'a', 'value' => sprintf('%0.4F', $this->getRequestLoadTime()), 'unit' => 'seconds'); $memoryUsage = number_format(Yii::getLogger()->getMemoryUsage() / 1024 / 1024, 2); if (function_exists('memory_get_peak_usage')) { $memoryUsage .= '/' . number_format(memory_get_peak_usage() / 1024 / 1024, 2); } $data[] = array('i' => 'p', 'value' => $memoryUsage, 'unit' => 'megabytes'); $this->render('resources', array('data' => $data)); }
/** * Initializes the route. * This method is invoked after the route is created by the route manager. */ public function init() { /** @noinspection PhpIncludeInspection */ require_once Yii::getPathOfAlias($this->phpConsolePathAlias) . '/__autoload.php'; if ($this->registerHelper) { Helper::register(); } if (!$this->isEnabled || !Connector::getInstance()->isActiveClient()) { return; } $handler = Handler::getInstance(); $handler->setHandleErrors($this->handleErrors); $handler->setHandleErrors($this->handleExceptions); $handler->start(); $this->handler = $handler; // required for correct PhpConsoleExtension work /** @noinspection PhpUndefinedMethodInspection */ Yii::app()->getErrorHandler()->discardOutput = false; Yii::getLogger()->autoFlush = 1; $connector = Connector::getInstance(); if ($this->sourcesBasePath) { $connector->setSourcesBasePath($this->sourcesBasePath); } if ($this->serverEncoding) { $connector->setServerEncoding($this->serverEncoding); } if ($this->password) { $connector->setPassword($this->password); } if ($this->enableSslOnlyMode) { $connector->enableSslOnlyMode(); } if ($this->ipMasks) { $connector->setAllowedIpMasks($this->ipMasks); } if ($this->headersLimit) { $connector->setHeadersLimit($this->headersLimit); } if ($this->detectDumpTraceAndSource) { $connector->getDebugDispatcher()->detectTraceAndSource = true; } $dumper = $connector->getDumper(); $dumper->levelLimit = $this->dumperLevelLimit; $dumper->itemsCountLimit = $this->dumperItemsCountLimit; $dumper->itemSizeLimit = $this->dumperItemSizeLimit; $dumper->dumpSizeLimit = $this->dumperDumpSizeLimit; $dumper->detectCallbacks = $this->dumperDetectCallbacks; if ($this->isEvalEnabled) { $connector->startEvalRequestsListener(); } }
/** * @param NiceUrlInterface $object * * @throws \yii\db\Exception */ public function runForOne(NiceUrlInterface $object) { $transaction = \Yii::$app->getDb()->beginTransaction(); try { $factory = new NiceUrlFactory(new DatabaseCounter()); $niceUrlCollection = $factory->generate($object); /** @var NiceUrl $niceUrl */ foreach ($niceUrlCollection as $niceUrl) { NiceUrlRemover::dropOldNiceUrl($niceUrl); $niceUrl->save(); } $transaction->commit(); } catch (\Exception $e) { $transaction->rollBack(); \Yii::getLogger()->log($e->getMessage(), Logger::LEVEL_ERROR, 'niceUrl'); } }
/** * {@inheritdoc} */ public function run() { $resources = array(YiiDebug::t('Page Load Time') => sprintf('%0.6F s.', $this->getLoadTime()), YiiDebug::t('Elapsed Time') => sprintf('%0.6F s.', $this->getRequestLoadTime()), YiiDebug::t('Memory Usage') => number_format(Yii::getLogger()->getMemoryUsage() / 1024) . ' KB', YiiDebug::t('Memory Peak Usage') => function_exists('memory_get_peak_usage') ? number_format(memory_get_peak_usage() / 1024) . ' KB' : 'N/A'); if (function_exists('mb_strlen') && isset($_SESSION)) { $resources[YiiDebug::t('Session Size')] = sprintf('%0.3F KB', mb_strlen(serialize($_SESSION)) / 1024); } echo CHtml::openTag('div', $this->htmlOptions); echo CHtml::tag('h1', array(), $this->title); echo CHtml::openTag('ul', array('class' => 'data')); foreach ($resources as $key => $value) { echo CHtml::openTag('li'); echo CHtml::tag('label', array(), $key); echo CHtml::tag('span', array(), $value); echo CHtml::closeTag('li'); } echo CHtml::closeTag('ul'); echo CHtml::closeTag('div'); }