addInfo() public method

Adds a log record at the INFO level.
public addInfo ( string $message, array $context = [] ) : boolean
$message string The log message
$context array The log context
return boolean Whether the record has been processed
 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 Pantheon $community
  * @param OutputInterface    $output
  */
 private function updateCommunityDateStat(Pantheon $community, OutputInterface $output)
 {
     $this->logger->addInfo(sprintf('Update community "%s" with id %s', $community->getName(), $community->getId()));
     $today = new \DateTime('-4 hour');
     /** @var PantheonDateStat[] $communityDateStat */
     $communityDateStat = $community->getDateStat();
     if (count($communityDateStat) && $communityDateStat->first()->getDate()->format('Y:m:d') == $today->format('Y:m:d')) {
         $this->logger->addInfo(sprintf('Community "%s" with id %s already parsed today', $community->getName(), $community->getId()));
         return;
     }
     $aggregator = array('sumPrestige' => 0, 'maxPrestige' => 0, 'pveSumMobKills' => 0, 'pveSumBossKills' => 0, 'pveSumDeaths' => 0, 'pvpSumTime' => 0, 'pvpSumKills' => 0, 'pvpSumDeaths' => 0, 'pvpSumAssists' => 0);
     /** @var Player $member */
     foreach ($community->getMembers() as $member) {
         if (!count($member->getDateStat())) {
             continue;
         }
         /** @var PlayerDateStat $lastPlayerDateStat */
         $lastPlayerDateStat = $member->getDateStat()->first();
         $aggregator['sumPrestige'] += $lastPlayerDateStat->getMaxPrestige();
         $aggregator['maxPrestige'] = $aggregator['maxPrestige'] < $lastPlayerDateStat->getMaxPrestige() ? $lastPlayerDateStat->getMaxPrestige() : $aggregator['maxPrestige'];
         $aggregator['pvpSumTime'] += $lastPlayerDateStat->getPvpTime();
         //            $aggregator['pveSumTime'] += $lastPlayerDateStat->getPveTime();
         foreach ($member->getRoleStat() as $role) {
             $aggregator['pveSumMobKills'] += $role->getPveMobKills();
             $aggregator['pveSumBossKills'] += $role->getPveBossKills();
             $aggregator['pveSumDeaths'] += $role->getPveDeaths();
             $aggregator['pvpSumKills'] += $role->getPvpKills();
             $aggregator['pvpSumDeaths'] += $role->getPvpDeaths();
             $aggregator['pvpSumAssists'] += $role->getPvpAssists();
         }
     }
     $newPantheonDateStat = new PantheonDateStat();
     $newPantheonDateStat->setPantheon($community)->setDate($today)->setSumPrestige($aggregator['sumPrestige'])->setAvgPrestige(count($community->getMembers()) ? round($aggregator['sumPrestige'] / count($community->getMembers())) : 0)->setMembersCount(count($community->getMembers()))->setMaxPrestige($aggregator['maxPrestige'])->setPveSumMobKills($aggregator['pveSumMobKills'])->setPveSumBossKills($aggregator['pveSumBossKills'])->setPveSumDeaths($aggregator['pveSumDeaths'])->setPvpSumTime($aggregator['pvpSumTime'])->setPvpSumKills($aggregator['pvpSumKills'])->setPvpSumDeaths($aggregator['pvpSumDeaths'])->setPvpSumAssists($aggregator['pvpSumAssists']);
     $this->em->persist($newPantheonDateStat);
 }
 public function terminate($request, $response)
 {
     $log = new Logger('HTTP');
     $handler = new RotatingFileHandler(config('laravelmiddlewarelogger.options.file'), Logger::INFO);
     $handler->setFormatter(new LineFormatter("[%datetime%] %channel%.%level_name%: %message% %context%\n\n"));
     $log->pushHandler($handler);
     if (config('laravelmiddlewarelogger.options.enabled')) {
         $inputs = $request->input();
         if (!empty($inputs)) {
             $inputSafe = config('laravelmiddlewarelogger.options.input_safe');
             foreach ($inputSafe as $safe) {
                 if (!empty($inputs[$safe])) {
                     $inputs[$safe] = '[*** SENSOR ***]';
                 }
             }
         }
         $request_array = ['method' => $request->method(), 'full-url' => $request->fullUrl(), 'client-ip' => $request->ip(), 'user-agent' => $request->header('user-agent'), 'query-string' => $request->query(), 'inputs' => $inputs];
         $response_array = [];
         if (config('laravelmiddlewarelogger.options.log_response')) {
             $response_array = ['status' => $response->status(), 'content' => ''];
             json_decode($response->content());
             if (json_last_error() == JSON_ERROR_NONE) {
                 $response_array['content'] = $response->content();
             }
         }
         $log->addInfo('REQUEST', $request_array);
         $log->addInfo('RESPONSE', $response_array);
     }
 }
 /**
  * @param OutputInterface $output
  */
 private function findCommunities(OutputInterface $output)
 {
     $this->logger->addInfo('Finding new communities');
     $communities = array();
     try {
         for ($page = 1; $page <= 20; $page++) {
             $responseMessage = $this->parseService->getPage($this->makeCommunitiesMoreUrl(), true, $this->makeCommunitiesUrl(), array('t:zone' => 'bunchZone', 'bunchIndex' => $page));
             $response = json_decode($responseMessage);
             if (!$response) {
                 $this->logger->addInfo(sprintf('Empty page %s', $page));
                 break;
             }
             $pageCommunities = $this->parseService->getCommunities($response->content);
             $this->logger->addInfo(sprintf('Page %s parsed successful, get %s communities', $page, count($pageCommunities)));
             $communities = $communities + $pageCommunities;
             usleep(rand(500, 1500) * 1000);
         }
     } catch (RuntimeException $e) {
         $this->logger->addInfo('Exception: ' . $e->getMessage() . ' ' . $e->getCode());
     }
     foreach ($communities as $parsedCommunity) {
         $community = $this->pantheonRepository->find($parsedCommunity->id);
         if ($community) {
             continue;
         }
         $community = new Pantheon();
         $community->setId($parsedCommunity->id)->setImg($parsedCommunity->pic)->setName($parsedCommunity->name)->setIsActive(0)->setUpdatedAt(new DateTime());
         $this->em->persist($community);
     }
     $this->em->flush();
 }
 public function getLogger($message)
 {
     if ($this->logger == null) {
         $this->setLogger();
     }
     $this->logger->addInfo($message);
 }
