Example #1
0
 /**
  * インスタンスを生成
  * Logger constructor.
  * @param null $fileName ファイル名を指定。デフォルトはmain設定ファイルのlog_file_format
  */
 public function __construct($fileName = null)
 {
     if ((bool) $fileName) {
         $logFile = LOGS_PATH . $fileName;
     } else {
         $logFile = LOGS_PATH . APPS_MAIN_CONF['log_file_name_format'];
     }
     $this->logger = new File($logFile);
     $req = new Request();
     $uri = $req->getURI();
     $this->logger->setFormatter(new LogFormatter("[%date%][{$uri}][%type%] %message%"));
 }
Example #2
0
 /**
  * 保存日志
  * @param string $logString 日志信息
  * @param string $level 日志级别
  */
 public function log($logString, $level = 'info')
 {
     $logger = new FileLogger($this->logDir . $this->logFile);
     $lineFormatter = new LineFormatter();
     $lineFormatter->setDateFormat('Y-m-d H:i:s');
     $logger->setFormatter($lineFormatter);
     $logger->log($logString, $this->log_level[$level]);
 }
 /**
  * Init logger.
  *
  * @param DI     $di     Dependency Injection.
  * @param Config $config Config object.
  *
  * @return void
  */
 protected function _initLogger($di, $config)
 {
     if ($config->application->logger->enabled) {
         $di->set('logger', function ($file = 'main', $format = null) use($config) {
             $logger = new File($config->application->logger->path . APPLICATION_STAGE . '.' . $file . '.log');
             $formatter = new FormatterLine($format ? $format : $config->application->logger->format);
             $logger->setFormatter($formatter);
             return $logger;
         }, false);
     }
 }
Example #4
0
 /**
  * Registers services related to the module
  *
  * @param DiInterface $di
  */
 public function registerServices(DiInterface $di)
 {
     /**
      * Read configuration
      */
     $config = (include APP_PATH . "/apps/backend/config/config.php");
     /**
      * Setting up the view component
      */
     $di['view'] = function () use($config) {
         $view = new View();
         $view->setViewsDir(__DIR__ . '/views/');
         $view->registerEngines(array('.volt' => function ($view, $di) use($config) {
             $volt = new VoltEngine($view, $di);
             $volt->setOptions(array('compiledPath' => __DIR__ . '/cache/', 'compiledSeparator' => '_'));
             $compiler = $volt->getCompiler();
             // format number
             $compiler->addFilter('number', function ($resolvedArgs) {
                 return 'Helpers::number(' . $resolvedArgs . ');';
             });
             return $volt;
         }, '.phtml' => 'Phalcon\\Mvc\\View\\Engine\\Php'));
         return $view;
     };
     /**
      * Database connection is created based in the parameters defined in the configuration file
      */
     $di['db'] = function () use($config) {
         $config = $config->database->toArray();
         $dbAdapter = '\\Phalcon\\Db\\Adapter\\Pdo\\' . $config['adapter'];
         unset($config['adapter']);
         return new $dbAdapter($config);
     };
     /**
      * Logger service
      */
     $di->set('logger', function ($filename = null, $format = null) use($config) {
         $format = $format ?: $config->get('logger')->format;
         $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
         $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
         $formatter = new FormatterLine($format, $config->get('logger')->date);
         $logger = new FileLogger($path . $filename);
         $logger->setFormatter($formatter);
         $logger->setLogLevel($config->get('logger')->logLevel);
         return $logger;
     });
     $di->set('url', function () use($config) {
         $url = new UrlResolver();
         $url->setBaseUri("/backend/");
         return $url;
     });
 }
Example #5
0
 /**
  * Tests new format logs correctly
  *
  * @author Nikos Dimopoulos <*****@*****.**>
  * @since  2012-09-17
  */
 public function testLoggerFormatterNewFormatFormatsDateCorrectly()
 {
     $fileName = newFileName('log', 'log');
     $logger = new PhTLoggerAdapterFile($this->logPath . $fileName);
     $formatter = new PhLoggerFormatterLine('%type%|%date%|%message%');
     $logger->setFormatter($formatter);
     $logger->log('Hello');
     $logger->close();
     $contents = file($this->logPath . $fileName);
     $message = explode('|', $contents[0]);
     cleanFile($this->logPath, $fileName);
     $date = new \DateTime($message[1]);
     $expected = date('Y-m-d H');
     $actual = $date->format('Y-m-d H');
     $this->assertEquals($expected, $actual, 'Date format not set properly');
 }
