pushProcessor() public method

Adds a processor in the stack.
public pushProcessor ( callable $callback )
$callback callable
 /**
  * {@inheritDoc}
  */
 public function register(Container $container)
 {
     // Append custom settings with missing params from default settings
     $container['settings']['logger'] = self::mergeWithDefaultSettings($container['settings']['logger']);
     /**
      * Add dependency (DI).
      *
      * @param Container $c
      *
      * @return Logger
      */
     $container['logger'] = function (Container $c) {
         $settings = $c['settings']['logger'];
         $loggerFormat = "[%datetime%] %level_name% %message% %context% %extra%\n";
         $loggerTimeFormat = "Y-m-d H:i:s";
         $loggerTimeZone = new DateTimeZone('Europe/Berlin');
         $logger = new Logger($settings['name']);
         if ($settings['color']) {
             $logger->pushProcessor(new ConsoleColorProcessor());
         }
         $logger->pushProcessor(new CleanupProcessor($settings['trimPaths']));
         $logger->pushProcessor(new IntrospectionProcessor(Logger::WARNING));
         $logger->pushProcessor(new ProcessIdProcessor());
         $logger->pushProcessor(new PsrLogMessageProcessor());
         $logger->setTimezone($loggerTimeZone);
         $logger->useMicrosecondTimestamps(false);
         // Using microseconds is buggy (2016-08-04)
         $formatter = new LineFormatter($loggerFormat, $loggerTimeFormat);
         $formatter->ignoreEmptyContextAndExtra(true);
         $defaultHandler = new StreamHandler('php://stdout', $settings['level'], $bubble = false);
         $defaultHandler->setFormatter($formatter);
         $logger->pushHandler($defaultHandler);
         $errorHandler = new StreamHandler('php://stderr', Logger::ERROR, $bubble = false);
         $errorHandler->setFormatter($formatter);
         $logger->pushHandler($errorHandler);
         // Register logger as default PHP error, exception and shutdown handler
         // Note: Make sure only this handler handles errors (set $callPrevious to false)
         $errorHandler = ErrorHandler::register($logger, $errorLevelMap = false, $exceptionLevelMap = false);
         $errorHandler->registerErrorHandler($levelMap = [], $callPrevious = false);
         $errorHandler->registerExceptionHandler($levelMap = [], $callPrevious = false);
         return $logger;
     };
 }
Beispiel #2
0
 public function work()
 {
     $identity = $this->identify();
     $this->logger->notice(sprintf('%s waiting for work on queue(s) [%s]', $identity, join(', ', $this->queues)));
     for (;;) {
         $job = $this->metro->pop($this->queues, $this);
         if (null !== $job) {
             $jobHandler = $this->metro->createTaskLogHander($job->getId());
             $this->logger->pushHandler($jobHandler);
             $this->logger->pushProcessor(function ($record) use($job) {
                 $record['extra']['job_id'] = $job->getId();
                 return $record;
             });
             $this->workOn($job, $jobHandler);
             $this->logger->popHandler();
             $this->logger->popProcessor();
         }
         if ($this->interval <= 0) {
             return;
         }
         if (null === $job) {
             if ($this->drainMode) {
                 $this->logger->notice(sprintf('%s exiting because all queues are empty', $identity));
                 return;
             }
             usleep($this->interval * 1000.0);
         }
     }
 }
Beispiel #3
0
 public static function ins($space = 'default')
 {
     //获取配置
     $config = \Yaf\Application::app()->getConfig();
     //项目名
     $projName = isset($config->projName) ? strtolower($config->projName) : 'default';
     $channel = $projName . '/' . $space;
     $channelAll = $projName . '/_all';
     if (isset(self::$ins[$channel])) {
         return self::$ins[$channel];
     }
     //日志配置
     if (!isset($config->log)) {
         throw new Exception('must config the logger first.');
     }
     $logger = new MonoLogger($space);
     $syslog = new SyslogHandler($channel, LOG_LOCAL6, self::$logLevels[$config->log->level]);
     $syslogAll = new SyslogHandler($channelAll, LOG_LOCAL6, self::$logLevels[$config->log->level]);
     //设置日志格式
     $formatter = new LineFormatter("%channel% %level_name%: %message% %context% %extra%");
     $syslog->setFormatter($formatter);
     $syslogAll->setFormatter($formatter);
     $logger->pushHandler($syslog);
     $logger->pushHandler($syslogAll);
     //增加pid
     $processor = new ProcessIdProcessor();
     $logger->pushProcessor($processor);
     //与psr3 context保持一致
     $processor = new PsrLogMessageProcessor();
     $logger->pushProcessor($processor);
     self::$ins[$channel] = $logger;
     return self::$ins[$channel];
 }
