public function process(AMQPMessage $message) { $handlers = $this->logger->getHandlers(); if (empty($handlers)) { throw new \Exception('No handlers registered'); } $this->logger->critical($message->body); $message->delivery_info['channel']->basic_ack($message->delivery_info['delivery_tag']); }
/** * @param Request $request * @param Response $response * @param \Exception $exception * @return Response */ public function __invoke(Request $request, Response $response, \Exception $exception) { $logMessage = $exception->getMessage() . ' in ' . $exception->getFile() . ':' . $exception->getLine(); // Log the message $this->logger->critical($logMessage); // create a JSON error string for the Response body $body = json_encode(['error' => $exception->getMessage(), 'code' => $exception->getCode()], JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES); return $response->withStatus(500)->withHeader('Content-type', 'application/json')->write($body); }
public function testLogsLevelAndLevelName() { $this->logger->debug('debug message'); $this->logger->critical('critical message'); $sql = 'SELECT * FROM logs WHERE level_name = \'%s\''; $debugLog = $this->pdo->query(sprintf($sql, 'DEBUG'))->fetch(); $criticalLog = $this->pdo->query(sprintf($sql, 'CRITICAL'))->fetch(); $this->assertNotEmpty($debugLog); $this->assertNotEmpty($criticalLog); $this->assertEquals($debugLog['message'], 'debug message'); $this->assertEquals($criticalLog['message'], 'critical message'); }
/** * Attempts to authenticate a TokenInterface object. * * @param TokenInterface $token The TokenInterface instance to authenticate * * @return TokenInterface An authenticated TokenInterface instance, never null * * @throws AuthenticationException if the authentication fails */ public function authenticate(TokenInterface $token) { /** @var SignedTokenInterface $token */ $user = $this->userProvider->loadUserByUsername($token->getUsername()); $signData = $this->getAuthSignData($token->getRequest()); $signData[] = $user->{$this->config['secret_getter']}(); $expectedSignature = hash($this->config['hash_alg'], implode($this->config['data_delimiter'], $signData)); if ($token->getSignature() == $expectedSignature) { $token->setUser($user); return $token; } $this->logger->critical(sprintf('Invalid auth signature. Expect "%s", got "%s"', $expectedSignature, $token->getSignature()), ['signData' => $signData]); throw new AuthenticationException("Invalid auth signature " . $token->getSignature()); }
public function critical($message, array $args = [], array $context = []) { if (count($args)) { $message = vsprintf($message, $args); } return parent::critical($message, $context); }
/** * @param $url * @param array $getData * @param array $postData * @param bool $addToken * @return mixed * @throws Exception */ public function operate($url, array $getData = [], array $postData = [], $addToken = true) { if (!is_string($url)) { $this->logger->critical('$url doit être une chaîne de caractères.'); if ($this->debug) { throw new Exception('$url doit être une chaîne de caractères.'); } } if (!is_array($getData)) { $this->logger->critical('$getData doit être un tableau.'); if ($this->debug) { throw new Exception('$getData doit être un tableau.'); } } if (!is_array($postData)) { $this->logger->critical('$postData doit être un tableau.'); if ($this->debug) { throw new Exception('$postData doit être un tableau.'); } } $this->buildURL($url, $getData, $postData, $addToken); $ch = curl_init(); curl_setopt_array($ch, array(CURLOPT_URL => $url, CURLOPT_RETURNTRANSFER => true, CURLINFO_HEADER_OUT => true, CURLOPT_HEADER => true)); if ($this->getAuthBasicUser() && $this->getAuthBasicPass()) { curl_setopt($ch, CURLOPT_USERPWD, $this->getAuthBasicUser() . ":" . $this->getAuthBasicPass()); } if (!empty($postData)) { curl_setopt_array($ch, array(CURLOPT_POST => true, CURLOPT_POSTFIELDS => json_encode($postData), CURLOPT_HTTPHEADER => array('Content-Type: application/json', 'Expect:'))); } // $res = explode("\r\n\r\n", curl_exec($ch)); $response = new Response(curl_exec($ch)); // $data = json_decode($res[1], true); $data = $response->getData(); $info = curl_getinfo($ch); $info = array('request' => array('url' => $info['url'], 'header' => curl_getinfo($ch, CURLINFO_HEADER_OUT), 'post_data' => json_encode($postData), 'content_type' => $info['content_type']), 'response' => array('header' => $response->headers->all(), 'http_code' => $info['http_code'], 'data' => $data)); $this->lastRequest = $info['request']; $this->lastResponse = $info['response']; if ($info['response']['http_code'] != '200') { $message = isset($data['exception']['message']) ? $data['exception']['message'] : "CURL Request failed: " . $url; $code = isset($data['exception']['code']) ? $data['exception']['code'] : 0; $this->logger->critical($message); if ($this->debug) { // dump($info); curl_close($ch); throw new Exception($message, $code); } } // Actuellement les contrôleurs s'attendent à ce que la propriété 'error' contienne le message d'erreur // et que la propriété 'code' contienne le code de l'exception. if (isset($data['exception'])) { if (!isset($data['error'])) { $data['error'] = $data['exception']['message']; } if (!isset($data['code'])) { $data['code'] = $data['exception']['code']; } } curl_close($ch); return $data; }
protected function callAsync($function, array $data, $log = false) { if (strtolower($function) == 'login') { $this->wrapperLog->error('Login can not be called asynchronously!'); throw new APIException('Login can not be called asynchronously!'); } if (!empty($this->hash)) { $data['hash'] = $this->hash; } $socket = fsockopen(parse_url($this->apiAddress, PHP_URL_HOST), 80, $errno, $errstr); if ($socket === false) { $this->wrapperLog->critical('Error while opening asynchronous socket: ' . $errstr, array('code' => $errno)); throw new ConnectionException('Error while opening asynchronous socket: ' . $errstr, $errno); } $data = 'data=' . urlencode(json_encode($data)); $msg = 'POST /' . $this->qbankAddress . '/' . $function . ' HTTP/1.1' . "\r\n"; $msg .= 'Host:' . parse_url($this->apiAddress, PHP_URL_HOST) . "\r\n"; $msg .= 'Content-type: application/x-www-form-urlencoded' . "\r\n"; $msg .= 'Content-length: ' . strlen($data) . "\r\n"; $msg .= 'Connection: Close' . "\r\n\r\n"; $msg .= $data; $result = fwrite($socket, $msg); if ($result === false) { $this->wrapperLog->critical('Error while writing to asycnhronous socket!'); throw new ConnectionException('Error while writing to asycnhronous socket!'); } @fclose($socket); }
/** * */ public function testPushErrors() { $redis = \Mockery::mock('Predis\\Client')->shouldReceive('publish')->times(8)->with('log', \Mockery::any())->mock(); $monolog = new Logger('test'); $monolog->pushHandler(new PublishHandler(new RedisPublisher($redis))); $monolog->debug('the message was: {message}', ['DEBUG!']); $monolog->info('the message was: {message}', ['INFO!']); $monolog->notice('the message was: {message}', ['NOTICE!']); $monolog->warning('the message was: {message}', ['WARNING!']); $monolog->error('the message was: {message}', ['ERROR!']); $monolog->critical('the message was: {message}', ['CRITICAL!']); $monolog->alert('the message was: {message}', ['ALERT!']); $monolog->emergency('the message was: {message}', ['EMERGENCY!']); }
public function testMonologPublishesMessageToKafkaBroker() { $producerTopic = $this->buildProducerTopic(); $handler = new KafkaHandler($producerTopic); $handler->setFormatter(new LineFormatter('%message%')); $monolog = new Logger('kafka-logger'); $monolog->pushHandler($handler); $monolog->critical(self::MESSAGE); sleep(2); $consumerTopic = $this->buildConsumerTopic(); $consumerTopic->consumeStart(self::PARTITION, rd_kafka_offset_tail(1)); $message = $consumerTopic->consume(self::PARTITION, 1000); $consumerTopic->consumeStop(self::PARTITION); $this->assertEquals(self::MESSAGE, $message->payload); }
/** * Respond to an exception with an error document wrapped in a Response. * * @param GetResponseForExceptionEvent $event */ public function onKernelException(GetResponseForExceptionEvent $event) { $exception = $event->getException(); // only intercept SwordController exceptions. if (!$this->controller[0] instanceof SwordController) { return; } if (!$exception instanceof SwordException) { return; } $this->logger->critical($exception->getMessage() . ' from ' . $this->requestStack->getCurrentRequest()->getClientIp()); $response = $this->templating->renderResponse('AppBundle:Sword:error.xml.twig', array('error' => $exception)); $response->headers->set('Content-Type', 'text/xml'); $response->setStatusCode($exception->getStatusCode()); $event->setResponse($response); }
/** * Critical conditions. * * Example: Application component unavailable, unexpected exception. * * @param string $message * @param array $context * @return null */ public function critical($message, array $context = array()) { $this->logger->critical($message, $context); }
/** * Critical conditions. * * Example: Application component unavailable, unexpected exception. * * @param string $message * @param array $params * @param array $context * @return null */ public function critical($message, array $params = array(), array $context = array()) { $logMessage = $this->createMessage($message, $params); $this->logger->critical($logMessage, $context); }
/** * Constructor method * * Prepare extender environment, do checks and fire extender.ready event */ public final function __construct() { // check if extender is running from cli if (Checks::cli() === false) { echo "Extender runs only in php-cli, exiting"; self::end(1); } // setup default timezone (in daemon mode, timezone warning may break extender) $default_timezone = ini_get('date.timezone'); if (empty($default_timezone)) { date_default_timezone_set(defined('EXTENDER_TIMEZONE') ? EXTENDER_TIMEZONE : 'Europe/Rome'); } $this->timestamp_absolute = microtime(true); $this->color = new Console_Color2(); // get command line options (vsdh) list($this->verbose_mode, $this->debug_mode, $this->summary_mode, $this->daemon_mode, $help_mode) = self::getCommandlineOptions(); if ($help_mode) { self::showHelp($this->color); self::end(0); } $this->logger = ExtenderLogger::create($this->verbose_mode, $this->debug_mode); // do checks $check_constants = Checks::constants(); if ($check_constants !== true) { $this->logger->critical($check_constants); self::end(1); } if (Checks::signals() === false and $this->daemon_mode) { $this->logger->critical("Extender cannot run in daemon mode without PHP Process Control Extensions"); self::end(1); } if (Checks::database() === false) { $this->logger->critical("Extender database not available, exiting"); self::end(1); } $this->tasks = TasksTable::load($this->logger); $this->events = Events::load($this->logger); // setup extender parameters $this->max_result_bytes_in_multithread = defined('EXTENDER_MAX_RESULT_BYTES') ? filter_var(EXTENDER_MAX_RESULT_BYTES, FILTER_VALIDATE_INT) : 2048; $this->max_childs_runtime = defined('EXTENDER_MAX_CHILDS_RUNTIME') ? filter_var(EXTENDER_MAX_CHILDS_RUNTIME, FILTER_VALIDATE_INT) : 600; $this->multithread_mode = defined('EXTENDER_MULTITHREAD_ENABLED') ? filter_var(EXTENDER_MULTITHREAD_ENABLED, FILTER_VALIDATE_BOOLEAN) : false; // if in daemon mode, remember parent pid, setup lock and register signal handlers if ($this->daemon_mode) { $this->parent_pid = posix_getpid(); Lock::register($this->parent_pid); $this->adjustNiceness(); if (Checks::signals()) { $this->registerSignals(); } } // init the runner $this->runner = new JobsRunner($this->logger, $this->getMultithreadMode(), $this->max_result_bytes_in_multithread, $this->max_childs_runtime); $this->logger->notice("Extender ready"); // store initial status and queue information Status::dump($this->timestamp_absolute, $this->parent_pid, $this->completed_processes, $this->failed_processes, $this->paused); Queue::dump(0, 0); // we are ready to go! }
/** * @inheritdoc * @return boolean Whether the record has been processed. */ public function critical($message, array $context = []) { return $this->_monolog->critical($message, $context); }
public function initAdapted(\GearmanJob $job) { $this->loop = Factory::create(); $this->read = new \React\Stream\Stream(STDIN, $this->loop); $this->read->bufferSize = 8192; $this->write = new \React\Stream\Stream(STDOUT, $this->loop); $this->write->bufferSize = 8192; $this->job = $job; //protect from repeated execution $initStart = false; $pmErrorDtoAlreadySent = false; /** * Receive sockets params json from PM to set it into performer */ $this->read->on('data', function ($data) use($initStart, $pmErrorDtoAlreadySent) { if (!is_array($this->pmWorkerDta)) { $this->pmWorkerDta = @json_decode($data, true); if ($this->pmWorkerDta !== false && is_array($this->pmWorkerDta)) { if ($initStart === false) { $initStart = true; try { $this->initBasicParams(); $this->adaptedService->getTerminatorPauseStander()->setPublisherPmSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PM]); $this->adaptedService->getTerminatorPauseStander()->setUSleepTime(5000000); $performerSocketParams = new PerformerSocketsParamsDto(); $performerSocketParams->setRequestPulsarRsSocketAddress($this->pmWorkerDta[DataTransferConstants::REQUEST_PULSAR_RS]); $performerSocketParams->setPublisherPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUBLISHER_PULSAR]); $performerSocketParams->setPushPulsarSocketAddress($this->pmWorkerDta[DataTransferConstants::PUSH_PULSAR]); $this->adaptedService->getZmqPerformer()->setSocketsParams($performerSocketParams); $this->adaptedService->getZmqPerformer()->setLogger($this->logger); $this->adaptedService->serviceExec(); $this->adaptedService->getExecutionDto()->setExecutionMessage($this->adaptedService->getParams()); $this->job->sendComplete(serialize($this->adaptedService->getExecutionDto())); $this->jobInfoWasSent = true; $this->logger->critical("Job complete was sent."); } catch (\Exception $e) { $errorMsg = "Adapter die in Exception with \$e: " . $e->getMessage() . "|params: " . serialize($this->adaptedService->getParams()); //. $e->getTraceAsString(); $this->logger->critical($errorMsg . " | " . serialize($this->pmWorkerDta)); $this->job->sendComplete(serialize(InspectionHelper::prepareErrorExecutionDto($this->adaptedService->getTaskId(), $errorMsg))); $this->jobInfoWasSent = true; $this->logger->critical("Job complete with exception was sent."); die; } $this->loop->nextTick(function () { $this->loop->stop(); }); } } else { if ($pmErrorDtoAlreadySent === false) { $pmErrorDtoAlreadySent = true; $pmErrorArr = []; $pmErrorArr[DataTransferConstants::ERROR_LEVEL] = ErrorsConstants::CRITICAL; $pmErrorArr[DataTransferConstants::ERROR_REASON] = PmErrorConstants::WORKER_NOT_RECEIVE_CORRECT_DTO; $pmErrorArr[DataTransferConstants::ERROR_ELEMENT] = $this->pmWorkerDta; //write to PM's allotted STDIN about critical error $this->write->write(json_encode($pmErrorArr)); $this->loop->nextTick(function () { $this->loop->stop(); }); } } } }); $timerIteration = 0; $this->loop->addPeriodicTimer(3, function (Timer $timer) use(&$timerIteration) { if ($this->pmWorkerDta === null) { if ($timerIteration > $this->maxTimerIteration) { $this->initBasicParams(); die; } $timerIteration++; } else { $timer->cancel(); } }); $this->loop->run(); if ($pmErrorDtoAlreadySent) { die; } }
/** * @param string $slug * @param string $repo * @param string $ref * * @return array */ public function processRequest($slug, $repo, $ref) { $this->log->info("Processing request with slug={$slug}, repo={$repo}, ref={$ref}"); $pullRequests = $this->stash->getPullRequestsByBranch($slug, $repo, $ref); $this->log->info("Found {$pullRequests['size']} pull requests"); foreach ($pullRequests['values'] as $pullRequest) { $this->log->info("Processing pull request #{$pullRequest['id']} {$pullRequest['fromRef']['latestCommit']}..{$pullRequest['toRef']['latestCommit']}"); $result = []; try { if ($this->stash->getUserName() != $pullRequest['author']['user']['name']) { $this->stash->addMeToPullRequestReviewers($slug, $repo, $pullRequest['id']); } $changes = $this->stash->getPullRequestDiffs($slug, $repo, $pullRequest['id'], 0); foreach ($changes['diffs'] as $diff) { $comments = []; // файл был удален, нечего проверять if ($diff['destination'] === null) { $this->log->info("Skip processing {$diff['source']['toString']}, as it was removed"); continue; } $filename = $diff['destination']['toString']; $extension = $diff['destination']['extension']; $this->log->info("Processing file {$filename}"); if ($this->checker->shouldIgnoreFile($filename, $extension, "./")) { $this->log->info("File is in ignore list, so no errors can be found"); $errors = []; } else { $affectedLines = []; foreach ($diff['hunks'] as $hunk) { foreach ($hunk['segments'] as $segment) { if ($segment['type'] == 'CONTEXT' || $segment['type'] == 'REMOVED') { continue; } foreach ($segment['lines'] as $line) { $affectedLines[$line['destination']] = true; } } } $this->log->info("Affected lines: " . $this->visualizeNumbersToInterval(array_keys($affectedLines))); try { $fileContent = $this->stash->getFileContent($slug, $repo, $pullRequest['id'], $filename); } catch (StashFileInConflict $e) { $this->log->error("File {$filename} at pull request #{$pullRequest['id']} os in conflict state, skip code style checking"); continue; } catch (StashJsonFailure $e) { $this->log->error("Can't get contents of {$filename} at pull request #{$pullRequest['id']}"); continue; } $this->log->debug("File content length: " . mb_strlen($fileContent)); $errors = $this->checker->processFile($filename, $extension, $fileContent); $this->log->info("Summary errors count: " . count($errors)); } foreach ($errors as $line => $data) { if (!isset($affectedLines[$line])) { continue; } if (!isset($comments[$line])) { $comments[$line] = []; } foreach ($data as $column => $errors) { foreach ($errors as $error) { $comments[$line][] = "{$error['message']}\n"; } } } $comments = array_map(function ($val) { return implode("\n", array_unique($val)); }, $comments); foreach ($comments as $line => $comment) { $result[$filename][$line] = $comment; } $this->log->info("Summary errors count after filtration: " . count($comments)); $existingComments = $this->stash->getPullRequestComments($slug, $repo, $pullRequest['id'], $filename)['values']; $this->log->info("Found " . count($existingComments) . " comment at this pull request"); foreach ($existingComments as $comment) { if ($comment['author']['name'] == $this->stash->getUserName()) { if (!isset($comments[$comment['anchor']['line']])) { // Comment exist at remote and not exists now, so remove it $this->log->info("Deleting comment #{$comment['id']}", ['line' => $comment['anchor']['line'], 'file' => $filename]); if (empty($comment['comments'])) { $this->stash->deletePullRequestComment($slug, $repo, $pullRequest['id'], $comment['version'], $comment['id']); } else { //If there are replies to our comment - just strike through our message //@see https://confluence.atlassian.com/display/STASH0310/Markdown+syntax+guide#Markdownsyntaxguide-Characterstyles $this->stash->updatePullRequestComment($slug, $repo, $pullRequest['id'], $comment['id'], $comment['version'], preg_replace("/^([^~]+)/s", "~~\$1", $comment["text"])); } } elseif (trim($comment['text']) != trim($comments[$comment['anchor']['line']])) { // Comment exist at remote and exists now, but text are different - so modify remote text $this->log->info("Updating comment #{$comment['id']}", ['line' => $comment['anchor']['line'], 'file' => $filename, 'newText' => $comments[$comment['anchor']['line']], 'oldText' => $comment['text']]); $this->stash->updatePullRequestComment($slug, $repo, $pullRequest['id'], $comment['id'], $comment['version'], $comments[$comment['anchor']['line']]); } unset($comments[$comment['anchor']['line']]); } } foreach ($comments as $line => $comment) { $this->log->info("Adding comment to line={$line}, file={$filename}", ['line' => $comment, 'file' => $comment, 'text' => $comment]); $this->stash->addPullRequestComment($slug, $repo, $pullRequest['id'], $filename, $line, $comment); } } $activities = $this->stash->getPullRequestActivities($slug, $repo, $pullRequest['id'])['values']; foreach ($activities as $activity) { if ($activity['action'] != 'COMMENTED' || $activity['commentAction'] != 'ADDED') { continue; } if (empty($activity['commentAnchor'])) { continue; } if (!$activity['commentAnchor']['orphaned']) { $this->log->debug("Skip activity #{$activity['id']} as not orphaned"); continue; } if ($activity['user']['name'] != $this->stash->getUserName()) { continue; } if (empty($activity['comment']['id'])) { $this->log->info("Cannot delete activity #{$activity['id']} as comment id not found"); continue; } if (empty($activity['comment']['comments'])) { $this->stash->deletePullRequestComment($slug, $repo, $pullRequest['id'], $activity['comment']['version'], $activity['comment']['id']); $this->log->debug("Delete activity #{$activity['id']} (commentId {$activity['comment']['id']}) as orphaned"); } else { //If there are replies to our comment - just strike through our message //@see https://confluence.atlassian.com/display/STASH0310/Markdown+syntax+guide#Markdownsyntaxguide-Characterstyles $this->stash->updatePullRequestComment($slug, $repo, $pullRequest['id'], $activity['comment']['id'], $activity['comment']['version'], preg_replace("/^([^~]+)/s", "~~\$1", $activity['comment']["text"])); } } if (!$result) { $this->stash->approvePullRequest($slug, $repo, $pullRequest['id']); $this->log->info("Approved pull request #{$pullRequest['id']}"); } else { $this->stash->unapprovePullRequest($slug, $repo, $pullRequest['id']); } return $result; } catch (ClientException $e) { $this->log->critical("Error integration with stash: " . $e->getMessage(), ['type' => 'client', 'reply' => (string) $e->getResponse()->getBody(), 'headers' => $e->getResponse()->getHeaders()]); } catch (ServerException $e) { $this->log->critical("Error integration with stash: " . $e->getMessage(), ['type' => 'server', 'reply' => (string) $e->getResponse()->getBody(), 'headers' => $e->getResponse()->getHeaders()]); } catch (StashJsonFailure $e) { $this->log->error("Json failure at pull request #{$pullRequest['id']}: " . $e->getMessage()); } } // No pull requests found, so no errors return []; }
public function testLogMessage() { $this->producerTopic->shouldReceive('produce')->with(RD_KAFKA_PARTITION_UA, 0, json_encode(['event' => 'critical alert']))->once(); $this->monolog->critical(json_encode(['event' => 'critical alert'])); }
<?php // Use Composer autoloader require 'vendor/autoload.php'; // Import Monolog namespaces use Monolog\Logger; use Monolog\Handler\StreamHandler; use Monolog\Handler\SwiftMailerHandler; date_default_timezone_set('America/New_York'); // Setup Monolog and basic handler $log = new Logger('my-app-name'); $log->pushHandler(new StreamHandler('logs/production.log', Logger::WARNING)); // Add SwiftMailer handler for critical errors $transport = \Swift_SmtpTransport::newInstance('smtp.example.com', 587)->setUsername('USERNAME')->setPassword('PASSWORD'); $mailer = \Swift_Mailer::newInstance($transport); $message = \Swift_Message::newInstance()->setSubject('Website error!')->setFrom(array('*****@*****.**' => 'John Doe'))->setTo(array('*****@*****.**')); $log->pushHandler(new SwiftMailerHandler($mailer, $message, Logger::CRITICAL)); // Use logger $log->critical('The server is on fire!');
protected function logMessage($message, array $context = array(), $severity) { $adminLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/admin_level'); $systemLogLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/system_level'); $emailLevel = $this->helper->getConfigValue('shqlogmenu/shqlogger/email_level'); if ($adminLevel > 0 && $adminLevel >= $severity) { $this->logAdmin($message, $context, $severity); } if ($systemLogLevel > 0 && $systemLogLevel >= $severity) { $message = is_string($message) ? $message : var_export($message, true); switch ($severity) { case self::SEVERITY_NOTICE: parent::debug($message, $context); break; case self::SEVERITY_MINOR: parent::notice($message, $context); break; case self::SEVERITY_MAJOR: parent::warning($message, $context); break; case self::SEVERITY_CRITICAL: parent::critical($message, $context); break; } } if ($emailLevel > 0 && $emailLevel >= $severity) { $this->logEmail($message, $context, $severity); } return true; }
<?php include 'basics.php'; use unreal4u\MonologHandler; use unreal4u\TgLog; use Monolog\Logger; #$monologTgLogger = new MonologHandler(new TelegramLog(BOT_TOKEN), A_USER_CHAT_ID, Logger::DEBUG); // Sends from DEBUG+ $monologTgLogger = new MonologHandler(new TgLog(BOT_TOKEN), A_USER_CHAT_ID, Logger::ERROR); // Sends ERROR+ //Create logger $logger = new Logger('TelegramLogger'); $logger->pushHandler($monologTgLogger); //Now you can use the logger, and further attach additional information $logger->debug('Nobody gives a dime for debug messages', ['moreInfo' => 'Within here']); $logger->info('A user has logged in'); $logger->notice('Something unusual has happened!', ['it did indeed']); $logger->warning('Somebody should attend this', ['some', 'extra' => 'information']); $logger->error('Something really bad happened'); $logger->critical('A critical message', ['please' => 'Check this out']); $logger->alert('This is an alert', ['oh no...' => 'This might be urgent']); $logger->emergency('Run for your lives!', ['this is it' => 'everything has stopped working']);
/** * Send a deposit to LOM via HTTP. * * @param Deposit $deposit * * @return bool true on success */ public function createDeposit(Deposit $deposit) { $this->serviceDocument($deposit->getJournal()); $xml = $this->templating->render('AppBundle:SwordClient:deposit.xml.twig', array('title' => 'Deposit from OJS part ' . $deposit->getAuContainer()->getId(), 'publisher' => 'Public Knowledge Project Staging Server', 'deposit' => $deposit, 'baseUri' => $this->router->generate('home', array(), UrlGeneratorInterface::ABSOLUTE_URL), 'plnJournalTitle' => $this->plnJournalTitle)); if ($this->saveDepositXml) { $atomPath = $this->filePaths->getStagingDir($deposit->getJournal()) . '/' . $deposit->getDepositUuid() . '.xml'; file_put_contents($atomPath, $xml); } try { $client = $this->getClient(); $request = $client->createRequest('POST', $this->colIri); $request->setBody(Stream::factory($xml)); $response = $client->send($request); $responseXml = new SimpleXMLElement($response->getBody()); } catch (RequestException $e) { $this->logger->critical($e->getMessage()); if ($e->hasResponse()) { $xml = $e->getResponse()->xml(); $xml->registerXPathNamespace('atom', 'http://www.w3.org/2005/Atom'); $xml->registerXPathNamespace('sword', 'http://purl.org/net/sword/'); $this->logger->critical('Summary: ' . (string) $xml->xpath('//atom:summary')[0]); $this->logger->warning('Detail: ' . (string) $xml->xpath('//sword:verboseDescription')[0]); } return false; } catch (Exception $e) { $this->logger->critical("Error parsing deposit response from server: {$e->getMessage()}"); return false; } $deposit->setDepositReceipt($response->getHeader('Location')); $deposit->setDepositDate(new DateTime()); // TODO should I do something wtih responseXML here? $this->namespaces->registerNamespaces($responseXml); return true; }
/** * @param string $message * @param array $context * @return bool */ public function critical($message, array $context = array()) { return parent::critical($message, $context); }
require_once $CFG->dirroot . '/local/strathjiscla/vendor/autoload.php'; require_once $CFG->dirroot . '/mod/assign/locallib.php'; $endpoint = 'http://localhost/learninglocker/public/data/xAPI/'; $version = '1.0.1'; $username = '******'; $password = '******'; $batchsize = 20; /** * @var LoggerInterface */ $log = new Logger('core'); $lrs = new RemoteLRS($endpoint, $version, $username, $password); // Check connection $about = $lrs->about(); if (!$about->success) { $log->critical("Unable to connect to server"); exit; } $log->debug("xAPI versions: " . implode(', ', $about->content->getVersion())); // Can't use autoloading on old Moodle versions class BatchController extends xapi_controller { /** * Creates a new event. * @param [String => Mixed] $opts * @return [String => Mixed] */ public function createEvent(array $opts) { $route = isset($opts['recipe']) ? $opts['recipe'] : ''; if (isset(static::$routes[$route])) {
/** * Adds a log record at the CRITICAL level. * * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function critical($message, $context = array()) { return \Monolog\Logger::critical($message, $context); }
/** * @param ServerRequestInterface $request * @param ResponseInterface $response * @param \Exception $exception * * @return \Psr\Http\Message\ResponseInterface */ public function __invoke(ServerRequestInterface $request, ResponseInterface $response, \Exception $exception) { // Log the message $this->logger->critical($exception->getMessage()); return $this->view->render($response, 'errors/500.twig')->withStatus(500); }