Example #6
0
 /**
  * Tests new format logs correctly
  *
  * @author Nikos Dimopoulos <*****@*****.**>
  * @since  2012-09-17
  */
 public function testLoggerFormatterLineNewFormatLogsCorrectly()
 {
     $this->specify("Line formatted does not set format correctly", function () {
         $I = $this->tester;
         $fileName = $I->getNewFileName('log', 'log');
         $logger = new File($this->logPath . $fileName);
         $formatter = new Line('%type%|%date%|%message%');
         $logger->setFormatter($formatter);
         $logger->log('Hello');
         $logger->close();
         $I->amInPath($this->logPath);
         $I->openFile($fileName);
         $I->seeInThisFile(sprintf('DEBUG|%s|Hello', date('D, d M y H:i:s O')));
         $I->deleteFile($fileName);
     });
 }
Example #7
0
 /**
  * 记录起始请求日志
  * 记录成功返回true,失败或没记录日志返回false
  *
  * @return  bool
  */
 public static function request_start_log()
 {
     if (!BaseLog::isLog('debug')) {
         return false;
     }
     if (!Config::getEnv("app.request_start_log")) {
         return false;
     }
     $data = Request::nonPostParam();
     if (Config::getEnv("app.request_log_post")) {
         $data = Request::param();
     }
     $file_path = BaseLog::handle_log_file('framework', 'debug');
     $log_time = date("Y-m-d H:i:s", QP_RUN_START);
     $ip = Request::getIp();
     $router_url = \Qp\Kernel\Http\Router\QpRouter::getRouterStr();
     $prefix = "[{$log_time}] [{$ip}] [router : {$router_url}] ";
     $msg = "【请求日志】" . json_encode(['data' => $data]);
     $logger = new FileAdapter($file_path);
     $logger->setFormatter(new LineFormatter("%message%"));
     return (bool) $logger->log($prefix . $msg);
 }
Example #8
0
 /**
  * Initialize the Logger.
  *
  * @param DiInterface   $di     Dependency Injector
  * @param Config        $config App config
  * @param EventsManager $em     Events Manager
  *
  * @return void
  */
 protected function initLogger(DiInterface $di, Config $config, EventsManager $em)
 {
     ErrorHandler::register();
     $di->set('logger', function ($filename = null, $format = null) use($config) {
         $format = $format ?: $config->get('logger')->format;
         $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
         $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
         $formatter = new FormatterLine($format, $config->get('logger')->date);
         $logger = new FileLogger($path . $filename);
         $logger->setFormatter($formatter);
         $logger->setLogLevel($config->get('logger')->logLevel);
         return $logger;
     });
 }
Example #9
0
 /**
  * Logs the error and dispatches an error controller.
  *
  * @param  \Phalcon\Error\Error $error
  * @return mixed
  */
 public static function handle(Error $error)
 {
     $di = Di::getDefault();
     $config = $di->getShared('config')->error->toArray();
     $logger = $config['logger'];
     if (!$logger instanceof AdapterInterface) {
         $logger = new FileLogger($logger);
     }
     $type = static::getErrorType($error->type());
     $message = "{$type}: {$error->message()} in {$error->file()} on line {$error->line()}";
     if (isset($config['formatter'])) {
         $formatter = null;
         if ($config['formatter'] instanceof Formatter) {
             $formatter = $config['formatter'];
         } elseif (is_array($config['formatter'])) {
             $format = null;
             $dateFormat = null;
             if (isset($config['formatter']['format'])) {
                 $format = $config['formatter']['format'];
             }
             if (isset($config['formatter']['dateFormat'])) {
                 $dateFormat = $config['formatter']['dateFormat'];
             } elseif (isset($config['formatter']['date_format'])) {
                 $dateFormat = $config['formatter']['date_format'];
             } elseif (isset($config['formatter']['date'])) {
                 $dateFormat = $config['formatter']['date'];
             }
             $formatter = new FormatterLine($format, $dateFormat);
         }
         if ($formatter) {
             $logger->setFormatter($formatter);
         }
     }
     $logger->log(static::getLogType($error->type()), $message);
     switch ($error->type()) {
         case E_WARNING:
         case E_NOTICE:
         case E_CORE_WARNING:
         case E_COMPILE_WARNING:
         case E_USER_WARNING:
         case E_USER_NOTICE:
         case E_STRICT:
         case E_DEPRECATED:
         case E_USER_DEPRECATED:
         case E_ALL:
             break;
         case 0:
         case E_ERROR:
         case E_PARSE:
         case E_CORE_ERROR:
         case E_COMPILE_ERROR:
         case E_USER_ERROR:
         case E_RECOVERABLE_ERROR:
             if ($di->has('view')) {
                 $dispatcher = $di->getShared('dispatcher');
                 $view = $di->getShared('view');
                 $response = $di->getShared('response');
                 $dispatcher->setControllerName($config['controller']);
                 $dispatcher->setActionName($config['action']);
                 $dispatcher->setParams(['error' => $error]);
                 $view->start();
                 $dispatcher->dispatch();
                 $view->render($config['controller'], $config['action'], $dispatcher->getParams());
                 $view->finish();
                 return $response->setContent($view->getContent())->send();
             } else {
                 echo $message;
             }
     }
 }