Beispiel #4
0
 /**
  * Returns a list of all container entries registered by this service provider.
  *
  * - the key is the entry name
  * - the value is a callable that will return the entry, aka the **factory**
  *
  * Factories have the following signature:
  *        function(ContainerInterface $container, callable $getPrevious = null)
  *
  * About factories parameters:
  *
  * - the container (instance of `Interop\Container\ContainerInterface`)
  * - a callable that returns the previous entry if overriding a previous entry, or `null` if not
  *
  * @return callable[]
  */
 public function getServices()
 {
     return [LoggerInterface::class => function () {
         $logger = new Logger("Monolog");
         $logger->pushProcessor(new WebProcessor());
         $logger->pushProcessor(new IntrospectionProcessor());
         $logger->pushHandler(new StreamHandler('php://stderr'));
         return $logger;
     }];
 }
Beispiel #5
0
 /**
  * Make resource to write log
  *
  * @return void
  */
 protected function makeResource()
 {
     $this->resource = new Logger($this->settings['name']);
     foreach ($this->settings['handlers'] as $handler) {
         $this->resource->pushHandler($handler);
     }
     foreach ($this->settings['processors'] as $processor) {
         $this->resource->pushProcessor($processor);
     }
 }
 public function register(\Pimple $pimple)
 {
     $pimple['db.connection'] = $pimple->share(function () {
         $databaseConnector = new DatabaseConnectorService();
         return $databaseConnector->getConnection();
     });
     $pimple['repository'] = $pimple->share(function () {
         return new RepositoryService();
     });
     $pimple['api.auth'] = $pimple->share(function ($pimple) {
         $basicAuthenticationService = new BasicAuthenticationService();
         $basicAuthenticationService->setPasswordService($pimple['password']);
         return $basicAuthenticationService;
     });
     $pimple['password'] = $pimple->share(function () {
         return new PasswordService();
     });
     $pimple['dispatcher'] = $pimple->share(function () {
         return new EventDispatcher();
     });
     $pimple['logger'] = $pimple->share(function () {
         $logger = new Logger('ubirimi.activity');
         $IntrospectionProcessor = new IntrospectionProcessor();
         $webProcessor = new WebProcessor();
         $logger->pushHandler(new StreamHandler(UbirimiContainer::get()['log.path'], Logger::DEBUG));
         $logger->pushHandler(new \DbMonologHandler(), Logger::DEBUG);
         $logger->pushProcessor($IntrospectionProcessor);
         $logger->pushProcessor($webProcessor);
         return $logger;
     });
     $pimple['email'] = $pimple->share(function ($pimple) {
         return new EmailService($pimple['session']);
     });
     $pimple['client'] = $pimple->share(function ($pimple) {
         return new ClientService();
     });
     $pimple['user'] = $pimple->share(function ($pimple) {
         return new UserService($pimple['session']);
     });
     $pimple['login.time'] = $pimple->share(function ($pimple) {
         return new LoginTimeService();
     });
     $pimple['session'] = $pimple->share(function () {
         $lastDot = strrpos($_SERVER['SERVER_NAME'], '.');
         $secondToLastDot = strrpos($_SERVER['SERVER_NAME'], '.', $lastDot - strlen($_SERVER['SERVER_NAME']) - 1);
         $storage = new NativeSessionStorage(array('cookie_domain' => substr($_SERVER['SERVER_NAME'], $secondToLastDot)), new NativeFileSessionHandler());
         return new Session($storage, new NamespacedAttributeBag(), new AutoExpireFlashBag());
     });
     $pimple['warmup'] = $pimple->share(function ($pimple) {
         return new WarmUpService($pimple['session']);
     });
     $pimple['savant'] = $pimple->share(function () {
         return new \Savant3(array('template_path' => array(__DIR__ . '/../Yongo/Resources/views/email/', __DIR__ . '/../GeneralSettings/Resources/views/email/', __DIR__ . '/../Calendar/Resources/views/email/', __DIR__ . '/../SvnHosting/Resources/views/email/', __DIR__ . '/../Resources/views/email')));
     });
 }
 public function testLogsFileAndLineWhenUsingIntrospectionProcessor()
 {
     $this->logger->pushProcessor(new IntrospectionProcessor());
     $this->logger->warning('a warning');
     $line = __LINE__;
     $log = $this->pdo->query('SELECT * FROM logs')->fetch();
     $this->assertTrue(isset($log['file']));
     $this->assertTrue(isset($log['line']));
     $this->assertEquals($log['message'], 'a warning');
     $this->assertEquals($log['file'], __FILE__);
     $this->assertEquals($log['line'], $line);
 }
 /**
  * getLogger
  *
  * @param OutputInterface $output
  * @param string $clothing
  *
  * @return LoggerInterface
  */
 protected function getLogger(OutputInterface $output, $clothing)
 {
     $logger = new Logger($clothing);
     $logger->pushHandler(new GelfHandler(new Publisher(new UdpTransport('127.0.0.1', 12201))));
     if ('bermuda' === $clothing) {
         $logger->pushHandler(new ConsoleHandler($output));
     }
     $logger->pushProcessor(new MemoryUsageProcessor(true, false));
     $logger->pushProcessor(new IntrospectionProcessor());
     $logger->pushProcessor(new PsrLogMessageProcessor());
     return $logger;
 }