Ejemplo n.º 6
0
 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);
     }
 }
Ejemplo n.º 7
0
 /**
  * {@inheritdoc}
  */
 public function onClose(ConnectionInterface $conn)
 {
     $this->_i--;
     if (null !== $this->_in) {
         $this->_in->addInfo('onClose', array('#open' => $this->_i, 'id' => $conn->resourceId));
     }
     $this->_component->onClose($conn);
 }
Ejemplo n.º 8
0
 /**
  * When a message appears, it checks the correlation_id property. If it
  * matches the value from the request it returns the response to the
  * application.
  *
  * @param AMQPMessage $rep
  */
 public function onResponse(AMQPMessage $rep)
 {
     $this->log->addInfo('Received response');
     if ($rep->get('correlation_id') == $this->corr_id) {
         $this->log->addInfo('Correlation id matches, setting response: ' . $rep->body);
         $this->response = $rep->body;
     }
 }
Ejemplo n.º 9
0
 /**
  * Handle login event.
  *
  * @param InteractiveLoginEvent $event
  */
 public function onSecurityInteractiveLogin(InteractiveLoginEvent $event)
 {
     /* @var BaseUser $user */
     $user = $event->getAuthenticationToken()->getUser();
     if ($user instanceof UserInterface) {
         $this->logger->addInfo($user . ' successfully logged in to the cms');
         $this->versionChecker->periodicallyCheck();
     }
 }
Ejemplo n.º 10
0
 /**
  * Sends an invoice generation task to the workers
  * 
  * @param int $invoiceNum
  */
 public function execute($invoiceNum)
 {
     $this->log->addInfo('Received invoice for processing: ' . $invoiceNum);
     $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
     $channel = $connection->channel();
     $channel->queue_declare('invoice_queue', false, true, false, false);
     $msg = new AMQPMessage($invoiceNum, array('delivery_mode' => 2));
     $channel->basic_publish($msg, '', 'invoice_queue');
     $this->log->addInfo('Published task to worker');
     $channel->close();
     $connection->close();
 }
