It contains a stack of Handlers and a stack of Processors, and uses them to store records that are added to it.
Автор: Jordi Boggiano (j.boggiano@seld.be)
Пример #1
0
 /**
  *
  * @param  Request $request
  * @param  string  $queryString
  * @param  string  $filename
  * @return Response
  */
 public function interventionRequestAction(Request $request, $queryString, $filename)
 {
     $log = new Logger('InterventionRequest');
     $log->pushHandler(new StreamHandler(ROADIZ_ROOT . '/logs/interventionRequest.log', Logger::INFO));
     try {
         $cacheDir = ROADIZ_ROOT . '/cache/rendered';
         if (!file_exists($cacheDir)) {
             mkdir($cacheDir);
         }
         $conf = new Configuration();
         $conf->setCachePath($cacheDir);
         $conf->setImagesPath(ROADIZ_ROOT . '/files');
         /*
          * Handle short url with Url rewriting
          */
         $expander = new ShortUrlExpander($request);
         $expander->injectParamsToRequest($queryString, $filename);
         /*
          * Handle main image request
          */
         $iRequest = new InterventionRequest($conf, $request, $log);
         $iRequest->handle();
         return $iRequest->getResponse();
     } catch (\Exception $e) {
         if (null !== $log) {
             $log->error($e->getMessage());
         }
         return new Response($e->getMessage(), Response::HTTP_NOT_FOUND, ['content-type' => 'text/plain']);
     }
 }
 /**
  * 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);
         });
     }
 }
Пример #3
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'));
 }
Пример #4
0
 /**
  * Instantiate mediavorus to register the mime types
  */
 public function setUp()
 {
     parent::setUp();
     $logger = new Logger('test');
     $logger->pushHandler(new NullHandler());
     $mediavorus = new MediaVorus(Reader::create($logger), Writer::create($logger), FFProbe::create());
 }
 public function register(Container $container)
 {
     $log = new Logger('grav');
     $log_file = LOG_DIR . 'grav.log';
     $log->pushHandler(new StreamHandler($log_file, Logger::WARNING));
     $container['log'] = $log;
 }
Пример #6
0
 /**
  * Options request for any Installation request.
  *
  * @param HttpFoundation\Request $request
  * @return HttpFoundation\Response
  */
 public function optionsIndex(HttpFoundation\Request $request)
 {
     $this->log->addDebug(print_r($request, true), ['namespace' => 'Alerts\\Controllers\\Install', 'method' => 'optionsIndex', 'type' => 'request']);
     $response = new HttpFoundation\Response('OK');
     $response->headers->add(['Access-Control-Allow-Methods' => 'POST, OPTIONS']);
     return $response;
 }
Пример #7
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.");
         }
     }
 }
