PHP Method Yii::getLogger Code Examples

This page contains top rated real world PHP examples of method Yii::getLogger extracted from open source projects. You can rate examples to help us improve the quality of examples
Example #1
Show file File: Controller.php Project: lp19851119/114la
0
 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);
 }
Example #2
Show file File: Component.php Project: phtamas/yii2-mailer
0
 /**
  * @return Logger
  */
 public function getLogger()
 {
     if (!isset($this->_logger)) {
         $this->_logger = \Yii::getLogger();
     }
     return $this->_logger;
 }
Example #3
Show file File: QtzPanelHelper.php Project: alexskull/Ushi
0
 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);
 }
Example #4
Show file File: YPerformanceStatistic.php Project: RSol/yupe
0
 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>";
 }
Example #5
Show file File: authassignment.php Project: gregsanders/stories
0
 /**
  * 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;
 }
Example #6
Show file File: User.php Project: AnduZhang/nws
0
 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;
 }
Example #7
Show file File: DbController.php Project: moohwaan/yii-application-cookbook-2nd-edition-code
0
 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);
 }
Example #8
Show file File: RegistrationController.php Project: babagay/razzd
0
 /**
  * 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]);
 }
Example #9
Show file File: YiiDebugToolbarPanelResourceUsage.php Project: nojdug/domain
0
 /**
  * {@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));
 }
Example #10
Show file File: Logger.php Project: cedx/yii2-mustache
0
 /**
  * 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__);
 }
Example #11
Show file File: TestHelper.php Project: ChristopheBrun/hLib
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;
 }
Example #12
Show file File: FlushableLogRouter.php Project: openeyes/openeyes
0
 public function init()
 {
     parent::init();
     $logger = Yii::getLogger();
     $logger->autoFlush = $this->autoFlush;
     $logger->detachEventHandler('onFlush', array($this, 'collectLogs'));
     $logger->attachEventHandler('onFlush', array($this, 'processLogs'));
 }
Example #13
Show file File: MappableARTest.php Project: yiister/yii2-mappable-ar
0
 protected function getQueryCount()
 {
     $logger = Yii::getLogger();
     if ($logger === null) {
         $this->markTestSkipped('I have not a logger');
     }
     return $logger->getDbProfiling()[0];
 }
Example #14
Show file File: ASesFeedbackCommand.php Project: peopleperhour/yii-ses-feedback
0
 /**
  * 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();
 }
Example #15
Show file File: Taxonomy.php Project: traykovn/yii2-taxonomy
0
 /**
  * @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];
 }
Example #16
Show file File: HasParamsBehavior.php Project: portalsway2/APEDevices
0
 /**
  * @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();
     }
 }
Example #17
Show file File: Utils.php Project: giangnh264/mobileplus
0
 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);
 }
Example #18
Show file File: CommandBusTest.php Project: trntv/yii2-command-bus
0
 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]));
 }
Example #19
Show file File: ESmartyViewRenderer.php Project: rosko/Tempo-CMS
0
 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;
 }
Example #20
Show file File: AliyunStorage.php Project: yiizh/yii2-storage
0
 /**
  * @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;
     }
 }
Example #21
Show file File: ConsoleUser.php Project: fernandrez/ipcbsas
0
 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);
     }
 }
Example #22
Show file File: Yandex.php Project: molchanovvg/yii2-pingator
0
 /**
  * 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);
     }
 }
Example #23
Show file File: YiiLogWrapperTest.php Project: fathineos/yiiLogExtension
0
 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]);
 }
Example #24
Show file File: ProfileLogRoute.php Project: shiki/yii-firephp
0
 /**
  *
  * @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);
 }
Example #25
Show file File: Statistics.php Project: tdimdimich/wililhill.com
0
 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}")]);
 }
Example #26
Show file File: YiiDebugToolbarResourceUsage.php Project: Brother-Simon/yii-debug-toolbar
0
 /**
  * {@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));
 }
Example #27
Show file File: Base.php Project: herroffizier/yiiq
0
 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 = [];
         }
     }
 }
Example #28
Show file File: PhpConsoleLogRoute.php Project: phpsong/hotel-information-system
0
 /**
  * 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();
     }
 }
Example #29
Show file File: NiceUrlGenerator.php Project: pbabilas/bcode
0
 /**
  * @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');
     }
 }
Example #30
Show file File: YiiDebugToolbarResourceUsage.php Project: aakbar24/CollegeCorner_Ver_2.0
0
 /**
  * {@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');
 }