Ejemplo n.º 11
0
 public function run()
 {
     $configFile = tempnam(sys_get_temp_dir(), 'satis-admin');
     file_put_contents($configFile, $this->manager->getJson());
     $process = ProcessBuilder::create(['php', $this->binDir . '/satis', 'build', $configFile, $this->outputDir])->getProcess();
     $this->logger->addInfo('Building config...', ['command-line' => $process->getCommandLine()]);
     if (0 === $process->run()) {
         $this->logger->addInfo('Config built.');
     } else {
         $this->logger->addError('Config not build', ['stdout' => $process->getOutput(), 'stderr' => $process->getErrorOutput()]);
     }
 }
Ejemplo n.º 12
0
 public function run()
 {
     $configFile = tempnam($this->cacheDir . '/satis', 'satis-admin');
     file_put_contents($configFile, $this->manager->getJson());
     $process = ProcessBuilder::create(['php', $this->binDir . '/satis', 'build', $configFile, $this->outputDir])->setTimeout(null)->addEnvironmentVariables(['HOME' => $this->cacheDir])->getProcess();
     $this->logger->addInfo('Building config...', ['command-line' => $process->getCommandLine()]);
     if (0 === $process->run()) {
         unlink($configFile);
         $this->logger->addInfo('Config built.');
     } else {
         $this->logger->addError('Config not build', ['stdout' => $process->getOutput(), 'stderr' => $process->getErrorOutput()]);
     }
 }
Ejemplo n.º 13
0
 /**
  * Sends a message to the pizzaTime queue.
  * 
  * @param string $message
  */
 public function execute($message)
 {
     $this->log->addInfo('Received message to send: ' . $message);
     $connection = new AMQPConnection('localhost', 5672, 'guest', 'guest');
     /** @var $channel AMQPChannel */
     $channel = $connection->channel();
     $channel->queue_declare('pizzaTime', false, false, false, false);
     $msg = new AMQPMessage($message);
     $channel->basic_publish($msg, '', 'pizzaTime');
     $this->log->addInfo('Message sent');
     $channel->close();
     $connection->close();
 }
 /**
  * Captura los eventos generados por las excepciones y
  * escribe en el fichero logs/excepciones.log información de cada una de ellas.
  * Responde al RF (58)(Configurar y registrar  datos  de las excepciones)
  *
  * @param GetResponseForExceptionEvent $event
  */
 public function onKernelException(GetResponseForExceptionEvent $event)
 {
     $exception = $event->getException();
     $logger = new Logger('excepciones');
     $stream = new StreamHandler($this->rootLogsDir . $this->fileName, Logger::DEBUG);
     $output = "[%datetime%]: %message% %context% \n";
     $stream->setFormatter(new ExcepcionesFormatter($output));
     $logger->pushHandler($stream);
     if ($exception instanceof LocalException) {
         $logger->addInfo("LocalException", array("codigo" => $exception->getCodigo(), "mensaje" => $exception->getMensaje(), "descripcion" => $exception->getDescripcion(), "clase" => $exception->getClase(), "linea" => $exception->getLinea(), "metodo" => $exception->getMetodo(), "traza" => $exception->getTraceAsString()));
     } else {
         $trazas = $exception->getTrace();
         $logger->addInfo(get_class($exception), array("codigo" => $exception->getCode(), "mensaje" => $exception->getMessage(), "clase" => $exception->getFile(), "linea" => $exception->getLine(), "metodo" => $trazas[0]['function'], "traza" => $exception->getTraceAsString()));
     }
 }
Ejemplo n.º 15
0
 public function actionUpdate($id, $hash)
 {
     $project = $this->projectFacade->find($id);
     $data = $this->getHttpRequest()->getRawBody();
     $verifyHash = hash_hmac('sha256', $data, $project->getKey());
     $messageData = unserialize($data);
     $this->logger->addInfo('importing ', $messageData);
     if ($hash === $verifyHash) {
         $imported = $this->projectFacade->importTemplate($messageData, $project);
         $this->sendResponse(new \Nette\Application\Responses\JsonResponse(['error' => 'false', 'message' => sprintf('OK. Imported %d messages.', $imported)]));
     } else {
         $this->sendResponse(new \Nette\Application\Responses\JsonResponse(['error' => 'true', 'message' => 'Bad request. Hash does not match.']));
     }
     $this->terminate();
 }
