コード例 #1
0
ファイル: ImportCommand.php プロジェクト: apioo/fusio-impl
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $file = $input->getArgument('file');
     if (!is_file($file)) {
         throw new RuntimeException('File does not exists');
     }
     $verbose = $output->getVerbosity() > OutputInterface::VERBOSITY_NORMAL;
     if (!$verbose) {
         $this->logger->pushHandler(new NullHandler());
     }
     try {
         $this->connection->beginTransaction();
         $result = $this->importService->import(file_get_contents($file));
         $this->connection->commit();
         $output->writeln('Import successful!');
         $output->writeln('The following actions were done:');
         $output->writeln('');
         foreach ($result as $message) {
             $output->writeln('- ' . $message);
         }
     } catch (\Exception $e) {
         $this->connection->rollback();
         $output->writeln('An exception occured during import. No changes are applied to the database.');
         $output->writeln('');
         $output->writeln('Message: ' . $e->getMessage());
         $output->writeln('Trace: ' . $e->getTraceAsString());
     }
     if (!$verbose) {
         $this->logger->popHandler();
     }
 }
コード例 #2
0
 /**
  * Set up test environment
  */
 public function setUp()
 {
     parent::setUp();
     $this->link = new \MySQLi('localhost', 'root', '');
     if ($this->link->connect_error) {
         throw new \RuntimeException('Failed to connect to database. MySQL said: ' . $this->link->connect_error);
     }
     if (!$this->link->select_db('activecollab_jobs_queue_commands_test')) {
         throw new \RuntimeException('Failed to select database.');
     }
     $this->connection = new MysqliConnection($this->link);
     $this->queue = new MySqlQueue($this->connection);
     $this->dispatcher = new Dispatcher($this->queue);
     $this->log_file_path = dirname(__DIR__) . '/logs/' . date('Y-m-d') . '.txt';
     if (is_file($this->log_file_path)) {
         unlink($this->log_file_path);
     }
     $this->log = new Logger('cli');
     $handler = new StreamHandler($this->log_file_path, Logger::DEBUG);
     $formatter = new LineFormatter();
     $formatter->includeStacktraces(true);
     $handler->setFormatter($formatter);
     $this->log->pushHandler($handler);
     $this->container = new Container(['dispatcher' => $this->dispatcher, 'log' => $this->log]);
 }
コード例 #3
0
 /**
  * {@inheritdoc}
  */
 public function collect(RequestObject $requestObject, array $parameters = [])
 {
     $parameters = $this->resolveCollectorParameters($parameters);
     $logFile = sprintf('%s/%s.%s', $this->logFolder, $this->kernelEnvironment, $parameters['logFile']);
     $this->logger->pushHandler(new StreamHandler($logFile));
     $this->logger->info('request_collector.collect', $this->serializer->normalize($requestObject));
 }
コード例 #4
0
ファイル: TestCase.php プロジェクト: activecollab/insight
 /**
  * {@inheritdoc}
  */
 public function setUp()
 {
     parent::setUp();
     $this->log = $log = new Logger('Insight test');
     $this->log->pushHandler(new NullHandler());
     $this->current_timestamp = new DateTimeValue();
     DateTimeValue::setTestNow($this->current_timestamp);
 }
コード例 #5
0
ファイル: LoggerTest.php プロジェクト: oqq/minc-log
 /**
  * @inheritdoc
  */
 public function setUp()
 {
     $this->handler = new ArrayHandler();
     $this->handler->setFormatter(new LineFormatter('%level_name% %message%'));
     $this->logger = new Logger('test');
     $this->logger->pushHandler($this->handler);
     $this->logger->pushProcessor(new ContextReplacementProcessor());
 }
コード例 #6
0
ファイル: LogSubscriber.php プロジェクト: assad2012/EvaOAuth
 public function __construct($logger = null, $formatter = null)
 {
     if ($logger instanceof LoggerInterface) {
         $this->logger = $logger;
     } else {
         $this->logger = new Logger('EvaOAuth');
         $this->logger->pushHandler(new StreamHandler($logger, Logger::DEBUG));
     }
     $this->formatter = $formatter instanceof Formatter ? $formatter : new Formatter($formatter);
 }
