/** * Options request for any Installation request. * * @param HttpFoundation\Request $request * @return HttpFoundation\Response */ public function optionsIndex(HttpFoundation\Request $request) { $this->log->addDebug(print_r($request, true), ['namespace' => 'Alerts\\Controllers\\Install', 'method' => 'optionsIndex', 'type' => 'request']); $response = new HttpFoundation\Response('OK'); $response->headers->add(['Access-Control-Allow-Methods' => 'POST, OPTIONS']); return $response; }
/** * Called when this object is called as a function * * @param Context $context * @param OptionsFactory $optionsFactory * @throws \Exception if haltOnError setting is true */ public function __invoke(Context $context, OptionsFactory $optionsFactory) { $getopt = $context->getopt(array_keys(self::$options)); // Get directory list $dirListFactory = new DirectoryListFactory(); $dirListFactory->loadFromCommandline($getopt->get(), 2); $dirListFactory->loadFromStdin(new StdinReader(3)); $dirList = $dirListFactory->getList(); $this->logger->addDebug('Found directories', [count($dirList)]); // Load base options $baseOptions = $optionsFactory->newInstance(); $baseOptions->validateAllRequired(); if ($baseOptions->preview) { $this->logger->addNotice('PREVIEW MODE'); } foreach ($dirList as $dir) { try { $this->logger->addNotice('In directory', [$dir]); $this->processDirectory($dir, $baseOptions, $optionsFactory); } catch (\Exception $e) { if ($baseOptions->haltOnError) { throw $e; } elseif ($baseOptions->verbosity == 2) { $this->logger->addError($e, []); } else { $this->logger->addError($e->getMessage(), []); } } } }
protected function writeEntry($level, $message, $indent, $category = "", $additionalData = []) { $message = str_pad($category, 16, " ", STR_PAD_RIGHT) . "\t" . str_repeat(" ", $indent) . $message; switch ($level) { case Log::BULK_DATA_LEVEL: $this->logger->addDebug($message, $additionalData); break; case Log::DEBUG_LEVEL: $this->logger->addDebug($message, $additionalData); break; case Log::ERROR_LEVEL: $this->logger->addError($message, $additionalData); break; case Log::PERFORMANCE_LEVEL: $this->logger->addNotice($message, $additionalData); break; case Log::WARNING_LEVEL: $this->logger->addWarning($message, $additionalData); break; case Log::REPOSITORY_LEVEL: $this->logger->addNotice($message, $additionalData); break; default: $this->logger->addNotice($message, $additionalData); } }
public function log($message, $priority = self::INFO) { if ($message instanceof \Exception) { $message = $message->getMessage(); $context = []; } elseif (is_string($message)) { $context = []; } else { $context = $message; unset($context[0]); unset($context[1]); if (isset($message[1])) { $message = preg_replace('#\\s*\\r?\\n\\s*#', ' ', trim($message[1])); } } switch ($priority) { case self::DEBUG: return $this->monolog->addDebug($message, $context); case self::CRITICAL: return $this->monolog->addCritical($message, $context); case self::ERROR: return $this->monolog->addError($message, $context); case self::EXCEPTION: return $this->monolog->addEmergency($message, $context); case self::WARNING: return $this->monolog->addWarning($message, $context); case 'access': return $this->monolog->addNotice($message, $context); case 'emergency': return $this->monolog->addEmergency($message, $context); default: return $this->monolog->addInfo($message, $context); } }
/** * @param string $token Access token from the calling client * * @return string|false The result from the cURL call against the oauth API. * * @codeCoverageIgnore This function is not tested because we can't test * curl_* calls in PHPUnit. */ protected function _call($token) { $ch = curl_init(); $url = $this->_apiUrl . $token; $this->_logger->addDebug('calling GET: ' . $url); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_HTTPHEADER, array('Accept: application/json')); $result = curl_exec($ch); $responseCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE); $curlErrno = curl_errno($ch); $curlError = curl_error($ch); // remove token from url for log output $url = substr($url, 0, stripos($url, 'token') + 6); if (0 !== $curlErrno) { $this->_logger->addError('curl error (' . $curlErrno . '): ' . $curlError . ' url: ' . $url); } if ($responseCode >= 500) { $this->_logger->addError('curl call error: ' . $responseCode . ' url: ' . $url); } elseif ($responseCode >= 300) { $this->_logger->addWarning('curl call warning: ' . $responseCode . ' url: ' . $url); } $this->_logger->addDebug('result: (' . $responseCode . ') ' . var_export($result, true)); curl_close($ch); return $result; }
public static function sendPush($deviceToken, $message, $data = null, $type = null) { $log = new \Monolog\Logger('notifications'); $log->pushHandler(new \Monolog\Handler\StreamHandler(Env::$config->logPath . 'notifications.log', Logger::DEBUG)); $log->addInfo('Entering to send a push'); if (strlen($deviceToken) == 64) { $log->addInfo('Sending notification to ios device', ["deviceToken" => $deviceToken]); $ctx = stream_context_create(); //dev pem /home7/quesoazu/www/doyride/push/dev_key.pem stream_context_set_option($ctx, 'ssl', 'local_cert', Env::$config->pem); stream_context_set_option($ctx, 'ssl', 'passphrase', Env::$config->passphrase); // Open a connection to the APNS server // DEV APNS gateway.sandbox.push.apple.com:2195 $fp = stream_socket_client(Env::$config->apns, $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx); if (!$fp) { exit("Failed to connect: {$err} {$errstr}" . PHP_EOL); } //echo 'Connected to APNS' . PHP_EOL; // Create the payload body $body['aps'] = array('alert' => $message, 'sound' => 'default', 'content-available' => 1); $body['d'] = $data; $body['t'] = $type; // Encode the payload as JSON $payload = json_encode($body); // Build the binary notification $msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload; // Send it to the server $result = fwrite($fp, $msg, strlen($msg)); $log->addDebug($result); // Close the connection to the server fclose($fp); } else { $log->addInfo('Sending notification to android device', ["deviceToken" => $deviceToken]); //AIzaSyBpweimzrQ-5pjUO1absB4cTrDVRHIxmMg $api_key = Env::$config->apikey; //$registrationIDs = array("APA91bHOZnfPwVys28cus-w9s18zZw4lXb-CU1Os8OiA2MpLpvGc4b9sxipnAVZNiDHe3iWv4T-_5B7UHJ_ce2ybu_w_Z4Y_kXWsIJqE4bjyF0tcrZrofszmE42xJ_sg15Tw2yG2IxVXcFu37LyP7ZHx9DqRqqRByPSLUwkrUqzqavQSWt1A3l4"); $registrationIDs = array($deviceToken); $message = $message; $url = 'https://android.googleapis.com/gcm/send'; /*$body['registration_ids'] = $deviceToken; $body['aps'] = array( 'alert' => $message, 'sound' => 'default' ); $body['d'] = $data; $body['t'] = $type;*/ $fields = array('registration_ids' => $registrationIDs, 'data' => array("message" => $message, "d" => $data, "t" => $type)); $headers = array('Authorization: key=' . $api_key, 'Content-Type: application/json'); $ch = curl_init(); curl_setopt($ch, CURLOPT_URL, $url); curl_setopt($ch, CURLOPT_POST, true); curl_setopt($ch, CURLOPT_HTTPHEADER, $headers); curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($fields)); $result = curl_exec($ch); $log->addDebug($result); curl_close($ch); } }
/** * @param $configFile */ public function loadFile($configFile) { if (!file_exists(realpath($configFile))) { $this->logger->addError('Config file ' . realpath($configFile) . ' not found.'); return; } try { $this->config = array_change_key_case(include $configFile, \CASE_LOWER); $this->logger->addDebug('Config file loaded: ' . realpath($configFile)); } catch (\Exception $e) { $this->logger->addError('Failed loading config file (' . realpath($configFile) . '): ' . $e->getMessage()); } }
/** * Log a message * * @param string $message * @param int $level * @param array $context * @return void */ public function log($message, $level = Logger::INFO, array $context = []) { if (!$this->logger) { return; } if (null === $level) { $level = Logger::INFO; } switch ($level) { case Logger::DEBUG: $this->logger->addDebug($message, $context); break; case Logger::INFO: $this->logger->addInfo($message, $context); break; case Logger::NOTICE: $this->logger->addNotice($message, $context); break; case Logger::WARNING: $this->logger->addWarning($message, $context); break; case Logger::ERROR: $this->logger->addError($message, $context); break; case Logger::CRITICAL: $this->logger->addCritical($message, $context); break; case Logger::EMERGENCY: $this->logger->addEmergency($message, $context); break; default: break; } }
/** * @internal Log debug events in verbose mode */ private function debug($message) { if (1 < func_num_args()) { $message = call_user_func_array('sprintf', func_get_args()); } $this->logger->addDebug($message); }
/** * @param array $fromCols * @param array $toCols * @throws StructureException * @throws \Exception */ public function compareColumns($fromCols, $toCols) { $columnClass = new \ReflectionClass('rombar\\PgExplorerBundle\\Models\\dbElements\\Column'); if (count($fromCols) == 0 || count($toCols) == 0) { throw new \Exception('A table has no columns!'); } $ignoredMethods = ['getTable', 'getRealPosition', 'getOid']; list($namesFrom, $namesTo) = $this->compareColumnsNames($fromCols, $toCols); foreach ($namesFrom as $fromKey => $fromColName) { $fromCol = $fromCols[$fromKey]; $toCol = $toCols[array_search($fromColName, $namesTo)]; foreach ($columnClass->getMethods(\ReflectionMethod::IS_PUBLIC) as $method) { if (preg_match('#^get#', $method->name) && !in_array($method->name, $ignoredMethods)) { $getter = $method->name; if ($fromCol->{$getter}() != $toCol->{$getter}()) { //Special hook for nextval. // With certain search path, the schema can be omitted wich make a false positive. if ($getter == 'getDefault' && preg_match('/^nextval/', $fromCol->{$getter}())) { $diff = str_replace('.', '', Utils::stringDiff($fromCol->{$getter}(), $toCol->{$getter}())); $this->logger->addDebug('diff search_path : ' . $diff); if (in_array($diff, $this->toAnalyzer->getSearchPath()) || in_array($diff, $this->fromAnalyzer->getSearchPath())) { $this->logger->addWarning('Bypass by search_path test for ' . $getter . ' : ' . $fromCol->{$getter}() . ' vs ' . $toCol->{$getter}()); continue; } } $this->logger->addWarning('Column ' . $fromColName . '->' . $getter . '() : ' . $fromCol->{$getter}() . ' vs ' . $toCol->{$getter}()); var_dump($fromCol); var_dump($toCol); throw new StructureException('Targeted database has a different column ' . $fromCol->getName() . ' in table ' . $fromCol->getSchema() . PgAnalyzer::DB_SEPARATOR . $this->fromAnalyzer->getTable($fromCol->getSchema(), $fromCol->getTable())->getName() . ' check the property ' . substr($getter, 3)); } } } } }
/** * Options request for OAuth. * * @param int $id * @param HttpFoundation\Request $request * @return HttpFoundation\Response */ public function optionsIndex($id, HttpFoundation\Request $request) { $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'optionsIndex', 'type' => 'request']); $response = new HttpFoundation\Response('OK'); $response->headers->add(['Access-Control-Allow-Methods' => is_null($id) ? 'POST, OPTIONS' : 'POST, PUT, OPTIONS']); return $response; }
/** * Отправляет сообщение в лог * * @param string $message сообщение * @param int $level уровень * * @return void */ public function log($message, $level = AbstractLogger::NOTICE) { if ($level < $this->severity) { return; } switch ($level) { case AbstractLogger::EMERGENCY: $this->impl->addEmergency($message); break; case AbstractLogger::ALERT: $this->impl->addAlert($message); break; case AbstractLogger::CRITICAL: $this->impl->addCritical($message); break; case AbstractLogger::ERROR: $this->impl->addError($message); break; case AbstractLogger::WARNING: $this->impl->addWarning($message); break; case AbstractLogger::NOTICE: $this->impl->addNotice($message); break; case AbstractLogger::INFO: $this->impl->addInfo($message); break; case AbstractLogger::DEBUG: $this->impl->addDebug($message); break; } }
/** * Start the worker. */ public function startWorker() { $this->pheanstalk->watch($this->queue); $this->pheanstalk->ignore('default'); $buildStore = Factory::getStore('Build'); while ($this->run) { // Get a job from the queue: $job = $this->pheanstalk->reserve(); $this->checkJobLimit(); // Get the job data and run the job: $jobData = json_decode($job->getData(), true); if (!$this->verifyJob($job, $jobData)) { continue; } $this->logger->addInfo('Received build #' . $jobData['build_id'] . ' from Beanstalkd'); // If the job comes with config data, reset our config and database connections // and then make sure we kill the worker afterwards: if (!empty($jobData['config'])) { $this->logger->addDebug('Using job-specific config.'); $currentConfig = Config::getInstance()->getArray(); $config = new Config($jobData['config']); Database::reset($config); } try { $build = BuildFactory::getBuildById($jobData['build_id']); } catch (\Exception $ex) { $this->logger->addWarning('Build #' . $jobData['build_id'] . ' does not exist in the database.'); $this->pheanstalk->delete($job); } try { // Logging relevant to this build should be stored // against the build itself. $buildDbLog = new BuildDBLogHandler($build, Logger::INFO); $this->logger->pushHandler($buildDbLog); $builder = new Builder($build, $this->logger); $builder->execute(); // After execution we no longer want to record the information // back to this specific build so the handler should be removed. $this->logger->popHandler($buildDbLog); } catch (\PDOException $ex) { // If we've caught a PDO Exception, it is probably not the fault of the build, but of a failed // connection or similar. Release the job and kill the worker. $this->run = false; $this->pheanstalk->release($job); } catch (\Exception $ex) { $build->setStatus(Build::STATUS_FAILED); $build->setFinished(new \DateTime()); $build->setLog($build->getLog() . PHP_EOL . PHP_EOL . $ex->getMessage()); $buildStore->save($build); $build->sendStatusPostback(); } // Reset the config back to how it was prior to running this job: if (!empty($currentConfig)) { $config = new Config($currentConfig); Database::reset($config); } // Delete the job when we're done: $this->pheanstalk->delete($job); } }
/** * Loads a plugin. See the README for plugin documentation. * * @param AbstractPlugin $plugin An instance of the plugin to load * * @return \Philip\Philip */ public function loadPlugin(AbstractPlugin $plugin) { $name = $plugin->getName(); $this->log->addDebug('--- Loading plugin ' . $name . PHP_EOL); $plugin->init(); $this->plugins[$name] = $plugin; return $this; }
private function post($path, $code, $grant_type, $fields = []) { $curl = curl_init(); curl_setopt_array($curl, [CURLOPT_URL => self::PUBLIC_API . DIRECTORY_SEPARATOR . $path, CURLOPT_RETURNTRANSFER => true, CURLOPT_HTTPHEADER => ['Accept: application/json'], CURLOPT_POST => true, CURLOPT_POSTFIELDS => http_build_query(array_merge(['code' => $code, 'grant_type' => $grant_type, 'client_id' => $this->getClientId(), 'client_secret' => $this->getClientSecret(), 'redirect_uri' => $this->getRedirectUri()], $fields))]); $result = curl_exec($curl); $this->logger->addDebug('#Orcid Debug', [$result]); return json_decode($result); }
/** * Validates a request and takes a scope value that could result * in a user id being put into the request if it's valid. * * @param HttpFoundation\Request $request * @param string $scope * @return null|HttpFoundation\Response */ public function validateRequest(HttpFoundation\Request $request, $scope) { $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]); $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request); if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) { //Put the userId into the request if we're validating at the user scope if ($scope === 'user') { $token = $this->server->getAccessTokenData($bridgeRequest); $request->request->set('userId', $token['user_id']); } else { //Set the userId to 0 which should make any //searches relying on this being valid to fail. $request->request->set('userId', 0); } return null; } $this->log->addWarning('Failed to validate request', ['namespace' => 'HackTheDinos\\Controllers\\OAuth', 'method' => 'validateRequest', 'scope' => $scope]); return new HttpFoundation\Response('Not Authorized', 401); }
public function flushStats() { foreach ($this->cumulatedTime as $statementName => $seconds) { $queryCount = $this->queryCount[$statementName]; $this->logger->addDebug("executing '{$statementName}' took " . $this->formatMilliseconds($seconds) . " ({$queryCount} queries" . ($queryCount > 0 ? ", avg " . $this->formatMilliseconds($seconds / $queryCount) : "") . ")"); } if ($this->transactionDepth != 0) { throw new \Fossology\Lib\Exception("you have not committed enough"); } }
public function run() { $this->output->writeln("Downloading video: " . $this->video->getId()); $this->logger->addInfo("START Downloading video: " . $this->video->getId()); if ($this->video->getDownloaded()) { $this->output->writeln("<info>Video already downloaded... Continue...</info>"); $this->logger->addInfo("END Skipping video: " . $this->video->getId() . " -> Already exists!"); return; } $builder = new ProcessBuilder(array('youtube-dl', '-x', '--audio-format', 'mp3', '--output', $this->webDir . "/media/" . "%(id)s.%(ext)s", '--cache-dir', $this->appDir . "/ytdl_cache/", 'https://youtube.com/watch?v=' . $this->video->getId())); $process = $builder->getProcess(); $process->setTimeout(0); $logger = $this->logger; $output = $this->output; $process->run(function ($type, $buffer) use($logger, $output) { if (Process::ERR === $type) { $output->writeln("<error>{$buffer}</error>"); $logger->addError("YOUTUBE-DL: " . $buffer); } else { $logger->addDebug("YOUTUBE-DL: " . $buffer); } }); $this->logger->addDebug("Video " . $this->video->getId() . ": Exitcode " . $process->getExitCode()); if ($process->getExitCode() === 0) { $this->video->setDownloaded(true); $output->writeln("<info>Video successfully downloaded!</info>"); $this->logger->addInfo("Video " . $this->video->getId() . ": Downloaded successfull"); } elseif ($process->getExitCode() === 127) { $this->video->setDownloaded(false); $output->writeln("<error>youtube-dl isn't installed!</error>"); $this->logger->addError("youtube-dl isn't available!"); } else { $this->video->setDownloaded(false); $output->writeln("<error>Video downloading error! See logs.</error>"); $this->logger->addError("Video " . $this->video->getId() . ": Unknown error!"); } $this->videoWrapper->saveVideo($this->video); }
/** * Create a new picture * * @param HttpFoundation\Request $request * @return HttpFoundation\JsonResponse|HttpFoundation\Response */ public function postIndex(HttpFoundation\Request $request) { $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\Pictures', 'method' => 'postIndex', 'type' => 'request']); $path = 'uploads'; $newfilename = date('Y-m-d_His') . '.jpg'; if ($_FILES["picture"]["error"] === UPLOAD_ERR_OK) { $tmp_name = $_FILES["picture"]["tmp_name"]; move_uploaded_file($tmp_name, "uploads/{$newfilename}"); } else { return new HttpFoundation\Response($_FILES["picture"]["error"], 500); } // TODO create a model object $picture = new Models\Picture(); $picture->filepath = $newfilename; // TODO save to DB if ($this->repo->save($picture)) { $this->log->addInfo('Created new picture', ['namespace' => 'HackTheDinos\\Controllers\\Picture', 'method' => 'postIndex', 'picture' => (array) $picture]); // TODO return picture db id return new HttpFoundation\JsonResponse($picture, 201); } $this->log->addWarning('Unable to create picture', ['namespace' => 'HackTheDinos\\Controllers\\Picture', 'method' => 'postIndex', 'request' => $request->getContent(), 'picture' => (array) $picture]); return new HttpFoundation\Response('Bad Request', 400); }
/** * Validates a request and takes a scope value that could result * in a user id being put into the request if it's valid. The * passThrough flag will allow the request to continue when it * would otherwise fail with a 401 response. * * @param HttpFoundation\Request $request * @param string $scope * @param bool $passThrough * @return null|HttpFoundation\Response */ public function validateRequest(HttpFoundation\Request $request, $scope, $passThrough = false) { $this->log->addDebug(print_r($request, true), ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope]); $bridgeRequest = HttpFoundationBridge\Request::createFromRequest($request); if ($this->server->verifyResourceRequest($bridgeRequest, null, $scope)) { //Put the user into the request if we're validating at the user scope if ($scope === 'user') { $token = $this->server->getAccessTokenData($bridgeRequest); $request->request->set('user', $this->usersRepo->getById($token['user_id'])); } else { //Set the user to null which should make any //searches relying on this being valid to fail. $request->request->set('user', null); } return null; //If the request shouldn't hard fail. This should only have a few specific use cases. } elseif ($passThrough) { $this->log->addInfo('OAuth Pass Through', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'type' => 'request', 'scope' => $scope, 'passThrough' => true]); return null; } $this->log->addInfo('Failed to validate request', ['namespace' => 'Alerts\\Controllers\\OAuth2', 'method' => 'validateRequest', 'scope' => $scope]); return new HttpFoundation\Response('Not Authorized', 401); }
/** * @test */ public function it_correctly_identifies_the_info() { $bugsnag = new Bugsnag_Client(self::APIKEY); $logger = new Logger('my_logger'); $logger->pushHandler(new BugsnagHandler(Logger::INFO, true, 'BugsnagMonolog', $bugsnag)); $logger->addInfo('info', ['some' => 'message']); $logger->addError('error', ['some' => 'message']); $logger->addAlert('alert', ['some' => 'message']); $logger->addCritical('critical', ['some' => 'message']); $logger->addDebug('debug', ['some' => 'message']); $logger->addWarning('warning', ['some' => 'message']); $logger->addEmergency('emergency', ['some' => 'message']); $logger->addNotice('notice', ['some' => 'message']); $this->assertTrue(true); }
public static function log($message, $priority = '') { if (LOG_LEVEL != null && LOG_LEVEL > 0) { $log = new Logger('movim'); $handler = new SyslogHandler('movim'); if (LOG_LEVEL > 1) { $log->pushHandler(new StreamHandler(LOG_PATH . '/movim.log', Logger::DEBUG)); } $log->pushHandler($handler, Logger::DEBUG); $errlines = explode("\n", $message); foreach ($errlines as $txt) { $log->addDebug($txt); } } }
/** * @param int $fossilId * @param HttpFoundation\Request $request * @return HttpFoundation\JsonResponse|HttpFoundation\Response */ public function postVotes($fossilId, HttpFoundation\Request $request) { $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\Fossils', 'method' => 'postVotes', 'type' => 'request']); $fossil = $this->fossilRepo->getById($fossilId); if (is_null($fossil)) { $this->log->addWarning('Could not find fossil', ['namespace' => 'HackTheDinos\\Controllers\\Fossils', 'method' => 'postVotes', 'fossilId' => $fossilId]); return new HttpFoundation\Response('Dog Not Found', 400); } $vote = $this->converter->entityArrayToModel(json_decode($request->getContent(), true), new Models\Vote()); $vote->fossilId = $fossil->id; if ($this->voteRepo->save($vote)) { $this->log->addInfo('Created new vote', ['namespace' => 'HackTheDinos\\Controllers\\Fossils', 'method' => 'postVote', 'fossil' => $fossil, 'vote' => $vote]); return new HttpFoundation\JsonResponse($vote, 201); } $this->log->addWarning('Unable to create vote', ['namespace' => 'HackTheDinos\\Controllers\\Fossils', 'method' => 'postVotes', 'request' => $request->getContent(), 'fossil' => $fossil, 'vote' => $vote]); return new HttpFoundation\Response('Bad Request', 400); }
/** * Queues an URL onto the queue if not queued yet * @param string * @return bool */ public function queueUrl($url) { // Remove fragment from URL (if any) if (strpos($url, '#')) { $url = substr($url, 0, strpos($url, '#')); } // If the URL should not be ignored (pattern matching) and isn't added to the list yet, add it to the list of pages to scan. if (preg_match('#^' . $this->rootUrlBasePath . '#i', $url) === 1 && !in_array($url, $this->pages)) { foreach ($this->ignorePatterns as $p) { if ($p && preg_match('#' . $p . '#i', $url)) { return false; } } $this->pages[] = $url; $this->logger->addDebug('Queued ' . $url); return true; } // Not queued return false; }
public static function log($loggerName, $message, $context = array(), StreamHandler $handler = null, LineFormatter $formatter = null) { $logger = null; if (isset(self::$_loggers[$loggerName])) { $logger = self::$_loggers[$loggerName]; } else { $logger = new Logger($loggerName); } if ($formatter == null) { self::initialize(); $formatter = self::$_formatter; } $handler->setFormatter($formatter); //设置handler $logger->pushHandler($handler); $level = $handler->getLevel(); if ($level == Logger::DEBUG) { $logger->addDebug($message, $context); } }
/** * Récupération du contenu de la page. * * @param string $url Url de la page à aspirer * * @return string */ public function exec($url) { // Application des headers $headers = $this->header->getHeader(); if (!empty($headers)) { $this->setOpt(CURLOPT_HTTPHEADER, $headers); } // chargement des options non modifiables foreach ($this->finalOpt as $option => $value) { $this->setOpt($option, $value); } $this->setOpt(CURLOPT_URL, $url); $this->log->addDebug('hit on ' . $url, [$headers]); $content = curl_exec($this->curl); if (curl_error($this->curl) !== '') { $this->log->addWarning('Error ' . curl_error($this->curl)); } $this->infoHit = curl_getinfo($this->curl); return $content; }
/** * Write a new report * * @return void */ public function write($params = array()) { $defaults = array(); // Test for DB, in case it's not able to connect yet try { $defaults['database'] = DB::getQueryLog(); } catch (\Exception $e) { // Continue running even if DB could not be logged, but display // a note in the log $this->buffer('error', 'Reporter could not connect to the database'); } // Default params $defaults['input'] = Input::get(); $defaults['logs'] = $this->buffered; // Apply default params $params = array_merge($defaults, $params); // Do a debug log, passing it all the extra data that it needs. This will ultimately // write to the log file $this->logger->addDebug('Reporter', $params); }
public function debug($message, $array = array()) { $log = new Logger($this->logName); $log->pushHandler(new StreamHandler($this->logFile, Logger::DEBUG)); $log->addDebug($message, $array); }
<?php /* * This file is part of the Monolog package. * * (c) Jordi Boggiano <*****@*****.**> * * For the full copyright and license information, please view the LICENSE * file that was distributed with this source code. */ spl_autoload_register(function ($class) { $file = __DIR__ . '/../../../../src/' . strtr($class, '\\', '/') . '.php'; if (file_exists($file)) { require $file; return true; } }); use Monolog\Logger; use Monolog\Handler\FirePHPHandler; use Monolog\Handler\ChromePHPHandler; $logger = new Logger('firephp'); $logger->pushHandler(new FirePHPHandler()); $logger->pushHandler(new ChromePHPHandler()); $logger->addDebug('Debug'); $logger->addInfo('Info'); $logger->addWarning('Warning'); $logger->addError('Error');
/** * @param Request $request Request object * @param Entity|null $user * * @return Response Reponse object * * @throws \Exception If unexpected exception is thrown */ public function dispatch(Request $request, Entity $user = null) : Response { $controllerFactory = new ControllerFactory($this->pdo, $this->configuration, $request, $user); /** * Figure out what controller to use and what action to call */ try { /** * @var Router $router */ $router = $this->configuration->get('Router'); list($controllerName, $action, $arguments) = array_values($router->route($request->getPath())); /** * Validate and initialize controller */ $controller = $controllerFactory->create($controllerName); } catch (RouteNonexistentException $e) { /** * Log nonexistent route (404) */ if ($this->logger) { $this->logger->addWarning('Route not connected', ['path' => $request->getPath()]); } $controller = $controllerFactory->create(NotFoundController::class); $action = 'index'; $arguments = []; } /** * Set arguments */ $controller->setArguments($arguments); /** * Validate and set controller action */ try { $controller->setAction($action); } catch (ControllerActionProtectedInsufficientAuthenticationException $e) { /** * Log unauthed protected controller action (403) */ if ($this->logger) { $this->logger->addWarning('Unauthenticated attempt to access protected action', ['path' => $request->getPath(), 'controller' => $controller->getShortName(), 'action' => $action]); } if ($this->configuration->exists('User.SignIn.Controller.Class') && $this->configuration->exists('User.SignIn.Controller.Action')) { /** * Save what controller and action was requested and then redirect to sign in form */ // @todo test that this works $request->getCookie()->set('SignIn.onSuccess.path', $request->getPath()); $controller = $controllerFactory->create($this->configuration->get('User.SignIn.Controller.Class')); $controller->setAction($this->configuration->get('User.SignIn.Controller.Action')); } else { $controller = $controllerFactory->create(NotFoundController::class); $controller->setAction('index'); } } catch (ControllerActionPrivateInsufficientAuthenticationException $e) { /** * Log unauthed private controller action (403) */ if ($this->logger) { $this->logger->addWarning('Unauthenticated attempt to access private action', ['path' => $request->getPath(), 'controller' => $controller->getShortName(), 'action' => $action]); } } /** * Create response from controller action headers and output */ $response = $controller->callAction(); /** * Performance logging */ if ($this->logger) { $time = number_format((microtime(true) - $_SERVER['REQUEST_TIME_FLOAT']) * 1000, 2); // @todo $_SERVER usage $this->logger->addDebug("Dispatched request in {$time} ms", ['path' => $request->getPath()]); } return $response; }