Beispiel #9
0
 public static function init()
 {
     if (!self::$logger instanceof Mlogger) {
         strtolower(C('LOG_TYPE')) == 'monolog' && C('SHOW_PAGE_TRACE', false);
         // 关闭, 以将日志记录到 \Think\Log::$log
         self::$logger = new Mlogger('Monolog');
         $handler = new StreamHandler(C('LOG_PATH') . date('y_m_d') . '.log', Logger::DEBUG);
         $handler->getFormatter()->allowInlineLineBreaks();
         $handler->getFormatter()->ignoreEmptyContextAndExtra();
         self::$logger->pushProcessor(new WebProcessor());
         self::$logger->pushHandler($handler);
         // 文件
     }
 }
Beispiel #10
0
 public function loadDependencyDefaults(ContainerInterface $container)
 {
     // logger
     $container['logger'] = function (ContainerInterface $c) {
         $settings = $c->get('settings')['logger'];
         $debug = array_key_exists('debug', $settings) && $settings['debug'];
         $logger = new Logger($settings['name']);
         $logger->pushProcessor(new UidProcessor());
         $logger->pushHandler(new StreamHandler($settings['path'], $debug ? Logger::DEBUG : Logger::ERROR));
         return $logger;
     };
     // entity manager
     $container['entityManager'] = function (ContainerInterface $c) {
         $settings = $c->get('settings')['database'];
         $config = new Configuration();
         $config->setMetadataCacheImpl(new ArrayCache());
         $driverImpl = $config->newDefaultAnnotationDriver(array(__DIR__ . '/Entity'));
         $config->setMetadataDriverImpl($driverImpl);
         $config->setProxyDir(__DIR__ . '/Entity/Proxy');
         $config->setProxyNamespace('Proxy');
         return EntityManager::create($settings, $config);
     };
     $container['foundHandler'] = function () {
         return new RequestResponseArgs();
     };
     $container['dataFormatter'] = function () {
         return new ResponseDataFormatter();
     };
     return $container;
 }
Beispiel #11
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;
 }