Example #10
0
 public static function run(DiInterface $di, array $options = [])
 {
     $memoryUsage = memory_get_usage();
     $currentTime = microtime(true);
     /**
      * The app path
      */
     if (!defined('K_PATH')) {
         define('K_PATH', dirname(dirname(dirname(__FILE__))));
     }
     /**
      * We will need the Utils class
      */
     require_once K_PATH . '/library/Kitsune/Utils.php';
     /**
      * Utils class
      */
     $utils = new Utils();
     $di->set('utils', $utils, true);
     /**
      * Check if this is a CLI app or not
      */
     $cli = $utils->fetch($options, 'cli', false);
     if (!defined('K_CLI')) {
         define('K_CLI', $cli);
     }
     $tests = $utils->fetch($options, 'tests', false);
     if (!defined('K_TESTS')) {
         define('K_TESTS', $tests);
     }
     /**
      * The configuration is split into two different files. The first one
      * is the base configuration. The second one is machine/installation
      * specific.
      */
     if (!file_exists(K_PATH . '/var/config/base.php')) {
         throw new \Exception('Base configuration files are missing');
     }
     if (!file_exists(K_PATH . '/var/config/config.php')) {
         throw new \Exception('Configuration files are missing');
     }
     /**
      * Get the config files and merge them
      */
     $base = (require K_PATH . '/var/config/base.php');
     $specific = (require K_PATH . '/var/config/config.php');
     $combined = array_replace_recursive($base, $specific);
     $config = new Config($combined);
     $di->set('config', $config, true);
     $config = $di->get('config');
     /**
      * Check if we are in debug/dev mode
      */
     if (!defined('K_DEBUG')) {
         $debugMode = boolval($utils->fetch($config, 'debugMode', false));
         define('K_DEBUG', $debugMode);
     }
     /**
      * Access to the debug/dev helper functions
      */
     if (K_DEBUG) {
         require_once K_PATH . '/library/Kitsune/Debug.php';
     }
     /**
      * We're a registering a set of directories taken from the
      * configuration file
      */
     $loader = new Loader();
     $loader->registerNamespaces($config->namespaces->toArray());
     $loader->register();
     require K_PATH . '/vendor/autoload.php';
     /**
      * LOGGER
      *
      * The essential logging service
      */
     $format = '[%date%][%type%] %message%';
     $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log';
     $logger = new LoggerFile($name);
     $formatter = new LoggerFormatter($format);
     $logger->setFormatter($formatter);
     $di->set('logger', $logger, true);
     /**
      * ERROR HANDLING
      */
     ini_set('display_errors', boolval(K_DEBUG));
     error_reporting(E_ALL);
     set_error_handler(function ($exception) use($logger) {
         if ($exception instanceof \Exception) {
             $logger->error($exception->__toString());
         } else {
             $logger->error(json_encode(debug_backtrace()));
         }
     });
     set_exception_handler(function (\Exception $exception) use($logger) {
         $logger->error($exception->getMessage());
     });
     register_shutdown_function(function () use($logger, $memoryUsage, $currentTime) {
         $memoryUsed = number_format((memory_get_usage() - $memoryUsage) / 1024, 3);
         $executionTime = number_format(microtime(true) - $currentTime, 4);
         if (K_DEBUG) {
             $logger->info('Shutdown completed [Memory: ' . $memoryUsed . 'Kb] ' . '[Execution: ' . $executionTime . ']');
         }
     });
     $timezone = $config->get('app_timezone', 'US/Eastern');
     date_default_timezone_set($timezone);
     /**
      * Routes
      */
     if (!K_CLI) {
         $di->set('router', function () use($config) {
             $router = new Router(false);
             $router->removeExtraSlashes(true);
             $routes = $config->routes->toArray();
             foreach ($routes as $pattern => $options) {
                 $router->add($pattern, $options);
             }
             return $router;
         }, true);
     }
     /**
      * We register the events manager
      */
     $di->set('dispatcher', function () use($di) {
         $eventsManager = new EventsManager();
         /**
          * Handle exceptions and not-found exceptions using NotFoundPlugin
          */
         $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin());
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace('Kitsune\\Controllers');
         return $dispatcher;
     });
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $di->set('url', function () use($config) {
         $url = new UrlProvider();
         $url->setBaseUri($config->baseUri);
         return $url;
     });
     $di->set('view', function () use($config) {
         $view = new View();
         $view->setViewsDir(K_PATH . '/app/views/');
         $view->registerEngines([".volt" => 'volt']);
         return $view;
     });
     /**
      * Setting up volt
      */
     $di->set('volt', function ($view, $di) {
         $volt = new VoltEngine($view, $di);
         $volt->setOptions(["compiledPath" => K_PATH . '/var/cache/volt/', 'stat' => K_DEBUG, 'compileAlways' => K_DEBUG]);
         return $volt;
     }, true);
     /**
      * Start the session the first time some component request the session
      * service
      */
     $di->set('session', function () {
         $session = new SessionAdapter();
         $session->start();
         return $session;
     });
     /**
      * Cache
      */
     $frontConfig = $config->cache_data->front->toArray();
     $backConfig = $config->cache_data->back->toArray();
     $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
     $frontCache = new $class($frontConfig['params']);
     $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
     $cache = new $class($frontCache, $backConfig['params']);
     $di->set('cache', $cache, true);
     /**
      * viewCache
      */
     $di->set('viewCache', function () use($config) {
         $frontConfig = $config->cache_view->front->toArray();
         $backConfig = $config->cache_view->back->toArray();
         $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
         $frontCache = new $class($frontConfig['params']);
         $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
         $cache = new $class($frontCache, $backConfig['params']);
         return $cache;
     });
     /**
      * Markdown renderer
      */
     $di->set('markdown', function () {
         $ciconia = new Ciconia();
         $ciconia->addExtension(new FencedCodeBlockExtension());
         $ciconia->addExtension(new TaskListExtension());
         $ciconia->addExtension(new InlineStyleExtension());
         $ciconia->addExtension(new WhiteSpaceExtension());
         $ciconia->addExtension(new TableExtension());
         $ciconia->addExtension(new UrlAutoLinkExtension());
         $ciconia->addExtension(new MentionExtension());
         $extension = new IssueExtension();
         $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/issues/%s)');
         $ciconia->addExtension($extension);
         $extension = new PullRequestExtension();
         $extension->setIssueUrl('[#%s](https://github.com/phalcon/cphalcon/pull/%s)');
         $ciconia->addExtension($extension);
         return $ciconia;
     }, true);
     /**
      * Posts Finder
      */
     $di->set('finder', function () use($utils, $cache) {
         $key = 'post.finder.cache';
         $postFinder = $utils->cacheGet($key);
         if (null === $postFinder) {
             $postFinder = new PostFinder();
             $cache->save($key, $postFinder);
         }
         return $postFinder;
     }, true);
     /**
      * For CLI I only need the dependency injector
      */
     if (K_CLI) {
         return $di;
     } else {
         $application = new Application($di);
         if (K_TESTS) {
             return $application;
         } else {
             return $application->handle()->getContent();
         }
     }
 }