Пример #8
0
 function fetchAllRates(Logger $logger)
 {
     $url = "https://api.vircurex.com/api/get_info_for_currency.json";
     $logger->info($url);
     $json = Fetch::jsonDecode(Fetch::get($url));
     $result = array();
     $ignored = 0;
     foreach ($json as $pair2 => $pairs) {
         if ($pair2 == "status") {
             continue;
         }
         foreach ($pairs as $pair1 => $market) {
             if ($market['last_trade'] == 0 || $market['lowest_ask'] == 0 || $market['highest_bid'] == 0) {
                 // ignore empty markets
                 $ignored++;
                 continue;
             }
             $currency1 = $this->getCurrencyCode($pair1);
             $currency2 = $this->getCurrencyCode($pair2);
             if (CurrencyOrder::hasOrder($currency1) && CurrencyOrder::hasOrder($currency2)) {
                 if (!CurrencyOrder::isOrdered($currency1, $currency2)) {
                     // do not duplicate ordered currencies
                     continue;
                 }
             }
             $rate = array("currency1" => $currency1, "currency2" => $currency2, "last_trade" => $market['last_trade'], "volume" => $market['volume'], 'bid' => $market['highest_bid'], 'ask' => $market['lowest_ask']);
             $result[] = $rate;
         }
     }
     $logger->info("Ignored " . $ignored . " markets with last trade price of 0");
     return $result;
 }
 /**
  * @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);
 }
Пример #10
0
 public function showWelcomeMessage()
 {
     echo sprintf("<div class='updated'><p>The <strong>%s</strong> plugin has been installed at <em>%s</em></p></div>", $this->pluginName, $this->path);
     // pass logger to your class whenever you want to log something
     // ensure log directory has correct permissions
     $this->log->Info('Welcome message shown', ['action' => 'admin_notices']);
 }
Пример #11
0
 function setUp()
 {
     $logger = new \Monolog\Logger("test");
     $logger->pushHandler(new SilentLogger());
     $parser = new Parser($logger);
     $this->result = $parser->load($this->getFile());
 }
Пример #12
0
 public function notify(Service\Record $record, DOMDocument $config, Logger $logger)
 {
     $activity = $config->getElementsByTagName('activity')->item(0);
     if ($activity !== null) {
         $logger->info('Create user activity template');
         try {
             $templates = $activity->childNodes;
             for ($i = 0; $i < $templates->length; $i++) {
                 $template = $templates->item($i);
                 if (!$template instanceof DOMElement) {
                     continue;
                 }
                 if ($template->nodeName == 'template') {
                     $type = $template->getAttribute('type');
                     $verb = $template->getAttribute('verb');
                     $table = $template->getAttribute('table');
                     $path = $template->getAttribute('path');
                     $summary = $template->nodeValue;
                     if (isset($this->registry['table.' . $table])) {
                         $table = $this->registry['table.' . $table];
                     } else {
                         throw new Exception('Invalid table ' . $table);
                     }
                     if (!empty($type) && !empty($verb) && !empty($table) && !empty($summary)) {
                         $this->sql->insert($this->registry['table.user_activity_template'], array('type' => $type, 'verb' => $verb, 'table' => $table, 'path' => $path, 'summary' => $summary));
                         $logger->info('> Created user activity template');
                         $logger->info($summary);
                     }
                 }
             }
         } catch (\Exception $e) {
             $logger->error($e->getMessage());
         }
     }
 }
Пример #13
0
 /**
  * This method is called before the first test of this test class is run.
  */
 public static function setUpBeforeClass()
 {
     // First, generate the INI files
     $buildNumber = time();
     $resourceFolder = __DIR__ . '/../../resources/';
     self::$buildFolder = __DIR__ . '/../../build/browscap-ua-test-' . $buildNumber . '/build/';
     $cacheFolder = __DIR__ . '/../../build/browscap-ua-test-' . $buildNumber . '/cache/';
     // create build folder if it does not exist
     if (!file_exists(self::$buildFolder)) {
         mkdir(self::$buildFolder, 0777, true);
     }
     if (!file_exists($cacheFolder)) {
         mkdir($cacheFolder, 0777, true);
     }
     $logger = new Logger('browscap');
     $logger->pushHandler(new NullHandler(Logger::DEBUG));
     $buildGenerator = new BuildGenerator($resourceFolder, self::$buildFolder);
     $writerCollectionFactory = new PhpWriterFactory();
     $writerCollection = $writerCollectionFactory->createCollection($logger, self::$buildFolder);
     $buildGenerator->setLogger($logger)->setCollectionCreator(new CollectionCreator())->setWriterCollection($writerCollection);
     $buildGenerator->run($buildNumber, false);
     $cache = new File([File::DIR => $cacheFolder]);
     self::$browscap = new Browscap();
     self::$browscap->setCache($cache)->setLogger($logger);
     self::$browscapUpdater = new BrowscapUpdater();
     self::$browscapUpdater->setCache($cache)->setLogger($logger);
     self::$propertyHolder = new PropertyHolder();
 }
Пример #14
0
 function storeSupportedCurrencies($currencies, Logger $logger)
 {
     $logger->info("Storing " . count($currencies) . " currencies persistently");
     // find all existing currencies
     $existing = $this->getSupportedCurrencies(true);
     // remove removed currencies
     foreach ($existing as $currency) {
         if (array_search($currency, $currencies) === false) {
             $logger->info("Removing currency {$currency}");
             $q = $this->db->prepare("DELETE FROM account_currencies WHERE exchange=? AND currency=?");
             $q->execute(array($this->exchange->getCode(), $currency));
         }
     }
     // add new currencies
     foreach ($currencies as $currency) {
         if (array_search($currency, $existing) === false) {
             if (strlen($currency) != 3) {
                 $logger->info("Ignoring currency '" . $currency . "': not three characters long");
                 continue;
             }
             $logger->info("Adding currency {$currency}");
             $q = $this->db->prepare("INSERT INTO account_currencies SET exchange=?, currency=?");
             $q->execute(array($this->exchange->getCode(), $currency));
         }
     }
     // reset cache
     $this->cached_currencies = null;
 }
 /**
  * @param ServiceLocatorInterface $serviceLocator
  * @return Logger
  */
 public function createService(ServiceLocatorInterface $serviceLocator)
 {
     $handler = new Handler\RotatingFileHandler('data/logs/error.log');
     $logger = new Logger('error-handling');
     $logger->pushHandler($handler);
     return $logger;
 }