コード例 #7
0
ファイル: Monitor.php プロジェクト: huyanping/log-monitor
 /**
  * @param LoggerInterface $logger
  */
 public function __construct(LoggerInterface $logger = null)
 {
     if (is_null($logger)) {
         $this->logger = new Logger("monitor");
         $this->logger->pushHandler(new NullHandler());
     } else {
         $this->logger = $logger;
     }
     $this->pool = new Pool();
 }
コード例 #8
0
ファイル: Crontab.php プロジェクト: u0mo5/php_crontab
 /**
  * @param LoggerInterface|null $logger
  * @param Mission[]|null $missions
  */
 public function __construct(LoggerInterface $logger = null, $missions = null)
 {
     set_time_limit(0);
     if (is_null($logger)) {
         $this->logger = new Logger(self::NAME);
         $this->logger->pushHandler(new NullHandler());
     } else {
         $this->logger = $logger;
     }
     $this->batchAddMissions($missions);
 }
コード例 #9
0
 protected function execute(InputInterface $input, OutputInterface $output)
 {
     $parameters = ['host' => $input->getArgument('host'), 'user' => $input->getArgument('username'), 'password' => $input->getArgument('password'), 'dbname' => $input->getArgument('database'), 'driver' => $input->getArgument('driver'), 'charset' => 'utf8'];
     $this->connection = $this->getContainer()->get('doctrine.dbal.connection_factory')->createConnection($parameters);
     $this->em = $this->getContainer()->get('doctrine.orm.entity_manager');
     $path = $this->getContainer()->getParameter('kernel.root_dir') . '/logs/import.log';
     $this->logger = $this->getContainer()->get('logger');
     $this->logger->pushHandler(new StreamHandler($path, Logger::INFO));
     if ($input->getOption('disable-logging')) {
         $this->disableLoggableExtension();
     }
 }
コード例 #10
0
ファイル: Log.php プロジェクト: romeoz/rock
 public function __construct($config = [])
 {
     $this->parentConstruct($config);
     if (isset($this->logger)) {
         return;
     }
     $this->logger = new Logger('Rock');
     if (!$this->handlers) {
         $this->handlers = $this->defaultHandlers();
     }
     foreach ($this->handlers as $level => $ahndler) {
         $this->logger->pushHandler($ahndler);
     }
 }
コード例 #11
0
 public static function getLogger()
 {
     if (!self::$logger) {
         self::$logger = new Logger(KBGDC_APP_NAME);
         if (getenv('KBGDC_PAPERTRAIL_PORT')) {
             $handler = new SyslogUdpHandler("logs.papertrailapp.com", getenv('KBGDC_PAPERTRAIL_PORT'));
         } else {
             $handler = new SyslogHandler(KBGDC_APP_NAME);
         }
         $handler->setFormatter(new JsonFormatter());
         self::$logger->pushHandler($handler);
     }
     return self::$logger;
 }
コード例 #12
0
ファイル: LoggerFactory.php プロジェクト: phxlol/lol-php-api
 /**
  * @param string $name
  * @param bool   $saveOnRedis
  *
  * @return LoggerInterface
  */
 public static function create($name = 'EloGankAPI', $saveOnRedis = false)
 {
     if (!isset(self::$logger)) {
         $verbosity = constant('Monolog\\Logger::' . strtoupper(ConfigurationLoader::get('log.verbosity')));
         self::$logger = new Logger($name, array(new ConsoleHandler(new ConsoleOutput(), true, array(OutputInterface::VERBOSITY_NORMAL => $verbosity, OutputInterface::VERBOSITY_VERBOSE => Logger::DEBUG, OutputInterface::VERBOSITY_VERY_VERBOSE => Logger::DEBUG, OutputInterface::VERBOSITY_DEBUG => Logger::DEBUG)), new RotatingFileHandler(ConfigurationLoader::get('log.path'), ConfigurationLoader::get('log.max_file'), $verbosity)));
         // Allow the server to retrieve clients logs
         if (true === ConfigurationLoader::get('client.async.enabled')) {
             self::$redisClient = new Client(sprintf('tcp://%s:%s', ConfigurationLoader::get('client.async.redis.host'), ConfigurationLoader::get('client.async.redis.port')));
             if ($saveOnRedis) {
                 self::$logger->pushHandler(new RedisHandler(self::$redisClient, ConfigurationLoader::get('client.async.redis.key') . '.client.logs', $verbosity));
             }
         }
     }
     return self::$logger;
 }