Ejemplo n.º 16
0
 /**
  * @param AfterbuyOrder $order
  *
  * @return array
  */
 public function createOrder(AfterbuyOrder $order)
 {
     $orderParams = $order->toArray();
     $this->logger->addInfo("\n\n" . date(DATE_RFC822) . "\nOrder ID: " . $order->getId());
     $this->logger->addInfo("\nItem to create: \n" . print_r($orderParams, true));
     $result = $this->afterbuyConnection->executeCommand('createOrder', $orderParams);
     if ($result['status'] == 'error') {
         $this->logger->addInfo("\n\nAfterbuy Response Data:\n" . $result['message']);
         return $result;
     }
     /** @var \SimpleXMLElement $xmlResponse */
     $xmlResponse = $result['message']->xml();
     $this->logger->addInfo("\n\nAfterbuy Response Data:\n" . $xmlResponse->asXML());
     return $this->getResponse($xmlResponse);
 }
 /**
  * Register the application services.
  *
  * @return void
  */
 public function register()
 {
     $configPath = __DIR__ . '/../config/sql-logging.php';
     $this->mergeConfigFrom($configPath, 'sql-logging');
     if (config('sql-logging.log', false)) {
         Event::listen('illuminate.query', function ($query, $bindings, $time) {
             $data = compact('bindings', 'time');
             // Format binding data for sql insertion
             foreach ($bindings as $i => $binding) {
                 if ($binding instanceof \DateTime) {
                     $bindings[$i] = $binding->format('\'Y-m-d H:i:s\'');
                 } else {
                     if (is_string($binding)) {
                         $bindings[$i] = "'{$binding}'";
                     }
                 }
             }
             // Insert bindings into query
             $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
             $query = vsprintf($query, $bindings);
             $log = new Logger('sql');
             $log->pushHandler(new StreamHandler(storage_path() . '/logs/sql-' . date('Y-m-d') . '.log', Logger::INFO));
             // add records to the log
             $log->addInfo($query, $data);
         });
     }
 }
 /**
  * Update an existing user
  *
  * @param int $id
  * @param HttpFoundation\Request $request
  * @return HttpFoundation\JsonResponse|HttpFoundation\Response
  */
 public function putIndex($id, HttpFoundation\Request $request)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'type' => 'request']);
     //If this request validated then the userId should be in the request.
     $userId = $request->request->get('userId');
     if ($userId === $id) {
         $user = $this->repo->getById($userId);
         $this->log->addDebug(print_r($user, true), ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'type' => 'user']);
         //It's almost impossible for this to happen but it's good defensive coding.
         if (!empty($user)) {
             $user = $this->converter->entityArrayToModel(json_decode($request->getContent(), true), new Models\User());
             $user->id = $userId;
             if (isset($user->password)) {
                 $user->password = password_hash($user->password, PASSWORD_DEFAULT);
             }
             if ($this->repo->save($user)) {
                 $this->log->addInfo('Updated user', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'user' => (array) $user]);
                 return new HttpFoundation\JsonResponse($user, 200);
             }
             //Otherwise we couldn't save the user for some reason
             $this->log->addWarning('Unable to update user', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'request' => $request->getContent(), 'user' => (array) $user]);
             return new HttpFoundation\Response('Bad Request', 400);
         }
     }
     //We didn't find a user to update.
     $this->log->addWarning('No user found', ['namespace' => 'HackTheDinos\\Controllers\\User', 'method' => 'putIndex', 'id' => $id, 'userId' => $userId]);
     return new HttpFoundation\Response('Not Found', 404);
 }
