addCritical() public method

Adds a log record at the CRITICAL level.
public addCritical ( 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);
     }
 }
Ejemplo n.º 2
0
 /**
  * @param array $config
  * @throws \Exception
  */
 protected function __construct($config)
 {
     parent::__construct($config);
     $this->memcache = new \Memcache();
     /**
      * This is something tricky in PHP. If you use pconnect (p=persistent) the connection will remain open all the time.
      * This is not a bad thing since we're using the cache all the time (you don't turn off the light of the kitchen if you're running in and out, switching it too much would even consume more)
      * In memcache, the old but stable implementation in PHP of memcached the persistent connection works like charm
      * In memcached however there is a severe bug which leads to a memory leak. If you'd take over code from this class to implement memcached, DON'T use the persistent connect!
      */
     if (!isset($this->config["host"])) {
         // the default host for memcached localhost
         $this->config["host"] = "localhost";
     }
     if (!isset($this->config["port"])) {
         // the default port for memcached is 11211
         $this->config["port"] = 11211;
     }
     if (!$this->memcache->pconnect($this->config["host"], $this->config["port"])) {
         if (isset($this->config["log_dir"])) {
             $log_dir = rtrim($this->config["log_dir"], "/");
             $log = new Logger('cache');
             $log->pushHandler(new StreamHandler($log_dir . "/log_" . date('Y-m-d') . ".txt", Logger::CRITICAL));
             $log->addCritical("Could not connect to memcached.", $this->config);
         } else {
             /*
              * if we have no log directory, it's no use to throw a TDTException
              */
             throw new \Exception("No connection could be made to the memcache. Please check your given configuration.");
         }
     }
 }
Ejemplo n.º 3
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.º 4
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.º 5
0
 /**
  * @param String $query
  * @param array $parameters
  * @return int|null|string
  */
 public function execute(string $query, $parameters = array())
 {
     try {
         $this->pdo->beginTransaction();
         $stmt = $this->pdo->prepare($query);
         $stmt->execute($parameters);
         if ($stmt->errorCode() != 0) {
             $this->pdo->rollBack();
             return 0;
         }
         $returnID = $this->pdo->lastInsertId();
         $this->pdo->commit();
         $stmt->closeCursor();
         return $returnID;
     } catch (\Exception $e) {
         $this->log->addError("There was an error during a query: ", [$e->getMessage()]);
         try {
             $this->pdo = $this->connect();
         } catch (\Exception $e2) {
             $this->log->addCritical("Couldn't reconnect to the database: " . $e->getMessage());
             die(1);
         }
     }
     return null;
 }
Ejemplo n.º 6
0
 public function __construct($errorcode, array $parameters = array(), array $config = array())
 {
     $this->config = $config;
     $this->errorcode = $errorcode;
     $this->parameters = $parameters;
     $exceptions = parse_ini_file("exceptions.ini", true);
     if (isset($exceptions[$errorcode])) {
         $this->exceptionini = $exceptions[$errorcode];
         //create the message of the exception by filling out the parameters, if the message exists of course
         $i = 1;
         if (isset($this->exceptionini["message"])) {
             foreach ($this->parameters as $param) {
                 $to_replace = "\$" . $i;
                 if (!is_string($param)) {
                     $param = print_r($param, true);
                 }
                 $this->exceptionini["message"] = str_replace($to_replace, $param, $this->exceptionini["message"]);
                 $i++;
             }
         }
     } else {
         if (isset($config["log_dir"])) {
             $log = new Logger('error_handler');
             $log_dir = rtrim($this->config["log_dir"], "/");
             $log->pushHandler(new StreamHandler($log_dir . "/log_" . date('Y-m-d') . ".txt", Logger::CRITICAL));
             $log->addCritical("Could not find an exception with errorcode " . $this->errorcode . ".");
         }
         if (isset($config["url"])) {
             $url = rtrim($config["url"], "/");
             header("Location: " . $url . "/critical");
         }
     }
     parent::__construct($this->getMsg(), $errorcode);
 }
 public function run(Repository $repository, GitSource $source)
 {
     $this->logger = new Logger($repository->getRepository(), array($this->handler));
     try {
         $docsRepository = null;
         $this->initSourcePath($repository, $source);
         $this->checkoutSource($repository, $source);
         $this->buildDefaultSettings($repository, $source);
         $this->buildSettings($repository, $docsRepository, $source);
         $this->checkBranch($repository, $docsRepository, $source);
         $this->initDocsPath($repository, $docsRepository, $source);
         $this->prepareDocs($repository, $docsRepository, $source);
         $this->generateDocs($repository, $docsRepository, $source);
         $this->pushDocs($repository, $docsRepository, $source);
         $this->updateHistory($repository, $docsRepository, $source);
     } catch (\Exception $exception) {
         $this->logger->addCritical($exception->getMessage() . "\n" . $exception->getTraceAsString());
     }
 }