コード例 #13
0
ファイル: Logging.php プロジェクト: bllevy2/projectRena
 /**
  * @param $app
  */
 public function __construct(RenaApp $app)
 {
     $this->app = $app;
     $this->logger = new Logger('projectRena');
     $logFile = $this->app->baseConfig->getConfig('logFile', 'Logging', __DIR__ . '/../../logs/app.log');
     // Make sure the logfile exists and is writeable
     if (!is_writable($logFile)) {
         chmod($logFile, 0777);
     }
     if (!file_exists($logFile)) {
         file_put_contents($logFile, "");
     }
     // Setup the push handler
     $this->logger->pushHandler(new StreamHandler($logFile, $this->app->baseConfig->getConfig("logLevel", "Logging", 100), true, 0777));
 }
コード例 #14
0
ファイル: Mail.php プロジェクト: aldoanizio/carteiro
 /**
  * Set different debug file location.
  *
  * @access  public
  * @param   string          $path  File path
  * @return  \carteiro\Mail
  */
 public function debugFilePath($path)
 {
     $this->debug(true);
     $this->logger->popHandler();
     $this->logger->pushHandler(new StreamHandler($path, Logger::DEBUG));
     return $this;
 }
コード例 #15
0
 /**
  * @codeCoverageIgnore
  * @return LoggerInterface
  */
 public function getLogger()
 {
     if (!$this->logger instanceof LoggerInterface) {
         $this->logger = new Logger(__CLASS__);
         $this->logger->pushHandler(new NullHandler());
     }
     return $this->logger;
 }
コード例 #16
0
 /**
  * Set the client Logger
  *
  * @throws PhpOrientException
  */
 public function setLogger()
 {
     if (ClientConstants::$LOGGING) {
         if ($this->_logger === null) {
             if (!class_exists('\\Monolog\\Logger', true)) {
                 throw new PhpOrientException("No development environment installed from composer. Try 'composer update' or remove logging from client constants ( \\PhpOrient\\Configuration\\Constants::\$LOGGING )");
             }
             $this->_logger = new \Monolog\Logger(get_class($this));
             $file_path = "php://stdout";
             if (ClientConstants::$LOG_FILE_PATH) {
                 $file_path = ClientConstants::$LOG_FILE_PATH;
             }
             $handler = new \Monolog\Handler\StreamHandler($file_path, \Monolog\Logger::DEBUG);
             $handler->setFormatter(new \Monolog\Formatter\LineFormatter(null, null, false, true));
             $this->_logger->pushHandler($handler);
         }
     } else {
         $this->_logger = new NullLogger();
     }
 }
コード例 #17
0
 /**
  * Run the invoke system for testing.
  *
  * @param array $settings Include:
  *                        method (GET/POST/PUT/OPTIONS)
  *                        setHeaders (array): additional headers sending in (such as origin)
  *                        configuration (array) Configuration data to pass in.
  *
  * @throws \Exception If configuration settings are missing.
  *
  * @return array
  */
 private function runInvoke(array $settings)
 {
     if (false === isset($settings['method']) || false === isset($settings['setHeaders']) || false === isset($settings['configuration'])) {
         throw new \Exception('Missing settings');
     }
     $sut = new MiddlewareCors($settings['configuration']);
     // sanity check
     $this->assertInstanceOf('Bairwell\\MiddlewareCors', $sut);
     $sutSettings = array_merge($this->defaults, $settings['configuration']);
     $this->arraysAreSimilar($sutSettings, $sut->getSettings(), 'Matching internal settings');
     // setup the logger
     $this->logger = new Logger('test');
     $this->testLogger = new TestHandler();
     $this->logger->pushHandler($this->testLogger);
     $sut->setLogger($this->logger);
     // set up the request
     $request = $this->getMockForAbstractClass('\\Psr\\Http\\Message\\ServerRequestInterface');
     $request->expects($this->any())->method('getMethod')->willReturn($settings['method']);
     $request->expects($this->any())->method('getHeaderLine')->willReturnCallback(function ($headerName) use($settings) {
         if (true === isset($settings['setHeaders'][$headerName])) {
             return $settings['setHeaders'][$headerName];
         } else {
             return '';
         }
     });
     // now setup the response stack.
     $responseCalls = [];
     $response = $this->getMockForAbstractClass('\\Psr\\Http\\Message\\ResponseInterface');
     $response->expects($this->any())->method('withAddedHeader')->will($this->returnCallback(function ($k, $v) use(&$responseCalls, $response) {
         $responseCalls['withAddedHeader:' . $k] = $v;
         return $response;
     }));
     $response->expects($this->any())->method('withHeader')->will($this->returnCallback(function ($k, $v) use(&$responseCalls, $response) {
         $responseCalls['withHeader:' . $k] = $v;
         return $response;
     }));
     $response->expects($this->any())->method('withoutHeader')->will($this->returnCallback(function ($k) use(&$responseCalls, $response) {
         $responseCalls['withoutHeader:' . $k] = true;
         return $response;
     }));
     $response->expects($this->any())->method('withStatus')->will($this->returnCallback(function ($k, $v) use(&$responseCalls, $response) {
         $responseCalls['withStatus'] = $k . ':' . $v;
         return $response;
     }));
     $next = function ($req, $res) use(&$responseCalls, $response) {
         $responseCalls['calledNext'] = 'called';
         return $response;
     };
     $returnedResponse = $sut->__invoke($request, $response, $next);
     return $responseCalls;
 }