Example #11
0
    return new Flash(array('error' => 'alert alert-danger', 'success' => 'alert alert-success', 'notice' => 'alert alert-info', 'warning' => 'alert alert-warning'));
});
/**
 * Start the session the first time some component request the session service
 */
$di->setShared('session', function () {
    $session = new SessionAdapter();
    $session->start();
    return $session;
});
/*
 * Routes
 */
#$di->set('router', function(){
#    require 'routes.php';
#    return $router;
#});
/**
 * Logger service
 */
$di->set('logger', function ($filename = null, $format = null) use($config) {
    $format = $format ?: $config->get('logger')->format;
    $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
    $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
    #$path = "/temp/system.log";
    $formatter = new FormatterLine($format, $config->get('logger')->date);
    $logger = new FileLogger($path . $filename);
    $logger->setFormatter($formatter);
    $logger->setLogLevel($config->get('logger')->logLevel);
    return $logger;
});
Example #12
0
 public function run(DiInterface $diContainer, array $options = [])
 {
     $memoryUsage = memory_get_usage();
     $currentTime = microtime(true);
     $this->diContainer = $diContainer;
     /**
      * The app path
      */
     if (!defined('K_PATH')) {
         define('K_PATH', dirname(dirname(dirname(__FILE__))));
     }
     /**
      * We will need the Utils class
      */
     require_once K_PATH . '/library/Kitsune/Utils.php';
     /**
      * Utils class
      */
     $utils = new Utils();
     $this->diContainer->set('utils', $utils, true);
     /**
      * Check if this is a CLI app or not
      */
     $cli = $utils->fetch($options, 'cli', false);
     if (!defined('K_CLI')) {
         define('K_CLI', $cli);
     }
     $tests = $utils->fetch($options, 'tests', false);
     if (!defined('K_TESTS')) {
         define('K_TESTS', $tests);
     }
     /**********************************************************************
      * CONFIG
      **********************************************************************/
     /**
      * The configuration is split into two different files. The first one
      * is the base configuration. The second one is machine/installation
      * specific.
      */
     if (!file_exists(K_PATH . '/var/config/base.php')) {
         throw new \Exception('Base configuration files are missing');
     }
     if (!file_exists(K_PATH . '/var/config/config.php')) {
         throw new \Exception('Configuration files are missing');
     }
     /**
      * Get the config files and merge them
      */
     $base = (require K_PATH . '/var/config/base.php');
     $specific = (require K_PATH . '/var/config/config.php');
     $combined = array_replace_recursive($base, $specific);
     $config = new Config($combined);
     $this->diContainer->set('config', $config, true);
     /**
      * Check if we are in debug/dev mode
      */
     if (!defined('K_DEBUG')) {
         $debugMode = boolval($utils->fetch($config, 'debugMode', false));
         define('K_DEBUG', $debugMode);
     }
     /**
      * Access to the debug/dev helper functions
      */
     if (K_DEBUG) {
         require_once K_PATH . '/library/Kitsune/Debug.php';
     }
     /**********************************************************************
      * LOADER
      **********************************************************************/
     /**
      * We're a registering a set of directories taken from the
      * configuration file
      */
     $loader = new Loader();
     $loader->registerNamespaces($config->namespaces->toArray());
     $loader->register();
     require K_PATH . '/vendor/autoload.php';
     /**********************************************************************
      * LOGGER
      **********************************************************************/
     /**
      * The essential logging service
      */
     $format = '[%date%][%type%] %message%';
     $name = K_PATH . '/var/log/' . date('Y-m-d') . '-kitsune.log';
     $logger = new LoggerFile($name);
     $formatter = new LoggerFormatter($format);
     $logger->setFormatter($formatter);
     $this->diContainer->set('logger', $logger, true);
     /**********************************************************************
      * ERROR HANDLING
      **********************************************************************/
     ini_set('display_errors', boolval(K_DEBUG));
     error_reporting(E_ALL);
     set_error_handler(function ($exception) use($logger) {
         if ($exception instanceof \Exception) {
             $logger->error($exception->__toString());
         } else {
             $logger->error(json_encode(debug_backtrace()));
         }
     });
     set_exception_handler(function (\Exception $exception) use($logger) {
         $logger->error($exception->getMessage());
     });
     register_shutdown_function(function () use($logger, $utils, $memoryUsage, $currentTime) {
         $memoryUsed = memory_get_usage() - $memoryUsage;
         $executionTime = microtime(true) - $currentTime;
         if (K_DEBUG) {
             $logger->info(sprintf('Shutdown completed [%s]s - [%s]', round($executionTime, 3), $utils->bytesToHuman($memoryUsed)));
         }
     });
     $timezone = $config->get('app_timezone', 'US/Eastern');
     date_default_timezone_set($timezone);
     /**********************************************************************
      * ROUTES
      **********************************************************************/
     if (false === K_CLI) {
         $router = new Router(false);
         $router->removeExtraSlashes(true);
         $routes = $config->routes->toArray();
         foreach ($routes as $pattern => $options) {
             $router->add($pattern, $options);
         }
         $this->diContainer->set('router', $router, true);
     }
     /**********************************************************************
      * DISPATCHER
      **********************************************************************/
     if (false === K_CLI) {
         /**
          * We register the events manager
          */
         $eventsManager = new EventsManager();
         /**
          * Handle exceptions and not-found exceptions using NotFoundPlugin
          */
         $eventsManager->attach('dispatch:beforeException', new NotFoundPlugin());
         $dispatcher = new Dispatcher();
         $dispatcher->setEventsManager($eventsManager);
         $dispatcher->setDefaultNamespace('Kitsune\\Controllers');
     } else {
         $dispatcher = new PhCliDispatcher();
         $dispatcher->setDefaultNamespace('Kitsune\\Cli\\Tasks');
     }
     $this->diContainer->set('dispatcher', $dispatcher);
     /**********************************************************************
      * URL
      **********************************************************************/
     /**
      * The URL component is used to generate all kind of urls in the application
      */
     $url = new UrlProvider();
     $url->setBaseUri($config->baseUri);
     $this->diContainer->set('url', $url);
     /**********************************************************************
      * VIEW
      **********************************************************************/
     $view = new View();
     $view->setViewsDir(K_PATH . '/app/views/');
     $view->registerEngines([".volt" => function ($view) {
         return $this->setVoltOptions($view);
     }]);
     $this->diContainer->set('view', $view);
     /**********************************************************************
      * VIEW SIMPLE
      **********************************************************************/
     $viewSimple = new ViewSimple();
     $viewSimple->setViewsDir(K_PATH . '/app/views/');
     $viewSimple->registerEngines([".volt" => function ($view) {
         return $this->setVoltOptions($view);
     }]);
     $this->diContainer->set('viewSimple', $viewSimple);
     /**********************************************************************
      * CACHE
      **********************************************************************/
     $frontConfig = $config->cache_data->front->toArray();
     $backConfig = $config->cache_data->back->toArray();
     $class = '\\Phalcon\\Cache\\Frontend\\' . $frontConfig['adapter'];
     $frontCache = new $class($frontConfig['params']);
     $class = '\\Phalcon\\Cache\\Backend\\' . $backConfig['adapter'];
     $cache = new $class($frontCache, $backConfig['params']);
     $this->diContainer->set('cache', $cache, true);
     /**********************************************************************
      * POSTS FINDER
      **********************************************************************/
     $this->diContainer->set('finder', new PostFinder(), true);
     /**********************************************************************
      * DISPATCH 17.5s
      **********************************************************************/
     if (K_CLI) {
         return new PhCliConsole($this->diContainer);
     } else {
         $application = new Application($this->diContainer);
         if (K_TESTS) {
             return $application;
         } else {
             return $application->handle()->getContent();
         }
     }
 }