Ejemplo n.º 8
0
 /**
  * @test
  */
 public function it_should_sent_message()
 {
     $spy = new MessageSenderSpy();
     $config = SmsapiConfigMother::createDefault();
     $handler = new SmsapiHandler($spy, new SmsapiFormatterFactory($config), $config);
     $logger = new Logger('example');
     $logger->pushHandler($handler);
     $logger->addCritical('some critical bug');
     $this->assertTrue($spy->isSent);
 }
 /**
  * Handle the event.
  *
  * @param UpdateAvailable $event
  */
 public function handle(UpdateAvailable $event)
 {
     if (config('self-update.log_events')) {
         $this->logger->addInfo('[' . $event->getEventName() . '] event: Notification triggered.');
     }
     $sendToAddress = config('self-update.mail_to.address');
     $sendToName = config('self-update.mail_to.name');
     $subject = config('self-update.mail_to.subject_update_available');
     if (empty($sendToAddress)) {
         $this->logger->addCritical('[' . $event->getEventName() . '] event: ' . 'Missing recipient email address. Please set SELF_UPDATER_MAILTO_ADDRESS in your .env file.');
     }
     if (empty($sendToName)) {
         $this->logger->addWarning('[' . $event->getEventName() . '] event: ' . 'Missing recipient email name. Please set SELF_UPDATER_MAILTO_NAME in your .env file.');
     }
     $this->mailer->send('vendor.self-update.mails.update-available', ['newVersion' => $event->getVersionAvailable()], function ($m) use($subject, $sendToAddress, $sendToName) {
         $m->subject($subject);
         $m->from(config('mail.from.address'), config('mail.from.name'));
         $m->to($sendToAddress, $sendToName);
     });
 }
Ejemplo n.º 10
0
 /**
  * @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);
 }
Ejemplo n.º 11
0
 /**
  * @brief Check the result for unexpected errors. If found, treat them as fatal.
  * @param resource $result command result object
  * @param string $sqlStatement SQL command (optional)
  */
 protected function checkResult($result, $sqlStatement = "")
 {
     if ($result !== false) {
         return;
     }
     $lastError = "";
     if ($this->dbDriver->isConnected()) {
         $lastError = $this->dbDriver->getLastError();
         $this->logger->addCritical($lastError);
         if ($this->transactionDepth > 0) {
             $this->dbDriver->rollback();
         }
     } else {
         $this->logger->addCritical("DB connection lost.");
     }
     $message = "error executing: {$sqlStatement}\n\n{$lastError}";
     throw new Exception($message);
 }
Ejemplo n.º 12
0
 public function receiveSig($sig)
 {
     $this->signalled = true;
     switch ($sig) {
         case SIGTERM:
             $this->logger->addError("Received SIGTERM");
             exit($this->stop() ? 0 : -1);
             break;
         case SIGINT:
             $this->logger->addWarning("Received SIGINT");
             exit($this->stop() ? 0 : -1);
             break;
         default:
             $this->logger->addCritical("Received Unknown Signal {$sig}");
             exit($this->stop() ? 127 : 127);
             break;
     }
 }