コード例 #18
0
 /**
  * Returns a stream instance for logging data on the socket connection.
  *
  * @return \Psr\Log\LoggerInterface
  */
 public function getLogger()
 {
     if (!$this->logger) {
         // See testGetLoggerRunFromStdin
         // @codeCoverageIgnoreStart
         $stderr = defined('\\STDERR') && !is_null(\STDERR) ? \STDERR : fopen('php://stderr', 'w');
         // @codeCoverageIgnoreEnd
         $handler = new StreamHandler($stderr, Logger::DEBUG);
         $handler->setFormatter(new LineFormatter("%datetime% %level_name% %message% %context%\n"));
         $this->logger = new Logger(get_class($this));
         $this->logger->pushHandler($handler);
     }
     return $this->logger;
 }
コード例 #19
0
ファイル: ApiExecutor.php プロジェクト: apioo/fusio-impl
 /**
  * @param string $method
  * @param string $path
  * @param array|null $body
  * @return mixed
  */
 public function request($method, $path, $body = null, $verbose = false)
 {
     $header = ['User-Agent' => 'Fusio-System v' . Base::getVersion(), 'Authorization' => 'Bearer ' . $this->getAccessToken()];
     $body = $body !== null ? Parser::encode($body) : null;
     $request = new Request(new Url('http://127.0.0.1/backend/' . $path), $method, $header, $body);
     $response = new Response();
     $response->setBody(new TempStream(fopen('php://memory', 'r+')));
     $this->logger->pushHandler($verbose ? new StreamHandler(STDOUT) : new NullHandler());
     $this->dispatch->route($request, $response, null, false);
     $this->logger->popHandler();
     $body = (string) $response->getBody();
     $data = Parser::decode($body, false);
     return $data;
 }
コード例 #20
0
 private function setHandlerFromConfig(string $name, array $handler) : self
 {
     $handlerInstance = $this->getHandlerInstance($name, $handler);
     if (false === empty($handler['formatter'])) {
         $formatter = $this->getFormatterFromConfig($handler['formatter']);
         $handlerInstance->setFormatter($formatter);
         //if the HTML formatter is used with email handler, set email content-type to text/html
         if ($formatter instanceof HtmlFormatter && $handlerInstance instanceof NativeMailerHandler && method_exists($handlerInstance, 'setContentType')) {
             $handlerInstance->setContentType('text/html');
         }
     }
     if (false === empty($handler['processors'])) {
         $this->setProcessorsToHandlerFromConfig($handler['processors'], $handlerInstance);
     }
     $this->logger->pushHandler($handlerInstance);
     return $this;
 }
