addAlert() public method

Adds a log record at the ALERT level.
public addAlert ( string $message, array $context = [] ) : boolean
$message string The log message
$context array The log context
return boolean Whether the record has been processed
Beispiel #1
1
 /**
  * Create a new connection to the database
  *
  * @param string $host     The MySQL host
  * @param string $user     The MySQL user
  * @param string $password The MySQL password for the user
  * @param string $dbName   The MySQL database name
  *
  * @return Database A database object to interact with the database
  */
 public function __construct($host, $user, $password, $dbName)
 {
     if (Service::getContainer()) {
         if ($logger = Service::getContainer()->get('monolog.logger.mysql')) {
             $this->logger = $logger;
         }
     }
     $this->dbc = new mysqli($host, $user, $password, $dbName);
     if ($this->dbc->connect_errno) {
         $this->logger->addAlert($this->dbc->connect_error);
         throw new Exception($this->dbc->connect_error, $this->dbc->connect_errno);
     }
     $this->dbc->set_charset("utf8");
 }
Beispiel #2
0
 /**
  * Create a new connection to the database
  *
  * @param string $host     The MySQL host
  * @param string $user     The MySQL user
  * @param string $password The MySQL password for the user
  * @param string $dbName   The MySQL database name
  */
 public function __construct($host, $user, $password, $dbName)
 {
     if (Service::getContainer()) {
         if ($logger = Service::getContainer()->get('monolog.logger.mysql')) {
             $this->logger = $logger;
         }
     }
     try {
         // TODO: Persist
         $this->dbc = new PDO('mysql:host=' . $host . ';dbname=' . $dbName . ';charset=utf8', $user, $password, array(PDO::ATTR_ERRMODE => PDO::ERRMODE_EXCEPTION, PDO::ATTR_EMULATE_PREPARES => false));
     } catch (PDOException $e) {
         $this->logger->addAlert($e->getMessage());
         throw new Exception($e->getMessage(), $e->getCode());
     }
 }