Ejemplo n.º 13
0
 /**
  * Get the contents of a given URL (via GET)
  * @param  string $pageUrl The URL of the page to get the contents of
  * @return string
  */
 private function getContents(&$pageUrl)
 {
     // Init CURL
     $curl = curl_init();
     @curl_setopt_array($curl, array(CURLOPT_RETURNTRANSFER => 1, CURLOPT_FOLLOWLOCATION => 1, CURLOPT_HEADER => 1, CURLOPT_URL => $pageUrl, CURLOPT_TIMEOUT_MS => $this->timeout, CURLOPT_SSL_VERIFYPEER => $this->checkCertificate, CURLOPT_SSL_VERIFYHOST => $this->getVerifyHost(), CURLOPT_USERAGENT => 'mixed-content-scan'));
     // Fetch the response (both head and body)
     $response = curl_exec($curl);
     // Fetch the URL of the page we actually fetched
     $newUrl = curl_getinfo($curl, CURLINFO_EFFECTIVE_URL);
     if ($newUrl != $pageUrl) {
         // If we started at the rootURL, and it got redirected:
         // --> overwrite the rootUrl so that we use the new one from now on
         if ($pageUrl == $this->rootUrl) {
             // Store the new rootUrl
             $this->setRootUrl($newUrl, false);
             // Update ignore patterns
             $this->setIgnorePatterns($this->ignorePatterns, $pageUrl);
         }
         // Update $pageUrl (pass by reference!)
         $pageUrl = $newUrl;
     }
     // Got an error?
     $curl_errno = curl_errno($curl);
     $curl_error = curl_error($curl);
     if ($curl_errno > 0) {
         $this->logger->addCritical('cURL Error (' . $curl_errno . '): ' . $curl_error);
     }
     // Extract the response head and response body from the response
     $headers = substr($response, 0, curl_getinfo($curl, CURLINFO_HEADER_SIZE));
     $body = substr($response, -curl_getinfo($curl, CURLINFO_CONTENT_LENGTH_DOWNLOAD));
     // Close it
     @curl_close($curl);
     // If the headers contain `Content-Security-Policy: upgrade-insecure-requests`
     // then the page should be skipped, as the browser will (should) then automatically
     // upgrade all requests.
     // @ref https://w3c.github.io/webappsec-upgrade-insecure-requests/
     // Return the fetched contents
     return $body;
 }
Ejemplo n.º 14
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();
Ejemplo n.º 15
0
    }
    if (!array_key_exists('exception', $record['context'])) {
        return false;
    }
    return preg_match('/^An error has occured/', $record['message']) === 1;
});
// Create some handlers
$stream = new RotatingFileHandler(__DIR__ . DIRECTORY_SEPARATOR . 'growl_conf.log');
$stream->setFilenameFormat('{filename}-{date}', 'Ymd');
$logger->pushHandler($stream);
try {
    $resourceDir = __DIR__ . DIRECTORY_SEPARATOR . 'images' . DIRECTORY_SEPARATOR;
    $notifications = array(GrowlHandler::DEBUG => array('icon' => $resourceDir . 'green.png'), GrowlHandler::INFO => array('icon' => $resourceDir . 'green.png'), GrowlHandler::NOTICE => array('icon' => $resourceDir . 'yellow.png'), GrowlHandler::WARNING => array('icon' => $resourceDir . 'yellow.png'), GrowlHandler::ERROR => array('icon' => $resourceDir . 'red.png'), GrowlHandler::CRITICAL => array('icon' => $resourceDir . 'red.png'), GrowlHandler::ALERT => array('icon' => $resourceDir . 'red.png'), GrowlHandler::EMERGENCY => array('icon' => $resourceDir . 'red.png'));
    $options = array('AppIcon' => dirname(__DIR__) . '/vendor/pear-pear.php.net/Net_Growl/data/Net_Growl/data/128/growl-starkicon.png');
    $growl = new GrowlHandler(array('name' => 'My Custom Growl', 'notifications' => $notifications, 'options' => $options));
    $growl->setFormatter(new LineFormatter("%message%\n%level_name%"));
    $logger->pushHandler(new CallbackFilterHandler($growl, $filters));
} catch (\Exception $e) {
    // Growl server is probably not started
    echo $e->getMessage(), PHP_EOL, PHP_EOL;
}
// You can now use your logger
$logger->addInfo('My logger is now ready');
// This record won't be stopped by the $filters rules, but by the growl $notifications config
$logger->addDebug('A debug message.');
$logger->addError('An error has occured. Will be logged to file BUT NOT notified by Growl.');
try {
    throw new \RuntimeException();
} catch (\Exception $e) {
    $logger->addCritical('An error has occured. Will be logged to file AND notified by Growl.', array('exception' => $e));
}
Ejemplo n.º 16
0
 /**
  * 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 addCritical($message, $context = array())
 {
     return \Monolog\Logger::addCritical($message, $context);
 }
/**
 * This example will :
 * - notify with Growl, CRITICAL events or higher
 *
 * @author   Laurent Laville <*****@*****.**>
 * @license  http://www.opensource.org/licenses/bsd-license.php BSD License
 * @since    Example available since Release 1.0.0
 */