Beispiel #12
0
 /**
  * Setup logging
  */
 protected function setupLogging()
 {
     $path = $this->_config->getVarPath() . '/log';
     //create an access log with browser information
     $accessLog = new \Monolog\Logger('access');
     $accessLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/access_log'));
     $accessMessage = "[{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']} {$_SERVER['SERVER_PROTOCOL']}] " . '[' . (!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-') . '] ' . '[' . (!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-') . ']';
     $accessLog->addInfo($accessMessage);
     //create an authenticationLog
     $this->_authLog = new \Monolog\Logger('authentication');
     $this->_authLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/authentication_log'));
     //create an authenticationLog
     $this->_404Log = new \Monolog\Logger('404');
     $this->_404Log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/404_log'));
     $this->_log = new \Monolog\Logger('jazzee');
     $this->_log->pushProcessor(new \Monolog\Processor\WebProcessor());
     $this->_log->pushProcessor(new \Monolog\Processor\IntrospectionProcessor());
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/strict_log'));
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/messages_log', \Monolog\Logger::INFO));
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/error_log', \Monolog\Logger::ERROR));
     $this->_log->pushHandler(new \Monolog\Handler\SyslogHandler('jazzee', 'syslog', \Monolog\Logger::ERROR));
     //Handle PHP errors with out logs
     set_error_handler(array($this, 'handleError'));
     //catch any excpetions
     set_exception_handler(array($this, 'handleException'));
 }
Beispiel #13
0
 /**
  * Pulls all pending builds from the database and runs them.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->output = $output;
     // For verbose mode we want to output all informational and above
     // messages to the symphony output interface.
     if ($input->hasOption('verbose') && $input->getOption('verbose')) {
         $this->logger->pushHandler(new OutputLogHandler($this->output, Logger::INFO));
     }
     $running = $this->validateRunningBuilds();
     $this->logger->pushProcessor(new LoggedBuildContextTidier());
     $this->logger->addInfo(Lang::get('finding_builds'));
     $store = Factory::getStore('Build');
     $result = $store->getByStatus(0, $this->maxBuilds);
     $this->logger->addInfo(Lang::get('found_n_builds', count($result['items'])));
     $builds = 0;
     while (count($result['items'])) {
         $build = array_shift($result['items']);
         $build = BuildFactory::getBuild($build);
         // Skip build (for now) if there's already a build running in that project:
         if (!$this->isFromDaemon && in_array($build->getProjectId(), $running)) {
             $this->logger->addInfo(Lang::get('skipping_build', $build->getId()));
             $result['items'][] = $build;
             // Re-run build validator:
             $running = $this->validateRunningBuilds();
             continue;
         }
         $builds++;
         try {
             // Logging relevant to this build should be stored
             // against the build itself.
             $buildDbLog = new BuildDBLogHandler($build, Logger::INFO);
             $this->logger->pushHandler($buildDbLog);
             $builder = new Builder($build, $this->logger);
             $builder->execute();
             // After execution we no longer want to record the information
             // back to this specific build so the handler should be removed.
             $this->logger->popHandler($buildDbLog);
         } catch (\Exception $ex) {
             $build->setStatus(Build::STATUS_FAILED);
             $build->setFinished(new \DateTime());
             $build->setLog($build->getLog() . PHP_EOL . PHP_EOL . $ex->getMessage());
             $store->save($build);
         }
     }
     $this->logger->addInfo(Lang::get('finished_processing_builds'));
     return $builds;
 }
 public function getLogger()
 {
     $logger = new Logger('foo');
     $logger->pushHandler($handler = new TestHandler());
     $logger->pushProcessor(new PsrLogMessageProcessor());
     $handler->setFormatter(new LineFormatter('%level_name% %message%'));
     $this->handler = $handler;
     return $logger;
 }
Beispiel #15
0
 /**
  * @param ContainerInterface $c
  * @return Logger
  */
 public function __invoke(ContainerInterface $c)
 {
     $var_dir = $c->get('settings')['var-dir'];
     $logger = new Logger('App');
     $logger->pushProcessor(new UidProcessor());
     $logger->pushHandler(new StreamHandler($var_dir . '/logs/app.log', Logger::DEBUG));
     $logger->pushHandler(new StreamHandler($var_dir . '/logs/app-error.log', Logger::ERROR));
     return $logger;
 }
 public function indexAction()
 {
     // create a log channel
     $log = new Logger('name');
     $log->pushHandler(new StreamHandler(LOG_PATH, Logger::WARNING));
     // add records to the log
     $log->addWarning('Foo', array('username' => 'Seldaek'));
     $log->addError('Bar');
     $log->pushProcessor(function ($record) {
         $record['extra']['dummy'] = 'Hello world!';
         return $record;
     });
     exit;
     $em = $this->getEntityManager();
     //         $user = new \Application\Entity\AssUser();
     //         $objectManager->persist($user);
     // //         $objectManager->flush();
     $user = $em->find("Application\\Entity\\AssUser", 2);
     $myFirstComment = new \Application\Entity\AssComment();
     $user->setFirstComment($myFirstComment);
     $em->persist($myFirstComment);
     $em->flush();
     //         $user = new \Application\Entity\User();
     //         $user->setName('engineer');
     //         $objectManager->persist($user);
     //         $objectManager->flush();
     //         $productIds = array(1,2,3);
     //         $reporter = $objectManager->find("Application\Entity\User", 2);
     //         $engineer = $objectManager->find("Application\Entity\User", 3);
     //         if (!$reporter || !$engineer) {
     //             echo "No reporter and/or engineer found for the input.\n";
     //             exit(1);
     //         }
     //         $bug = new \Application\Entity\Bug();
     //         $bug->setDescription("Something does not work!");
     //         $bug->setCreated(new \DateTime("now"));
     //         $bug->setStatus("OPEN");
     //         foreach ($productIds as $productId) {
     //             $product = $objectManager->find("Application\Entity\Product", $productId);
     //             $bug->assignToProduct($product);
     //         }
     //         $bug->setReporter($reporter);
     //         $bug->setEngineer($engineer);
     //         $objectManager->persist($bug);
     //         $objectManager->flush();
     //         echo "Your new Bug Id: ".$bug->getId()."\n";
     //         $product = new \Application\Entity\Product();
     //         $product->setName('test');
     //         $objectManager->persist($product);
     //         $objectManager->flush();
     //         var_dump($product);
     //         Debug::dump($product);
     //         $objectManager->clear();
     //         $objectManager->close();
     return new ViewModel();
 }
 public function register(Container $c)
 {
     $c['logger'] = function ($c) {
         $settings = $c->get('settings')['logger'];
         $logger = new Logger($settings['name']);
         $logger->pushProcessor(new UidProcessor());
         $logger->pushHandler(new StreamHandler($settings['path'], Logger::DEBUG));
         return $logger;
     };
 }
 public function register(ContainerInterface $container)
 {
     $config = $this->getConfig();
     $container['logger'] = function () use($config) {
         $logger = new Logger($config['name']);
         $logger->pushProcessor(new WebProcessor());
         $logger->pushHandler(new StreamHandler($config['path'], Logger::DEBUG));
         return $logger;
     };
 }
 /**
  * @param Logger $logger
  */
 public function resetLogger(Logger $logger)
 {
     if (count($logger->getProcessors()) > 0) {
         $logger->popProcessor();
     }
     $logger->pushProcessor(function ($record) {
         $record['context']['ReqID'] = $this->getConfig()->req_id;
         return $record;
     });
 }