Beispiel #3
0
 public function fillParentTables(&$schemas)
 {
     $this->em->clear();
     //Inherit
     $sql = "WITH RECURSIVE inh AS (\n                   SELECT i.inhrelid, i.inhparent\n                   FROM pg_catalog.pg_inherits i\n                   UNION\n                   SELECT i.inhrelid, inh.inhparent\n                   FROM inh INNER JOIN pg_catalog.pg_inherits i ON (inh.inhrelid = i.inhparent)\n            )\n            SELECT n.nspname as schema,\n                   c.oid,\n                   c.oid::pg_catalog.regclass as name,\n                   c.relname as table_name,\n                   --c2.relname as parent_name,\n                   c2.oid as table\n            FROM inh\n                   INNER JOIN pg_catalog.pg_class c ON (inh.inhrelid = c.oid)\n                   INNER JOIN pg_catalog.pg_namespace n ON (c.relnamespace = n.oid)\n                   INNER JOIN pg_catalog.pg_class c2 ON (inh.inhparent = c2.oid)\n           WHERE n.nspname <> 'pg_catalog'\n               AND n.nspname <> 'information_schema'\n               AND n.nspname !~ '^pg_toast'\n               AND n.nspname !~ '^pg_temp'\n               AND n.nspname <> 'londiste'\n               AND n.nspname <> 'pgq'";
     $rsm = new ResultSetMapping();
     $rsm->addScalarResult('oid', 'oid');
     $rsm->addScalarResult('name', 'name');
     $rsm->addScalarResult('schema', 'schema');
     $rsm->addScalarResult('table', 'table');
     $rsm->addScalarResult('table_name', 'table_name');
     $stmt = $this->em->createNativeQuery($sql, $rsm);
     $stmt->useResultCache(true, PgRetriever::CACHE_LIFETIME);
     foreach ($stmt->getResult(AbstractQuery::HYDRATE_ARRAY) as $row) {
         $child = new ParentTable($row['schema'], $row['table']);
         foreach ($row as $key => $value) {
             $child->__set($key, $value);
         }
         try {
             if ($this->index_type == PgRetriever::INDEX_TYPE_OID) {
                 $schemas[$row['schema']]->addTableParentTable($row['oid'], $child);
             } elseif ($this->index_type == PgRetriever::INDEX_TYPE_NAME) {
                 $schemas[$row['schema']]->addTableParentTable($row['table_name'], $child);
             }
         } catch (\Exception $e) {
             $this->logger->addAlert($e->getMessage() . ' ' . json_encode($row), $e->getTrace());
         }
         unset($child);
     }
     unset($stmt);
 }
 /**
  * Отправляет сообщение в лог
  *
  * @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;
     }
 }
Beispiel #5
0
 /**
  * Build from a live endpoint
  * @param string Swagger compliant JSON endpoint for resource listing
  * @throws \Exception
  * @return Swizzle
  */
 public function build($base_url)
 {
     $this->service = null;
     $client = SwaggerClient::factory(compact('base_url'));
     $this->debug('pulling resource listing from %s', $base_url);
     /* @var $listing ResourceListing */
     $listing = $client->getResources();
     // check this looks like a resource listing
     if (!$listing->isSwagger()) {
         throw new \Exception("This doesn't look like a Swagger spec");
     }
     if (!$listing->getApis()) {
         $this->logger->addAlert("Resource listing doesn't define any APIs");
     }
     // check swagger version
     if (self::SWAGGER_VERSION !== $listing->getSwaggerVersion()) {
         throw new \Exception('Unsupported Swagger version, Swizzle expects ' . self::SWAGGER_VERSION);
     }
     // Declared version overrides anything we've set
     if ($version = $listing->getApiVersion()) {
         $this->debug('+ set apiVersion %s', $version);
         $this->setApiVersion($version);
     }
     // Set description if missing from constructor
     if (!$this->init['description']) {
         $info = $listing->getInfo();
         $this->init['description'] = $info['description'] ?: $this->init['title'];
     }
     // no more configs allowed now, Guzzle service gets constructed
     $service = $this->getServiceDescription();
     // set base path from docs location if not provided
     if (!$service->getBaseUrl()) {
         $service->setBaseUrl(self::mergeUrl('/', $base_url));
     }
     // ready to pull each api declaration
     foreach ($listing->getApiPaths() as $path) {
         if ($this->delay) {
             usleep($this->delay);
         }
         // @todo do proper path resolution here, allowing a cross-domain spec.
         $path = trim($path, '/ ');
         $this->debug('pulling /%s ...', $path);
         $declaration = $client->getDeclaration(compact('path'));
         foreach ($declaration->getModels() as $model) {
             $this->addModel($model);
         }
         // Ensure a fully qualified base url for this api
         $baseUrl = self::mergeUrl($declaration->getBasePath(), $service->getBaseUrl());
         // add each api against required base url
         foreach ($declaration->getApis() as $api) {
             $this->addApi($api, $baseUrl);
         }
     }
     $this->debug('finished');
     return $this;
 }