コード例 #21
0
ファイル: SlimTest.php プロジェクト: bairwell/middleware-cors
 /**
  * Get the CORs system integrated with Slim and FastRoute.
  *
  * @param ContainerInterface              $container The Slim Container.
  *
  * @return MiddlewareCors
  */
 protected function getCors(ContainerInterface $container) : MiddlewareCors
 {
     // set our allowed methods callback to integrate with Slim
     $corsAllowedMethods = function (ServerRequestInterface $request) use($container) : array {
         // if this closure is called, make sure it has the route available in the container.
         /* @var \Slim\Interfaces\RouterInterface $router */
         $router = $container->get('router');
         $routeInfo = $router->dispatch($request);
         $methods = [];
         // was the method called allowed?
         if ($routeInfo[0] === Dispatcher::METHOD_NOT_ALLOWED) {
             $methods = $routeInfo[1];
         } else {
             // if it was, see if we can get the routes and then the methods from it.
             // @var \Slim\Route $route
             $route = $request->getAttribute('route');
             // has the request get a route defined? is so use that
             if (null !== $route) {
                 $methods = $route->getMethods();
             }
         }
         // if we have methods, let's list them removing the OPTIONs one.
         if (false === empty($methods)) {
             // find the OPTIONs method
             $key = array_search('OPTIONS', $methods);
             // and remove it if set.
             if (false !== $key) {
                 unset($methods[$key]);
                 $methods = array_values($methods);
             }
         }
         return $methods;
     };
     // setup CORs
     $cors = new MiddlewareCors(['origin' => $this->allowedHosts, 'exposeHeaders' => '', 'maxAge' => 60, 'allowCredentials' => true, 'allowMethods' => $corsAllowedMethods, 'allowHeaders' => ['Accept-Language', 'Authorization', 'Content-type']]);
     // setup the logger
     $this->logger = new Logger('test');
     $this->testLogger = new TestHandler();
     $this->logger->pushHandler($this->testLogger);
     $cors->setLogger($this->logger);
     return $cors;
 }
コード例 #22
0
 /**
  * Test the parse item section.
  *
  * @param mixed   $settingValue   The callable,int,string,bool or array we are testing against.
  * @param string  $expectedResult The expected result.
  * @param boolean $isSingle       Does this "setting" take a single (true) or multiple parameters (false).
  */
 protected function parseItem($settingValue, string $expectedResult, bool $isSingle = false)
 {
     $sut = new MiddlewareCors();
     $reflection = new \ReflectionClass(get_class($sut));
     $settingsProperty = $reflection->getProperty('settings');
     $settingsProperty->setAccessible(true);
     // setup the logger
     $this->logger = new Logger('test');
     $this->testLogger = new TestHandler();
     $this->logger->pushHandler($this->testLogger);
     $sut->setLogger($this->logger);
     $method = $reflection->getMethod('parseItem');
     $method->setAccessible(true);
     $request = $this->getMockBuilder('Psr\\Http\\Message\\ServerRequestInterface')->disableOriginalConstructor()->getMock();
     $settingName = 'testItem';
     $settingsProperty->setValue($sut, [$settingName => $settingValue, 'def' => '567', 'ghi' => '911']);
     $result = $method->invokeArgs($sut, [$settingName, $request, $isSingle]);
     $this->assertInternalType('string', $result);
     $this->assertSame($expectedResult, $result);
 }
コード例 #23
0
 /**
  * @param LoggerInterface $logger
  * @param OutputInterface $output
  */
 protected function attachConsoleHandler(LoggerInterface $logger, OutputInterface $output)
 {
     if (!class_exists('Monolog\\Logger') || !$logger instanceof \Monolog\Logger) {
         return;
     }
     foreach ($logger->getHandlers() as $handler) {
         if ($handler instanceof ConsoleHandler) {
             return;
         }
     }
     $logger->pushHandler(new ConsoleHandler($output));
 }
コード例 #24
0
ファイル: Logging.php プロジェクト: karbowiak/seriis
 /**
  * @param $app
  */
 public function __construct(SeriisApp $app)
 {
     $this->app = $app;
     $this->logger = new Logger('Seriis');
     $this->logger->pushHandler(new StreamHandler($this->app->baseConfig->getConfig('logFile', 'Logging', __DIR__ . '/../../logs/app.log'), $this->app->baseConfig->getConfig("logLevel", "Logging", 100)));
 }
コード例 #25
0
 public function __construct()
 {
     $this->logger = new Logger("logger notification");
     $this->logger->pushHandler(new StreamHandler("/tmp/notification.log"));
 }
コード例 #26
0
 /**
  * Logger constructor.
  */
 private function __construct()
 {
     $this->logger = new \Monolog\Logger('DockerCloud');
     $this->logger->pushHandler(new StreamHandler('php://stdout'));
 }