Beispiel #20
0
 /**
  * @param ServiceLocatorInterface $sl
  * @param LoggerOptions $options
  * @return Logger
  */
 public function create(ServiceLocatorInterface $sl, LoggerOptions $options)
 {
     $name = $options->getName();
     if (!$name) {
         throw new Exception\InvalidArgumentException('Logger must have a name');
     }
     $logger = new Logger($name);
     $tags = $options->getTags();
     if (!empty($tags)) {
         $tagProcessor = new TagProcessor($tags);
         $logger->pushProcessor($tagProcessor);
     }
     foreach ($options->getProcessors() as $processor) {
         if (is_string($processor)) {
             /** @var callable $processor */
             $processor = $sl->get("monolog.processor.{$processor}");
         } elseif (is_array($processor)) {
             if (empty($processor['type'])) {
                 throw new Exception\InvalidArgumentException('Type of processor must be specified');
             }
             $type = $processor['type'];
             unset($processor['type']);
             $processor = $sl->get(ProcessorPluginManager::class)->get($type, $processor);
         }
         $logger->pushProcessor($processor);
     }
     foreach ($options->getHandlers() as $handler) {
         if (is_string($handler)) {
             $handler = $sl->get("monolog.handler.{$handler}");
         } elseif (is_array($handler)) {
             if (empty($handler['type'])) {
                 throw new Exception\InvalidArgumentException('Type of handler must be specified');
             }
             $type = $handler['type'];
             unset($handler['type']);
             $handler = $sl->get(HandlerPluginManager::class)->get($type, $handler);
         }
         /** @var HandlerInterface $handler */
         $logger->pushHandler($handler);
     }
     return $logger;
 }