Ejemplo n.º 19
0
 public function getLegacyRoute($givenRoute)
 {
     try {
         $result = false;
         foreach ($this->routesCollection as $route) {
             if (!$result && (isset($route['legacy']) && $route['legacy'] == $givenRoute)) {
                 $result = true;
                 $controller = $route['controller'];
                 $class = explode('::', $controller)[0];
                 $method = explode('::', $controller)[1];
                 if (!class_exists($class)) {
                     throw new \Exception('Legacy The route class doesn\'t exist!');
                 } else {
                     if (!method_exists($class, $method)) {
                         throw new \Exception('Legacy The route class\'s method doesn\'t exist!');
                     }
                 }
                 $this->logger->addInfo("Legacy Route controller method found: {$class} -> {$method}");
                 $result = array('pattern' => $route['pattern'], 'class' => $class, 'method' => $method);
             }
         }
         if (!$result) {
             return null;
         } else {
             return $result;
         }
     } catch (\Exception $e) {
         $this->logger->addError('Error handling route: ' . $e->getMessage());
         throw new \Exception($e->getMessage(), $e->getCode(), $e->getPrevious());
     }
 }
Ejemplo n.º 20
0
 public function run()
 {
     $handle = fopen("/tmp/discord.db", "r+");
     flock($handle, LOCK_EX);
     $message = "";
     while ($row = fgets($handle)) {
         if (!empty($row)) {
             $row = str_replace("\n", "", str_replace("\r", "", str_replace("^@", "", $row)));
             if ($row == "" || $row == " ") {
                 continue;
             }
             $message .= $row . " | ";
         }
     }
     flock($handle, LOCK_UN);
     fclose($handle);
     $handle = fopen("/tmp/discord.db", "w+");
     fclose($handle);
     chmod("/tmp/discord.db", 0777);
     $data = null;
     $handle = null;
     clearstatcache();
     if (!empty($message)) {
         // Strip out the last |
         $message = trim(substr($message, 0, -2));
         $channelID = 154221481625124864;
         /** @var Channel $channel */
         $channel = Channel::find($channelID);
         $this->log->addInfo("Sending ping to #pings on The Culture");
         $channel->sendMessage("@everyone " . $message, false);
     }
 }