Пример #16
0
 public function setUp()
 {
     parent::setUp();
     $this->monolog = new Monolog\Logger('log-decorator');
     $this->handler = new Monolog\Handler\TestHandler();
     $this->monolog->pushHandler($this->handler);
 }
Пример #17
0
 public static function setUpBeforeClass()
 {
     parent::setUpBeforeClass();
     self::$logger = new Logger('filefindtest');
     self::$logger->pushHandler(new TestHandler());
     self::$logger->pushHandler(new StreamHandler('test.log'));
 }
Пример #18
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);
 }
Пример #19
0
 /**
  * Find the next job that should be executed.
  * By default, just selects any job instance that is in the database that isn't
  * already executing, hasn't already been finished, and hasn't errored out.
  * @return a job array (id, job_type, [user_id], [arg_id]) or {@code false} if there is none
  */
 function findJob(Connection $db, Logger $logger)
 {
     // TODO timeout jobs
     // mark all repeatedly failing jobs as failing
     $execution_limit = Config::get("job_execution_limit", 5);
     $q = $db->prepare("SELECT * FROM jobs WHERE is_executed=0 AND is_executing=0 AND execution_count >= ?");
     $q->execute(array($execution_limit));
     if ($failed = $q->fetchAll()) {
         $logger->info("Found " . number_format(count($failed)) . " jobs that have executed too many times ({$execution_limit})");
         foreach ($failed as $f) {
             $q = $db->prepare("UPDATE jobs SET is_executed=1,is_error=1 WHERE id=?");
             $q->execute(array($f['id']));
             $logger->info("Marked job " . $f['id'] . " as failed");
         }
     }
     // find first a job that has zero execution count
     $q = $db->prepare("SELECT * FROM jobs WHERE " . $this->defaultFindJobQuery() . " AND execution_count=0 LIMIT 1");
     $q->execute();
     if ($job = $q->fetch()) {
         return $job;
     }
     // or, any job
     $q = $db->prepare("SELECT * FROM jobs WHERE " . $this->defaultFindJobQuery() . " LIMIT 1");
     $q->execute();
     return $q->fetch();
 }
Пример #20
0
 public function runRequest($request)
 {
     $c = $this->loadController($request);
     $sess = \Sessionx::start();
     $sess->refreshCookie();
     if (is_callable(array($c, 'load'))) {
         $c->name = $request;
         $c->load();
         $c->checkSession();
         $c->dispatch();
         // If the controller ask to display a different page
         if ($request != $c->name) {
             $new_name = $c->name;
             $c = $this->loadController($new_name);
             $c->name = $new_name;
             $c->load();
             $c->dispatch();
         }
         // We display the page !
         $c->display();
     } else {
         $log = new Logger('movim');
         $log->pushHandler(new SyslogHandler('movim'));
         $log->addError(t("Could not call the load method on the current controller"));
     }
 }
Пример #21
0
/**
 * Error Handler...
 */
function systemErrorHandler($errno, $errstr, $errfile, $errline, $errcontext = null)
{
    $log = new Logger('movim');
    $log->pushHandler(new SyslogHandler('movim'));
    $log->addError($errstr);
    return false;
}
Пример #22
0
 /**
  * Método constructor de la clase.
  *
  * Construye el log de Monolog y lo asigna a la variable de clase log.
  */
 private function __construct()
 {
     $log = new Logger("Sistema." . $this->getAppEnv());
     $log->pushHandler(new StreamHandler(__DIR__ . "/../../../storage/logs/System.log"));
     $log->pushProcessor(new WebProcessor());
     $this->log = $log;
 }