Beispiel #21
0
 public function testCompilesWithoutErrors()
 {
     $command = new MergeSourceCommand($this->testKernel);
     $compiler = $command->createCompiler();
     if ($this->isDebug()) {
         $logger = new Logger('K2', [new StreamHandler('php://stderr')]);
         $logger->pushProcessor(new PsrLogMessageProcessor());
         $compiler->setLogger($logger);
     }
     $compiler->compile();
 }
Beispiel #22
0
 public function testLogsToFile()
 {
     $monolog = new Logger("ROBIN");
     $monolog->pushHandler(new StreamHandler(__DIR__ . '/logs/robin.log'));
     $monolog->pushProcessor(new IntrospectionProcessor());
     $logger = new RobinLogger($monolog);
     $logger->sendError(new Orders(), 500, "Missing Data", ['blaat' => 'blaat']);
     $content = $this->getLog();
     $this->assertContains('blaat', $content);
     $this->deleteLog();
 }
 /**
  * @param ServiceLocatorInterface|ContainerInterface $container
  * @param MonologOptions $options
  * @return Logger
  */
 public function createLogger($container, MonologOptions $options)
 {
     $logger = new Logger($options->getName());
     $handlers = array_reverse($options->getHandlers());
     foreach ($handlers as $handler) {
         $logger->pushHandler($this->createHandler($container, $options, $handler));
     }
     foreach ($options->getProcessors() as $processor) {
         $logger->pushProcessor($this->createProcessor($container, $processor));
     }
     return $logger;
 }
Beispiel #24
0
 /**
  * Add Reporter configuration to the main monolog
  *
  * @return $this
  */
 public function boot()
 {
     // Create a new log file for reporter
     $stream = new StreamHandler(storage_path('logs/reporter.log'), Logger::DEBUG);
     $this->logger->pushHandler($stream);
     // Apply the Reporter formatter
     $formatter = new Formatter();
     $stream->setFormatter($formatter);
     // Log to standard PHP log
     if (config('reporter.error_log')) {
         $stdout = new ErrorLogHandler();
         $this->logger->pushHandler($stdout);
         $stdout->setFormatter($formatter);
     }
     // Add custom and built in processors
     $this->logger->pushProcessor(Timer::getFacadeRoot());
     $this->logger->pushProcessor(new MemoryUsageProcessor());
     $this->logger->pushProcessor(new MemoryPeakUsageProcessor());
     $this->logger->pushProcessor(new WebProcessor());
     // Enable chainig
     return $this;
 }
/**
 * @param string $log_file
 *
 * @return Log\LoggerInterface
 */
function build_logger($log_file)
{
    $site_id = get_current_blog_id();
    $logger = new Monolog\Logger("IAC-DEBUG-{$site_id}");
    $logger->pushHandler(new Monolog\Handler\RotatingFileHandler($log_file));
    $logger->pushProcessor(new Monolog\Processor\UidProcessor());
    /**
     * @param Monolog\Logger $logger
     *
     * @return Log\LoggerInterface
     */
    return apply_filters('iac_debugger_psr_logger', $logger, $log_file);
}
Beispiel #26
0
 /**
  * Создаем объект логгера нужного типа.
  * @param string $type Тип логгера.
  * @return Logger Экземпляр логгера.
  */
 private static function createLogger($type)
 {
     $Logger = new Logger($type);
     foreach (Config::getInstance()->get('logger', 'handlers') as $handlerType => $handlerConfig) {
         $Handler = static::createHandler($handlerType, $handlerConfig);
         if (!$Handler) {
             continue;
         }
         $Handler->setFormatter(static::createLogFormatter($handlerConfig));
         $Logger->pushHandler($Handler);
     }
     $Logger->pushProcessor(new GlobalContextProcessor());
     return $Logger;
 }