Beispiel #6
0
 /**
  * @param $to
  * @return array
  */
 public function sendVerificationEmail($to, $first_name, $last_name, $verificationKey)
 {
     $verifyUrl = "http://recipes.personal/verify/" . $verificationKey;
     /* EMAIL BODY CONTENT */
     $html = '<!DOCTYPE HTML>' . '<head>' . '<meta http-equiv="content-type" content="text/html">' . '<title>Verification Required</title>' . '</head>' . '<body>' . '<div id="header" style="width: 80%; height: 60px; margin: 0 auto; padding: 10px; color: #fff; text-align: center; background-color: #E0E0E0; font-family: Open Sans,Arial,sans-serif;">' . '<img height="50" width="220" style="border-width:0" src="" alt="Image Description" title="Image Title">' . '</div>' . '<div id="outer" style="width: 80%; margin: 0 auto; margin-top: 10px;">' . '<div id="inner" style="width: 78%;margin: 0 auto;background-color: #fff;font-family: Open Sans,Arial,sans-serif;font-size: 13px;font-weight: normal;line-height: 1.4em;color: #444;margin-top: 10px;">' . '<p>Hello, ' . $first_name . ',</p>' . '<p>Thank you for registering at ' . $_ENV['WEBSITE_NAME'] . '</p>' . '<p>In order to log in, we first need you to verify that you are the person who used your email address to sign up! To do this, please click the link below:</p>' . '<p><a href="' . $verifyUrl . '">' . $verifyUrl . '</a></p>' . '<p>We hope you enjoy the recipes you discover!</p>' . '<p>Kind regards,</p>' . '<p>' . $_ENV['WEBSITE_NAME'] . '</p>' . '</div>' . '</div>' . '<div id="footer" style="width: 80%;height: 40px;margin: 0 auto;text-align: center;padding: 10px;font-family: Verdena;background-color: #E2E2E2;">' . 'All rights reserved @ ' . $_ENV['WEBSITE_NAME'] . ' ' . date('Y') . '</div>' . '</body>';
     /* END BODY CONTENT */
     $mailer = \Swift_Mailer::newInstance($this->transport);
     $email = Swift_Message::newInstance()->setTo(array($to => $first_name . " " . $last_name))->setFrom(array(self::SUPPORT_EMAIL_ADDRESS => 'Recipes Support'))->setSubject("Welcome to Recipes - Verification Needed")->setBody($html, 'text/html');
     $ret = array();
     if ($recipients = $mailer->send($email)) {
         $ret['success'] = true;
         $ret['message'] = "Verification email sent.";
     } else {
         $ret['success'] = false;
         $ret['message'] = "Verification email not sent - please contact support.";
         $this->logger->addAlert("Verification email failed for: " . $email);
     }
     return json_encode($ret);
 }
 public function add($minerKey, CommentBrief $commentBrief)
 {
     $checkSum = $commentBrief->getCheckSum();
     if (!array_key_exists($checkSum, $this->checkSumIndex)) {
         $this->checkSumIndex[$checkSum] = $commentBrief;
         $this->checkSumMinerIndex[$checkSum] = $minerKey;
         if ($checkSum) {
             $this->logger->addAlert('Checksum: ' . $checkSum);
             $test = $this->ackService->test('comment_digest', $checkSum);
         } else {
             $this->logger->addAlert('Checksum not used');
             $test = false;
         }
         if (!$test) {
             $subscriber = $commentBrief->getSubscriber();
             if (!array_key_exists($subscriber, $this->bySubscriberIndex)) {
                 $this->bySubscriberIndex[$subscriber] = [$minerKey => []];
             }
             if (!array_key_exists($minerKey, $this->bySubscriberIndex[$subscriber])) {
                 $this->bySubscriberIndex[$subscriber][$minerKey] = [];
             }
             $this->bySubscriberIndex[$subscriber][$minerKey][] = $commentBrief;
         } else {
             $this->logger->addAlert('Comment already notified for user');
             $this->logger->addAlert(is_object($commentBrief->getComment()) ? $commentBrief->getComment()->getOrigin() : $commentBrief->getComment());
             $this->logger->addAlert($commentBrief->getSubscriber());
         }
     }
 }
 /**
  * @param string $view email template
  * @param User $user
  * @param NULL|array $args template variables
  *
  * @throws Exception from Latte\Engine
  * @throws SmtpException from Mailer
  */
 public function send($view, User $user, array $args = [])
 {
     if ($this->orm->unsubscribes->getByEmail($user->email)) {
         // Last line of defense. Make sure unsubscribed users
         // really dont receive any email. This should however
         // be handled before the task is queued.
         $this->logger->addAlert("Email to '{$user->email}' not send, user unsubscribed. Find out why it was queued");
         return;
     }
     $msg = new Message();
     $msg->setFrom('Khanova škola <*****@*****.**>');
     $msg->addReplyTo('Markéta Matějíčková <*****@*****.**>');
     $msg->addTo($user->email, $user->name);
     $token = Unsubscribe::createFromUser($user);
     $token->emailType = $view;
     $this->orm->tokens->attach($token);
     $this->orm->flush();
     $args['recipient'] = $user;
     $args['email'] = $msg;
     $args['unsubscribe'] = (object) ['token' => $token, 'code' => $token->getUnsafe()];
     $args['baseUrl'] = rtrim($this->baseUrl, '/');
     $latte = new Engine();
     /** @var Presenters\Token $presenter */
     $presenter = $this->factory->createPresenter('Token');
     $presenter->autoCanonicalize = FALSE;
     $ref = new \ReflectionProperty(Presenter::class, 'globalParams');
     $ref->setAccessible(TRUE);
     $ref->setValue($presenter, []);
     $latte->addFilter('token', function (Token $token, $unsafe) use($presenter, $view) {
         return $presenter->link('//Token:', ['token' => $token->toString($unsafe), 'utm_campaign' => "email-{$view}"]);
     });
     $latte->addFilter('vocative', function ($phrase) {
         return $this->inflection->inflect($phrase, 5);
     });
     $template = $latte->renderToString($this->getTemplate($view), $args);
     $msg->setHtmlBody($template);
     $this->mailer->send($msg);
     $this->logger->addInfo('Email send', ['view' => $view, 'email' => $user->email]);
 }
 /**
  * @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);
 }
Beispiel #10
0
$view = $app->view();
$view->parserExtensions = array(new \Slim\Views\TwigExtension());
$redis = new Predis\Client(array("scheme" => "tcp", "host" => "127.0.0.1", "port" => 6379));
$app->get('/hello/:name', function ($name) use($app) {
    $logPath = '/tmp/mono.log';
    $logger = new Logger('foo_test');
    $logger->pushHandler(new StreamHandler($logPath, Logger::DEBUG));
    // $logger->info()
    $logger->addInfo('info_bar');
    // $logger->notice()
    $logger->addNotice('notice_bar');
    // $logger->warning(), $logger->warn()
    $logger->addWarning('warning_bar');
    // $logger->error(), $logger->err()
    $logger->addError('error_bar');
    // $logger->critical(), $logger->crit()
    $logger->addCritical('critical_bar');
    // $logger->alert()
    $logger->addAlert('alert_bar');
    // $logger->emergency(), $logger->emerg()
    $logger->addEmergency('emergency_bar');
    $app->render('index.html', array('name' => $name));
});
$app->get('/redis', function () use($redis) {
    // PING
    echo $redis->ping();
    $redis->set('key', 'value');
    $value = $redis->get('key');
    echo "key: " . $value;
});
$app->run();
Beispiel #11
0
 /**
  * Output a given log message to STDOUT.
  *
  * @param string $message Message to output.
  * @param int $code
  * @return bool True if the message is logged
  */
 public function log($message, $code = self::LOG_TYPE_INFO)
 {
     if ($this->logLevel === self::LOG_NONE) {
         return false;
     }
     /*if ($this->logger === null) {
           if ($this->logLevel === self::LOG_NORMAL && $code !== self::LOG_TYPE_DEBUG) {
               fwrite($this->logOutput, "*** " . $message['message'] . "\n");
           } else if ($this->logLevel === self::LOG_VERBOSE) {
               fwrite($this->logOutput, "** [" . strftime('%T %Y-%m-%d') . "] " . $message['message'] . "\n");
           } else {
               return false;
           }
           return true;
       } else {*/
     $extra = array();
     if (is_array($message)) {
         $extra = $message['data'];
         $message = $message['message'];
     }
     if (!isset($extra['worker'])) {
         if ($this->child > 0) {
             $extra['worker'] = $this->hostname . ':' . getmypid();
         } else {
             list($host, $pid, ) = explode(':', (string) $this, 3);
             $extra['worker'] = $host . ':' . $pid;
         }
     }
     if (($this->logLevel === self::LOG_NORMAL || $this->logLevel === self::LOG_VERBOSE) && $code !== self::LOG_TYPE_DEBUG) {
         if ($this->logger === null) {
             fwrite($this->logOutput, "[" . date('c') . "] " . $message . "\n");
         } else {
             switch ($code) {
                 case self::LOG_TYPE_INFO:
                     $this->logger->addInfo($message, $extra);
                     break;
                 case self::LOG_TYPE_WARNING:
                     $this->logger->addWarning($message, $extra);
                     break;
                 case self::LOG_TYPE_ERROR:
                     $this->logger->addError($message, $extra);
                     break;
                 case self::LOG_TYPE_CRITICAL:
                     $this->logger->addCritical($message, $extra);
                     break;
                 case self::LOG_TYPE_ALERT:
                     $this->logger->addAlert($message, $extra);
             }
         }
     } else {
         if ($code === self::LOG_TYPE_DEBUG && $this->logLevel === self::LOG_VERBOSE) {
             if ($this->logger === null) {
                 fwrite($this->logOutput, "[" . date('c') . "] " . $message . "\n");
             } else {
                 $this->logger->addDebug($message, $extra);
             }
         } else {
             return false;
         }
     }
     return true;
     //}
 }
 /**
  * This method wraps monolog's add alert
  * @param Logger $logger
  * @param $msg
  * @param array $param
  */
 public function alert(Logger $logger, $msg, $param = array())
 {
     $logger->addAlert($msg, $param);
 }