Пример #23
0
 /**
  * {@inheritDoc}
  */
 public function register(Container $container)
 {
     // Append custom settings with missing params from default settings
     $container['settings']['database'] = self::mergeWithDefaultSettings($container['settings']['database']);
     $settings = $container['settings']['database'];
     $logLevel = $settings['logger']['level'] ?? null;
     $logPath = $settings['logger']['path'] ?? null;
     $className = $settings['classname'] ?? null;
     if (!$className) {
         $className = 'Propel\\Runtime\\Connection\\ConnectionWrapper';
         if ($logLevel == Logger::DEBUG) {
             $className = 'Propel\\Runtime\\Connection\\ProfilerConnectionWrapper';
         }
     }
     $manager = new ConnectionManagerSingle();
     $manager->setConfiguration(['classname' => $className, 'dsn' => $settings['dsn'], 'user' => $settings['user'], 'password' => $settings['password'], 'settings' => $settings['settings']]);
     $manager->setName($settings['connection']);
     /** @var StandardServiceContainer $serviceContainer */
     $serviceContainer = Propel::getServiceContainer();
     $serviceContainer->checkVersion($settings['version']);
     $serviceContainer->setAdapterClass($settings['connection'], $settings['adapter']);
     $serviceContainer->setConnectionManager($settings['connection'], $manager);
     $serviceContainer->setDefaultDatasource($settings['connection']);
     if ($logPath && $logLevel) {
         $logger = new Logger('defaultLogger');
         $logger->pushHandler(new StreamHandler($logPath, $logLevel));
         $serviceContainer->setLogger('defaultLogger', $logger);
         if ($logLevel == Logger::DEBUG) {
             /** @var ConnectionWrapper $con */
             $con = Propel::getConnection();
             $con->useDebug(true);
         }
     }
 }
Пример #24
0
 public function execute(InputInterface $input, OutputInterface $output)
 {
     $configuration = new Configuration(file_get_contents(__DIR__ . '/../../../config/config.json'));
     $resolver = new SpawnResolver($configuration, CpuInfo::detect());
     $factory = new Factory();
     $classname = $resolver->getClassName();
     if ($input->getOption('verbose')) {
         $outputLogger = new StreamHandler('php://stdout');
     } else {
         $outputLogger = new NullHandler();
     }
     $workers = new \ArrayIterator();
     for ($i = 1; $i <= $resolver->getSpawnQuantity(); $i++) {
         $output->write("Launching Worker <info>{$i}</info> ...");
         $logger = new Logger('Worker-' . $i);
         $logger->pushHandler($outputLogger);
         $logger->pushHandler(new RotatingFileHandler(__DIR__ . '/../../../logs/worker-' . $i . '.logs', 3));
         $worker = new Worker('Worker-' . $i, new \GearmanWorker(), $logger);
         foreach ($configuration['gearman-servers'] as $server) {
             $worker->addServer($server['host'], $server['port']);
         }
         $worker->setFunction(new $classname($configuration, $logger, $factory));
         $workers->append($worker);
         $output->writeln("Success !");
     }
     $manager = new ProcessManager(new EventDispatcher());
     $manager->process($workers, function (Worker $worker) {
         $worker->run();
     });
 }