Beispiel #27
0
function useTick($concurrent, $numberOfJobs)
{
    $logger = new Logger('swarm_logger');
    $logger->pushProcessor(new MemoryUsageProcessor());
    $swarm = new SwarmProcess($logger);
    $swarm->setMaxRunStackSize($concurrent);
    $counter = 0;
    // Now go run it:
    do {
        // If we have work to give the stack, then let's give it:
        if (++$counter <= $numberOfJobs) {
            $swarm->pushNativeCommandOnQueue(getCommand());
        }
    } while ($swarm->tick());
}
Beispiel #28
0
 /**
  * @param string $logName
  * @param string $stream
  *
  * @return \Monolog\Logger $logger
  */
 public function createInstance($logName, $stream, $logLevel = \Monolog\Logger::ERROR)
 {
     if (!isset($logName, $stream)) {
         throw new \InvalidArgumentException('The $logName and $stream
          parameters are required');
     }
     $logger = new Logger($logName);
     $logger->pushHandler(new NewRelicHandler());
     $logger->pushProcessor(new RequestIdProcessor());
     $streamHandler = new StreamHandler($stream, $logLevel);
     $formatter = new Formatter\LogstashFormatter($logName);
     $streamHandler->setFormatter($formatter);
     $logger->pushHandler($streamHandler);
     return $logger;
 }
Beispiel #29
0
 /**
  * Pulls all pending builds from the database and runs them.
  */
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $this->output = $output;
     // For verbose mode we want to output all informational and above
     // messages to the symphony output interface.
     if ($input->hasOption('verbose')) {
         $this->logger->pushHandler(new OutputLogHandler($this->output, Logger::INFO));
     }
     $this->logger->pushProcessor(new LoggedBuildContextTidier());
     $this->logger->addInfo("Finding builds to process");
     $store = Factory::getStore('Build');
     $result = $store->getByStatus(0, $this->maxBuilds);
     $this->logger->addInfo(sprintf("Found %d builds", count($result['items'])));
     $builds = 0;
     foreach ($result['items'] as $build) {
         $builds++;
         $build = BuildFactory::getBuild($build);
         try {
             // Logging relevant to this build should be stored
             // against the build itself.
             $buildDbLog = new BuildDBLogHandler($build, Logger::INFO);
             $this->logger->pushHandler($buildDbLog);
             $builder = new Builder($build, $this->logger);
             $builder->execute();
             // After execution we no longer want to record the information
             // back to this specific build so the handler should be removed.
             $this->logger->popHandler($buildDbLog);
         } catch (\Exception $ex) {
             $build->setStatus(Build::STATUS_FAILED);
             $build->setLog($build->getLog() . PHP_EOL . PHP_EOL . $ex->getMessage());
             $store->save($build);
         }
     }
     $this->logger->addInfo("Finished processing builds");
     return $builds;
 }
Beispiel #30
0
 /**
  * creates a \Monolog\Logger instance
  *
  * @param bool $debug If true the debug logging mode will be enabled
  *
  * @return \Monolog\Logger
  */
 public function create($debug = false)
 {
     $logger = new Logger('browscap');
     if ($debug) {
         $stream = new StreamHandler('php://output', Logger::DEBUG);
         $stream->setFormatter(new LineFormatter('[%datetime%] %channel%.%level_name%: %message% %extra%' . "\n"));
         /** @var callable $memoryProcessor */
         $memoryProcessor = new MemoryUsageProcessor(true);
         $logger->pushProcessor($memoryProcessor);
         /** @var callable $peakMemoryProcessor */
         $peakMemoryProcessor = new MemoryPeakUsageProcessor(true);
         $logger->pushProcessor($peakMemoryProcessor);
     } else {
         $stream = new StreamHandler('php://output', Logger::INFO);
         $stream->setFormatter(new LineFormatter('[%datetime%] %message% %extra%' . "\n"));
         /** @var callable $peakMemoryProcessor */
         $peakMemoryProcessor = new MemoryPeakUsageProcessor(true);
         $logger->pushProcessor($peakMemoryProcessor);
     }
     $logger->pushHandler($stream);
     $logger->pushHandler(new ErrorLogHandler(ErrorLogHandler::OPERATING_SYSTEM, Logger::NOTICE));
     ErrorHandler::register($logger);
     return $logger;
 }