Example #13
0
 /**
  * 日志处理
  */
 protected function initLogger()
 {
     $config = $this->config;
     $this->di['logger'] = function () use($config) {
         $logLevel = $this->debug ? Logger::DEBUG : Logger::ERROR;
         if ($config->offsetExists('logger')) {
             try {
                 if ($config->logger->offsetExists('path') == false) {
                     throw new \Exception('logger path not in config.');
                 }
                 $path = $config->logger->path;
                 $path = str_replace('{{date}}', date("Ymd"), $path);
                 if ($config->logger->offsetExists('formatter')) {
                     $formatter = new LineFormatter($config->logger->formatter);
                 } else {
                     $formatter = new LineFormatter('%date%[%type%] - %message%');
                 }
                 $logger = new LoggerFile($path);
                 $logger->setFormatter($formatter);
                 $logger->setLogLevel($logLevel);
                 return $logger;
             } catch (\Exception $e) {
             }
         }
         $logger = new LoggerStream("php://stderr");
         $logger->setLogLevel($logLevel);
         return $logger;
     };
 }
Example #14
0
 /**
  * Initialize the Logger.
  */
 protected function initLogger()
 {
     ErrorHandler::register();
     $this->di->set('logger', function ($filename = null, $format = null) {
         /** @var DiInterface $this */
         $config = $this->getShared('config');
         $format = $format ?: $config->get('logger')->format;
         $filename = trim($filename ?: $config->get('logger')->filename, '\\/');
         $path = rtrim($config->get('logger')->path, '\\/') . DIRECTORY_SEPARATOR;
         if (false === strpos($filename, '.log')) {
             $filename = "{$filename}.log";
         }
         $formatter = new FormatterLine($format, $config->get('logger')->date);
         $logger = new FileLogger($path . $filename);
         $logger->setFormatter($formatter);
         $logger->setLogLevel($config->get('logger')->logLevel);
         return $logger;
     });
 }