Пример #25
0
 /**
  * @param $name
  * @param $path
  * @param int $level
  * @return LoggerInterface
  */
 public static function newLogger($name, $path, $level = MonoLogger::DEBUG)
 {
     // create a log channel
     $log = new MonoLogger($name);
     $log->pushHandler(new StreamHandler($path, $level));
     return $log;
 }
 /**
  * @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();
 }
Пример #27
0
 /**
  * Verifies that all events are logged.
  */
 public function testListen()
 {
     // create the test sources
     mkdir($this->dir . '/src/a', 0755, true);
     mkdir($this->dir . '/src/b', 0755, true);
     mkdir($this->dir . '/src/c', 0755, true);
     file_put_contents($this->dir . '/src/a/a', 'a');
     file_put_contents($this->dir . '/src/b/b', 'b');
     file_put_contents($this->dir . '/src/c/c', 'c');
     // create the logger
     $handler = new TestHandler();
     $logger = new Logger('test');
     $logger->pushHandler($handler);
     // create the event dispatcher and register the subscriber
     $dispatcher = new EventDispatcher();
     $dispatcher->addSubscriber(new LoggerSubscriber($logger));
     // register the dispatcher with the builder
     $this->builder->setEventDispatcher($dispatcher);
     // build the archive
     $this->builder->addEmptyDir('path/to/d');
     $this->builder->addFile($this->dir . '/src/a/a', 'path/to/e');
     $this->builder->addFromString('path/to/f', 'f');
     $this->builder->buildFromDirectory($this->dir . '/src/b', '/(^test)/');
     $this->builder->buildFromIterator(new ArrayIterator(array('c/c' => $this->dir . '/src/c/c')), $this->dir . '/src/');
     $this->builder->setStub('<?php __HALT_COMPILER();');
     // make sure the log is what we expected
     $records = $handler->getRecords();
     $expected = array(array('message' => 'The empty directory "d" is about to be added.', 'context' => array('local' => 'path/to/d')), array('message' => 'The empty directory "d" has been added.', 'context' => array('local' => 'path/to/d')), array('message' => 'The file "a" is about to be added as "e".', 'context' => array('file' => $this->dir . '/src/a/a', 'local' => 'path/to/e')), array('message' => 'The string is about to be added as "e".', 'context' => array('local' => 'path/to/e')), array('message' => 'The string has been added as "e".', 'context' => array('local' => 'path/to/e')), array('message' => 'The file "a" has been added as "e".', 'context' => array('file' => $this->dir . '/src/a/a', 'local' => 'path/to/e')), array('message' => 'The string is about to be added as "f".', 'context' => array('local' => 'path/to/f')), array('message' => 'The string has been added as "f".', 'context' => array('local' => 'path/to/f')), array('message' => 'The directory "b" is about to be added.', 'context' => array('filter' => '/(^test)/', 'path' => $this->dir . '/src/b')), array('message' => 'The items from the "RegexIterator" iterator are about to be added.', 'context' => array('base' => $this->dir . '/src/b', 'class' => 'Box\\Component\\Builder\\Iterator\\RegexIterator')), array('message' => 'The items from the "RegexIterator" iterator have been added.', 'context' => array('base' => $this->dir . '/src/b', 'class' => 'Box\\Component\\Builder\\Iterator\\RegexIterator')), array('message' => 'The directory "b" has been added.', 'context' => array('filter' => '/(^test)/', 'path' => $this->dir . '/src/b')), array('message' => 'The items from the "ArrayIterator" iterator are about to be added.', 'context' => array('base' => $this->dir . '/src/', 'class' => 'ArrayIterator')), array('message' => 'The path "c" is about to be added as "c".', 'context' => array('path' => $this->dir . '/src/c/c', 'local' => 'c/c')), array('message' => 'The items from the "ArrayIterator" iterator have been added.', 'context' => array('base' => $this->dir . '/src/', 'class' => 'ArrayIterator')), array('message' => 'The custom stub is about to be set.', 'context' => array()), array('message' => 'The custom stub has been set.', 'context' => array()));
     foreach ($expected as $i => $e) {
         self::assertEquals($e['message'], $records[$i]['message']);
         self::assertEquals($e['context'], $records[$i]['context']);
     }
 }
 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);
     }
 }
 public static function doLog($logmethod, array $data, &$output)
 {
     $log = new Logger('ezperflogger');
     // constructor args for the specific handler can be set via ini
     /// @todo how to create resources instead?
     foreach (eZPerfLoggerINI::variable('MonologSettings', 'LogHandlers') as $handlerName) {
         $handlerClass = 'Monolog\\Handler\\' . $handlerName . "Handler";
         if (eZPerfLoggerINI::hasVariable('MonologSettings', 'LogHandler_' . $handlerName)) {
             $r = new ReflectionClass($handlerClass);
             $handler = $r->newInstanceArgs(eZPerfLoggerINI::variable('MonologSettings', 'LogHandler_' . $handlerName));
         } else {
             $handler = new $handlerClass();
         }
         $log->pushHandler($handler);
     }
     // the default severity level: taken from config file
     $level = (int) eZPerfLoggerINI::variable('MonologSettings', 'SeverityLevel');
     // either coalesce messages or not: taken from config file
     if (eZPerfLoggerINI::variable('MonologSettings', 'Coalescevariables') == 'enabled') {
         /// @todo allow via ini file the specification of custom formatters?
         $msg = array();
         foreach ($data as $varname => $value) {
             $msg[] = "{$varname}: {$value}";
         }
         $log->addRecord($level, implode(', ', $msg));
     } else {
         foreach ($data as $varname => $value) {
             $log->addRecord($level, "{$varname}: {$value}");
         }
     }
 }
Пример #30
0
 public static function warning($message, $context = array())
 {
     $logger = new Logger('api_log');
     $file = static::prepare('warning');
     $logger->pushHandler(new StreamHandler($file, Logger::INFO));
     $logger->warning($message, $context);
 }