Ejemplo n.º 21
0
 /**
  * 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);
     }
 }
Ejemplo n.º 22
0
 public function testLogsFromListeners()
 {
     $output = new BufferedOutput();
     $output->setVerbosity(OutputInterface::VERBOSITY_DEBUG);
     $handler = new ConsoleHandler(null, false);
     $logger = new Logger('app');
     $logger->pushHandler($handler);
     $dispatcher = new EventDispatcher();
     $dispatcher->addListener(ConsoleEvents::COMMAND, function () use($logger) {
         $logger->addInfo('Before command message.');
     });
     $dispatcher->addListener(ConsoleEvents::TERMINATE, function () use($logger) {
         $logger->addInfo('Before terminate message.');
     });
     $dispatcher->addSubscriber($handler);
     $dispatcher->addListener(ConsoleEvents::COMMAND, function () use($logger) {
         $logger->addInfo('After command message.');
     });
     $dispatcher->addListener(ConsoleEvents::TERMINATE, function () use($logger) {
         $logger->addInfo('After terminate message.');
     });
     $event = new ConsoleCommandEvent(new Command('foo'), $this->getMock('Symfony\\Component\\Console\\Input\\InputInterface'), $output);
     $dispatcher->dispatch(ConsoleEvents::COMMAND, $event);
     $this->assertContains('Before command message.', $out = $output->fetch());
     $this->assertContains('After command message.', $out);
     $event = new ConsoleTerminateEvent(new Command('foo'), $this->getMock('Symfony\\Component\\Console\\Input\\InputInterface'), $output, 0);
     $dispatcher->dispatch(ConsoleEvents::TERMINATE, $event);
     $this->assertContains('Before terminate message.', $out = $output->fetch());
     $this->assertContains('After terminate message.', $out);
 }
Ejemplo n.º 23
0
 /**
  * @param InputInterface $input
  * @param OutputInterface $output
  * @return int|null|void
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $log = new Logger('dns-updater');
     $log->pushHandler(new StreamHandler(__DIR__ . '/application.log', Logger::INFO));
     if ($input->hasArgument('name') && !empty($input->getArgument('name'))) {
         $names = [$input->getArgument('name')];
     } else {
         $names = $this->getConfig('dns_records');
     }
     $externalIp = $this->getExternalIp();
     $output->writeln("<info>External IP queried: " . $externalIp . '</info>');
     if ($this->hasIpChanged($externalIp)) {
         $this->storeIp($externalIp);
         $output->writeln(sprintf('<info>External ip %s has been changed, starting dns update</info>', $externalIp));
         $log->addInfo(sprintf('External ip %s has been changed, starting dns update', $externalIp));
         foreach ($names as $name) {
             if (!empty($name)) {
                 $response = $this->removeDnsRecord($name);
                 if ($response) {
                     $output->writeln('<info>Removed dns record: ' . $name . '</info>');
                     $this->addDnsRecord($name, $externalIp);
                     if ($response) {
                         $output->writeln('<info>Added dns record: ' . $name . ' with ip ' . $externalIp . '</info>');
                     } else {
                         $output->writeln('<error>Error while removing dns record: ' . $name . '</error>');
                     }
                 } else {
                     $output->writeln('<error>Error while removing dns record: ' . $name . '</error>');
                 }
             }
         }
     } else {
         $output->writeln(sprintf("<info>External ip %s matches stored ip address %s, skipping dns update</info>", $externalIp, $this->getStoredIp()));
     }
 }
Ejemplo n.º 24
0
 /**
  * Отправляет сообщение в лог
  *
  * @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;
     }
 }
Ejemplo n.º 25
0
 public static function access($message, $context = array())
 {
     $logger = new Logger('api_log');
     $file = static::prepare('access');
     $logger->pushHandler(new StreamHandler($file, Logger::INFO));
     $logger->addInfo($message, $context);
 }
Ejemplo n.º 26
0
 public static function run()
 {
     echo "say hello on " . date('Y-m-d H:i:s');
     $log = new Logger('hello');
     $log->pushHandler(new StreamHandler('app.log', Logger::INFO));
     $log->addInfo("say hello on " . date('Y-m-d H:i:s'));
 }
Ejemplo n.º 27
0
 /**
  * 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;
     }
 }
Ejemplo n.º 28
0
 /**
  * Log a query in the connection's query log.
  *
  * @param  string  $query
  * @param  array   $bindings
  * @param  array   $called_at
  * @param  float|null  $time
  * @return void
  */
 public function logQuery($query, $bindings, $called_at, $time = null)
 {
     if (!$this->loggingQueries) {
         return;
     }
     $this->queryLog[] = $query_data = compact('query', 'bindings', 'called_at', 'time');
     //write the queries
     if ($this->writingQueries && $this->fileLogger != null) {
         if ($this->fillQueries) {
             // format the bindings for insertion
             foreach ($bindings as $key => $binding) {
                 if ($binding instanceof \DateTime) {
                     $bindings[$key] = $binding->format('\'Y-m-d H:i:s\'');
                 } else {
                     if (is_string($binding)) {
                         $bindings[$key] = "'{$binding}'";
                     }
                 }
             }
             // insert bindings into query
             $query = str_replace(array('%', '?'), array('%%', '%s'), $query);
             $query = vsprintf($query, $bindings);
         }
         if ($this->writingQueries) {
             // add the record to the query log
             $this->fileLogger->addInfo($query, $query_data);
         }
     }
 }
 /**
  * @param int $period
  * @return CommentBriefIndex
  */
 public function mine($period)
 {
     $fromDate = new \DateTime('-' . $period . ' hour');
     $this->logger->addInfo('Gather comments since ' . $fromDate->format('Y-m-d H:i:s'));
     $subscriptions = new CommentBriefIndex($this->ackService);
     $subscriptions->setLogger($this->logger);
     foreach ($this->miners as $miner) {
         $minerClass = get_class($miner);
         if (!$this->isMinerEnabled($minerClass)) {
             continue;
         }
         foreach ($miner->mine($fromDate, $period) as $element) {
             $subscriptions->add($minerClass, $element);
         }
     }
     return $subscriptions;
 }
 /**
  * @param $message
  * @param array $params
  * @param array $context
  * @return bool
  */
 protected function addInfoFile($message, $params = [], $context = [])
 {
     if (count($params)) {
         $this->logger->addInfo(vsprintf($message, $params), $context);
         return true;
     }
     $this->logger->addInfo($message, $context);
 }