Example #15
0
 /**
  *
  * @param type $options
  */
 protected function initLogger($options = [])
 {
     $config = $this->_di->get('config');
     $this->_di->setShared('logger', function () use($config) {
         if (!file_exists($config->logger->file)) {
             mkdir($config->logger->file, 0777, true);
         }
         $logger = new LoggerFile($config->logger->file . date('Y-m-d') . '.log');
         $formatter = new LoggerFormatter($config->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
     $this->_di->setShared('loggerDb', function () use($config) {
         if (!file_exists($config->logger->file . '/db/')) {
             mkdir($config->logger->file . '/db/', 0777, true);
         }
         $logger = new LoggerFile($config->logger->file . '/db/' . date('Y-m-d') . '.log');
         $formatter = new LoggerFormatter($config->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
 }
Example #16
0
 /**
  * 默认服务依赖注入
  *
  */
 protected function commonServices()
 {
     $mode = $this->mode;
     $di = $this->mode === 'CLI' ? new Cli() : new FactoryDefault();
     // 日志
     $di->set('logger', function () {
         $config = load('logger');
         $adapter = $config['adapter'];
         $filename = $config[$adapter]['filename'];
         $filedir = dirname($filename);
         if (empty($config)) {
             throw new \Exception('logger config Require failed');
         }
         if (!is_dir($filedir)) {
             mkdir($filedir, 0755, true);
         }
         $logger = new File($filename);
         $formatter = new Line(null, 'Y-m-d H:i:s');
         $loglevel = config('app.loglevel');
         $logger->setFormatter($formatter);
         $logger->setLogLevel($loglevel ? $loglevel : \Phalcon\Logger::ERROR);
         return $logger;
     }, true);
     $this->application->setDI($di);
     // 命名空间
     $di->set('dispatcher', function () use($mode) {
         $dispatcher = new Dispatcher();
         $dispatcher = $mode === 'CLI' ? new \Phalcon\CLI\Dispatcher() : new Dispatcher();
         $bootstrap = load('bootstrap');
         $default = $bootstrap['dispatcher'];
         $dispatcher->setDefaultNamespace($mode === 'CLI' ? $default['cli'] : $default['default']);
         return $dispatcher;
     }, true);
     // 路由
     if ($load = load('router', null, true)) {
         if ($load instanceof Router) {
             $di->set('router', $load);
         }
     }
     // 视图
     $di->set('view', function () {
         $view = new View();
         $view->setViewsDir(APP_VIEW);
         return $view;
     }, true);
     // 加解密
     if ($config = config('crypt')) {
         $di->set('crypt', function () use($config) {
             $crypt = new Crypt();
             $crypt->setKey($config['authkey']);
             return $crypt;
         }, true);
     }
     // 默认缓存
     if ($config = config('cache')) {
         $di->set('cache', function () use($config) {
             $cache = null;
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             $frontend = new Data(array('lifetime' => $config['lifetime']));
             switch ($adapter) {
                 case 'memcache':
                     $cache = new Memcache($frontend, $options);
                     break;
                 case 'redis':
                     if (empty($options['auth'])) {
                         unset($options['auth']);
                     }
                     $cache = new \Phalcon\Extend\Cache\Backend\Redis($frontend, $options);
                     break;
             }
             return $cache;
         }, true);
     }
     // Cookies
     if ($config = config('cookies')) {
         $di->set('cookies', function () use($config) {
             $cookies = new \Phalcon\Extend\Http\Response\Cookies($config);
             if (!config('crypt.authkey')) {
                 $cookies->useEncryption(false);
             }
             return $cookies;
         }, true);
     }
     // Session
     if ($config = config('session')) {
         $di->set('session', function () use($config) {
             if (!empty($config['options'])) {
                 foreach ($config['options'] as $name => $value) {
                     ini_set("session.{$name}", $value);
                 }
             }
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             switch ($adapter) {
                 case 'memcache':
                     $session = new SessionMemcache($options);
                     break;
                 case 'redis':
                     $session = new \Phalcon\Extend\Session\Adapter\Redis($options);
                     break;
                 default:
                     $session = new SessionFiles();
                     break;
             }
             $session->start();
             return $session;
         }, true);
     }
     // Db
     if ($config = config('db')) {
         $di->set('db', function () use($config) {
             $mysql = new Mysql($config);
             if (debugMode()) {
                 $eventsManager = new Manager();
                 $logger = new File(APP_LOG . DS . 'Mysql' . LOGEXT);
                 $formatter = new Line(null, 'Y-m-d H:i:s');
                 $logger->setFormatter($formatter);
                 $eventsManager->attach('db', function ($event, $mysql) use($logger) {
                     if ($event->getType() == 'beforeQuery') {
                         $logger->log($mysql->getSQLStatement(), Logger::INFO);
                     }
                     if ($event->getType() == 'afterQuery') {
                     }
                 });
                 $mysql->setEventsManager($eventsManager);
             }
             return $mysql;
         }, true);
     }
     // DB 元信息
     if ($config = config('metadata')) {
         $di->set('modelsMetadata', function () use($config) {
             $modelsMetadata = null;
             $adapter = strtolower($config['adapter']);
             $options = $config[$adapter];
             switch ($adapter) {
                 case 'memcache':
                     $modelsMetadata = new MetaDataMemcache($options);
                     break;
                 case 'redis':
                     if (empty($options['auth'])) {
                         unset($options['auth']);
                     }
                     $modelsMetadata = new MetaDataRedis($options);
                     break;
             }
             return $modelsMetadata;
         }, true);
     }
     $this->application->setDI($di);
 }
Example #17
0
 /**
  * Init logger.
  *
  * @param DI     $di     Dependency Injection.
  * @param Config $config Config object.
  *
  * @return void
  */
 protected function _initLogger($di, $config)
 {
     $di->set('logger', function ($file = 'main', $format = null) use($config) {
         $logger = new PhLogFile($config->global->logger->path . ENV . '.' . $file . '.log');
         $formatter = new PhFormatLine($format ? $format : $config->global->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     }, false);
 }
 /**
  * Initializes the logger
  *
  * @param array $options
  */
 protected function initLogger($options = array())
 {
     $config = $this->_di->get('config');
     $this->_di->set('logger', function () use($config) {
         $logger = new PhLoggerFile(ROOT_PATH . $config->app->logger->file);
         $formatter = new PhLoggerFormatter($config->app->logger->format);
         $logger->setFormatter($formatter);
         return $logger;
     });
 }
Example #19
0
 /**
  * 底层日志记录方法
  * 记录成功返回true,失败或没记录日志返回false
  *
  * @param   string  $log_level  日志等级
  * @param   string  $msg        日志消息(占位符使用{键名})
  * @param   array   $data       数据(支持key-value形式的数组,用来替换$msg中的占位字符)
  * @param   bool    $is_replace 是否替换占位字符
  * @param   string  $modular    应用模块名
  * @return  bool
  */
 protected static function log($log_level, $msg = '', $data = [], $is_replace = false, $modular = 'unknown_module')
 {
     if (!in_array($log_level, self::$log_level_allow)) {
         throw new \InvalidArgumentException("不支持的日志等级:" . $log_level);
     }
     if (!self::isLog($log_level)) {
         return false;
     }
     $file_path = self::handle_log_file($modular, $log_level);
     $log_time = date('Y-m-d H:i:s');
     $ip = \Qp\Kernel\Request::getIp();
     $router_url = \Qp\Kernel\Http\Router\QpRouter::getRouterStr();
     $prefix = "[{$log_time}] [{$ip}] [router : {$router_url}] ";
     if ($is_replace) {
         $msg = self::interpolate($msg, $data);
     } else {
         $msg = $msg . json_encode(['data' => $data]);
     }
     $logger = new FileAdapter($file_path);
     $logger->setFormatter(new LineFormatter("%message%"));
     return (bool) $logger->log($prefix . $msg);
 }