$baseDir = dirname(__DIR__);
$vendorDir = $baseDir . '/vendor';
require_once $vendorDir . '/autoload.php';
use Bartlett\Monolog\Handler\GrowlHandler;
use Monolog\Logger;
// Create the logger
$logger = new Logger('my_logger');
// Create some handlers
try {
    $growl = new GrowlHandler(array(), Logger::CRITICAL);
    $logger->pushHandler($growl);
} catch (\Exception $e) {
    // Growl server is probably not started
    echo $e->getMessage(), PHP_EOL;
}
// You can now use your logger
$logger->addInfo('My logger is now ready');
$logger->addError('An error has occured.');
try {
    throw new \RuntimeException();
} catch (\Exception $e) {
    $logger->addCritical('A critical condition has occured. You will be notified by growl.', array('exception' => $e));
}
Ejemplo n.º 18
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;
     //}
 }
<?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.');
Ejemplo n.º 20
0
 /**
  * @param $contents
  *
  * @return mixed
  */
 public function warning($contents)
 {
     return $this->log->addCritical($contents);
 }
Ejemplo n.º 21
0
 /**
  * @param $desc
  */
 public static function critical($desc)
 {
     $log = new Logger('Project');
     $log->pushHandler(new StreamHandler(__DIR__ . "/../log/register.log", Logger::CRITICAL));
     $log->addCritical($desc);
 }
Ejemplo n.º 22
0
 public function critical($msg)
 {
     $this->logger->addCritical($msg);
 }
Ejemplo n.º 23
0
 /**
  * @param string $message
  * @param array $context
  * @return bool
  */
 public function addCritical($message, array $context = array())
 {
     return parent::addCritical($message, $context);
 }
Ejemplo n.º 24
0
 /**
  * @param Collection $models
  * @param $reason
  * @param $message
  * @param $primitive
  */
 public function sendError(Collection $models, $reason, $message, $primitive)
 {
     $this->logger->addCritical("Failed sending the following Customer objects to ROBIN: ", compact("models", "reason", "message", "primitive"));
 }
Ejemplo n.º 25
0
 public function critical($message, $array = array())
 {
     $log = new Logger($this->logName);
     $log->pushHandler(new StreamHandler($this->logFile, Logger::CRITICAL));
     $log->addCritical($message, $array);
 }
Ejemplo n.º 26
0
 public function critical($message, array $context = array())
 {
     if (isset($this->logger)) {
         $this->logger->addCritical($message, $context);
     }
 }
Ejemplo n.º 27
0
 public function critical($msg, $context = [])
 {
     $this->logger->addCritical($msg, $context);
 }