Beispiel #13
0
 /**
  * @covers Monolog\Logger::addRecord
  */
 public function testProcessorsNotCalledWhenNotHandled()
 {
     $logger = new Logger(__METHOD__);
     $handler = $this->getMock('Monolog\\Handler\\HandlerInterface');
     $handler->expects($this->once())->method('isHandling')->will($this->returnValue(false));
     $logger->pushHandler($handler);
     $that = $this;
     $logger->pushProcessor(function ($record) use($that) {
         $that->fail('The processor should not be called');
     });
     $logger->addAlert('test');
 }
Beispiel #14
0
 protected function error($message, $context = [])
 {
     $this->logger->addAlert($message, $context);
 }
Beispiel #15
0
 public function alert($message, $array = array())
 {
     $log = new Logger($this->logName);
     $log->pushHandler(new StreamHandler($this->logFile, Logger::ALERT));
     $log->addAlert($message, $array);
 }
 /**
  * Adds a log record at the ALERT 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 addAlert($message, $context = array())
 {
     return \Monolog\Logger::addAlert($message, $context);
 }
<?php

if ($argc < 2) {
    exit('Usage: php example.php <token> <room_id>' . PHP_EOL);
}
if (!isset($argv[1])) {
    throw new \InvalidArgumentException('Please provide a valid hipchat token.');
}
if (!isset($argv[2])) {
    throw new \InvalidArgumentException('Please provide a valid room id');
}
require_once __DIR__ . '/autoload.php';
use Monolog\Logger;
use Monolog\Handler\StreamHandler;
use Palleas\HipChat\Monolog\RoomHandler;
$client = new \HipChat($argv[1]);
$log = new Logger('awesome');
$log->pushHandler(new RoomHandler($client, (int) $argv[2]));
$log->addInfo('Palleas is a really nice guy.');
$log->addDebug('Just so you know, it works.');
$log->addWarning("Don't want to scare you, but there is a weird speaking-cat right behing you.");
$log->addError("So, you're using Zend frameworl heh?");
$log->addCritical('We are out of coffee.');
$log->addAlert('Today is tuesday.');
Beispiel #18
0
 /**
  * @param string $message
  * @param array $context
  * @return bool
  */
 public function addAlert($message, array $context = array())
 {
     return parent::addAlert($message, $context);
 }
Beispiel #19
0
 public function alert($message, array $context = array())
 {
     if (isset($this->logger)) {
         $this->logger->addAlert($message, $context);
     }
 }
Beispiel #20
0
 public function alert($msg, $context = [])
 {
     $this->logger->addAlert($msg, $context);
 }