Ejemplo n.º 28
0
Archivo: router.php Proyecto: tdt/start
    $route = preg_replace('/^' . strtoupper($_SERVER['REQUEST_METHOD']) . '(\\s|\\t)*\\|(\\s|\\t)*/', "", trim($route));
    $routes[trim($route)] = trim($controller);
}
//$log->logInfo("The routes we are working with", $routes);
try {
    // This function will do the magic.
    Glue::stick($routes);
} catch (Exception $e) {
    // Instantiate a Logger
    $log = new Logger('router');
    $log->pushHandler(new StreamHandler(app\core\Config::get("general", "logging", "path") . "/log_" . date('Y-m-d') . ".txt", Logger::ERROR));
    // Generator to generate an error page
    $generator = new Generator();
    $generator->setTitle("The DataTank");
    if ($e instanceof tdt\exceptions\TDTException) {
        // DataTank error
        $log->addError($e->getMessage());
        set_error_header($e->getCode(), $e->getShort());
        if ($e->getCode() < 500) {
            $generator->error($e->getCode(), "Sorry, but there seems to be something wrong with the call you've made", $e->getMessage());
        } else {
            $generator->error($e->getCode(), "Sorry, there seems to be something wrong with our servers", "If you're the system administrator, please check the logs. Otherwise, check back in a short while.");
        }
    } else {
        // General error
        $log->addCritical($e->getMessage());
        set_error_header(500, "Internal Server Error");
        $generator->error($e->getCode(), "Sorry, there seems to be something wrong with our servers", "If you're the system administrator, please check the logs. Otherwise, check back in a short while.");
    }
    exit(0);
}
Ejemplo n.º 29
0
use Monolog\Logger;
use Monolog\Handler\RotatingFileHandler;
$logger = new Logger('PosibrainRestApi');
if (!is_dir(__DIR__ . '/../logs/')) {
    mkdir(__DIR__ . '/../logs/');
    chmod(__DIR__ . '/../logs/', '755');
}
$loggerHandler = new RotatingFileHandler(__DIR__ . '/../logs/restapi.log', 2, Logger::DEBUG);
$logger->pushHandler($loggerHandler);
$request = Request::createFromGlobals();
$routes = new Routing\RouteCollection();
$routes->add('bots', new Routing\Route('/bots/{botId}', array('botId' => '', '_controller' => 'Posibrain\\RestApi\\RestApiController::actionGetBots'), array('_method' => 'GET')));
$routes->add('positrons', new Routing\Route('/positrons', array('_controller' => 'Posibrain\\RestApi\\RestApiController::actionGetPositrons'), array('_method' => 'GET')));
$routes->add('submit', new Routing\Route('/submit/{botId}/{botLang}', array('botId' => '', 'botLang' => '', '_controller' => 'Posibrain\\RestApi\\RestApiController::actionSubmit'), array('_method' => 'GET')));
$context = new Routing\RequestContext();
$context->fromRequest($request);
$matcher = new UrlMatcher($routes, $context);
$resolver = new ControllerResolver();
$response = null;
try {
    $request->attributes->add($matcher->match($request->getPathInfo()));
    $controller = $resolver->getController($request);
    $arguments = $resolver->getArguments($request, $controller);
    $response = call_user_func_array($controller, $arguments);
} catch (ResourceNotFoundException $e) {
    $response = new Response('Not Found', 404);
} catch (\Exception $e) {
    $logger->addCritical('[500] An error occurred', $e);
    $response = new Response('An error occurred', 500);
}
$response->send();
Ejemplo n.º 30
0
        $messageBody .= '<tr><td>' . $index . '</td><td>' . $item['createdAt'] . '</td><td>' . $item['branchName'] . '</td></tr>';
    }
    $messageBody .= '</table><br>';
    $messageBody .= 'Please review this branches and remove them or merge to development.<br>Or keep in mind that you have this branches not merged to development. <br><br>';
    $messageBody .= 'Thanks and have a nice day!';
    /**
     * create message instance
     */
    $message = Swift_Message::newInstance('Morning pre-work email')->setFrom([$config['app']['email']['from'] => $config['app']['name']])->setTo($config['users'][$username]['sendTo'])->setContentType('text/html')->setBody($messageBody);
    /**
     * add custom headers
     */
    if (!empty($config['app']['email']['headers'])) {
        $headers = $message->getHeaders();
        foreach ($config['app']['email']['headers'] as $headerName => $headerValue) {
            $headers->addTextHeader($headerName, $headerValue);
        }
    }
    /**
     * send
     */
    try {
        if ($mailer->send($message) == 1) {
            $log->addInfo('Mail was sent to ' . $username);
        } else {
            $log->addError('Can\'t send to ' . $config['users'][$username]['sendTo']);
        }
    } catch (\Exception $e) {
        $log->addCritical($e->getMessage() . "\n" . $e->getTraceAsString());
    }
}