Exemplo n.º 1
0
 /**
  * Instanciate the ElasticSearch Migration Service
  *
  * @param array $hostsConfHash Elastic Search connection config
  *              e.g. : [
  *                  'from' => '192.168.100.100:9200',
  *                  'to'   => '192.168.100.100:9200'
  *               ]
  * @param array $migrationHash index migration informations
  *              e.g. : [
  *                  'from'    => ['index' => 'bar',     'type' => 'foo'],
  *                  'to'      => ['index' => 'new_bar', 'type' => 'foo'],
  *                  'bulk'    => ['action' => 'index', 'id' => '_id'],
  *                  'aliases' => ['read' => 'barRead', 'write' => 'barWrite'],
  *                  'mapping' => [...]
  *              ]
  * @param integer log level Slingshot::VERBOSITY_INFO | VERBOSITY_DEBUG | VERBOSITY_ERROR
  * @return void
  */
 public function __construct($hostsConfHash, $migrationHash, $verbosity = self::VERBOSITY_INFO)
 {
     // Init logger
     $this->logger = new Logger('slingshot');
     $syslogH = new SyslogHandler(null, 'local6', $verbosity);
     $formatter = new LineFormatter($this->logLineFormat);
     $syslogH->setFormatter($formatter);
     $this->logger->pushHandler($syslogH);
     $this->logger->pushProcessor(new PsrLogMessageProcessor());
     if (!$this->isMigrationConfValid($migrationHash)) {
         throw new \Exception('Wrong migrationHash paramater');
     }
     if (!$this->isHostsConfValid($hostsConfHash)) {
         throw new \Exception('Wrong hosts conf paramater');
     }
     $this->migrationHash = $migrationHash;
     $this->docsProcessed = 0;
     $this->ESClientSource = new \Elasticsearch\Client(['hosts' => [$hostsConfHash['from']]]);
     if (!empty($hostsConfHash['to']) && $hostsConfHash['from'] != $hostsConfHash['to']) {
         $this->ESClientTarget = new \Elasticsearch\Client(['hosts' => [$hostsConfHash['to']]]);
     } else {
         $this->ESClientTarget =& $this->ESClientSource;
     }
     $this->bulkHash = $this->migrationHash['to'];
 }
 public static function factory(array $config, array $handlers, $debug)
 {
     $config = self::validateAndNormaliseConfig($config);
     $handler = new SyslogHandler($config['ident'], LOG_USER, $debug ? PsrLogLevel::DEBUG : $config['min_level']);
     $handler->setFormatter($config['formatter']['factory']::factory($config['formatter']['conf']));
     return $handler;
 }
Exemplo n.º 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];
 }
Exemplo n.º 4
0
 /**
  * constructor
  *
  * @param string $type            
  * @param array $options            
  * @throws \Exception
  */
 public function __construct($type, array $options = [])
 {
     if (!is_string($type)) {
         throw new RunTimeException(sprintf('%s expects the $type argument to be a string class name; received "%s"', __METHOD__, is_object($type) ? get_class($type) : gettype($type)));
     }
     if (!class_exists($type)) {
         $class = __NAMESPACE__ . '\\Storage\\' . $type;
         if (!class_exists($class)) {
             throw new RunTimeException(sprintf('%s expects the $type argument to be a valid class name; received "%s"', __METHOD__, $type));
         }
         $type = $class;
     }
     $this->storage = new $type($options);
     if (array_key_exists('pageCount', $options)) {
         $this->pageCount = $options['pageCount'];
     }
     if (array_key_exists('pageInternal', $options)) {
         $this->pageInternal = $options['pageInternal'];
     }
     if (array_key_exists('blockingPeriod', $options)) {
         $this->blockingPeriod = $options['blockingPeriod'];
     }
     if (array_key_exists('pageRequestMethods', $options)) {
         $this->pageRequestMethods = $options['pageRequestMethods'];
     }
     $this->logger = new Logger('application');
     $syslog = new SyslogHandler('Evasive');
     $formatter = new LineFormatter("%channel%.%level_name%: %message% %extra%");
     $syslog->setFormatter($formatter);
     $this->logger->pushHandler($syslog);
 }
 /**
  * Bootstrap the application services.
  */
 public function boot()
 {
     $monolog = Log::getMonolog();
     $syslog = new SyslogHandler('papertrail');
     $formatter = new LineFormatter('%channel%.%level_name%: %message% %extra%');
     $syslog->setFormatter($formatter);
     $monolog->pushHandler($syslog);
 }
Exemplo n.º 6
0
 /**
  * Wraps the creation of log handlers so they can be created in a standard way.
  *
  * @param string $type    Type of log handler to create
  * @param array  $options Configuration options for log handler
  *
  * @throws \Exception
  */
 public function addLogHandler($type, $options)
 {
     // Throw exception if no handler configuration has been set. FirePHPHandler is the exception, it doesn't
     // have any config options.
     if ($options == []) {
         throw new \Exception('Missing handler configuration!', 1);
     }
     // Set the log level if one wasn't given.
     if (!array_key_exists('log_level', $options)) {
         $options['log_level'] = $this->defaultLogLevel;
     }
     // Allow messages to "bubble-up" the stack to other handlers
     if (!array_key_exists('bubble', $options)) {
         $options['bubble'] = true;
     }
     // Add the requested handler
     switch ($type) {
         case 'file':
             $this->pushHandler(new StreamHandler($options['log_location'], $this->loggerLevel($options['log_level']), $options['bubble']));
             break;
         case 'firebug':
             $this->pushHandler(new FirePHPHandler($this->loggerLevel($options['log_level']), $options['bubble']));
             break;
         case 'syslog':
             $syslog = new SyslogHandler($options['facility'], $options['syslogLevel'], $options['bubble']);
             $formatter = new LineFormatter('%channel%.%level_name%: %message% %context% %extra%');
             $syslog->setFormatter($formatter);
             $this->pushHandler($syslog);
             break;
         case 'mail':
             // Create the Swift_mail transport
             $transport = Swift_SmtpTransport::newInstance($options['host'], $options['port'], 'ssl')->setUsername($options['username'])->setPassword($options['password']);
             // Create the Mailer using your created Transport
             $mailer = Swift_Mailer::newInstance($transport);
             // Create a message
             $message = Swift_Message::newInstance($options['subject'])->setFrom($options['from'])->setTo($options['to'])->setBody('', 'text/html');
             $htmlFormatter = new HtmlFormatter();
             $mailStream = new SwiftMailerHandler($mailer, $message, $this->loggerLevel($options['log_level']), $options['bubble']);
             $mailStream->setFormatter($htmlFormatter);
             $this->pushHandler($mailStream);
             break;
         case 'sms':
             $twilio = new TwilioHandler($options['account_sid'], $options['auth_token'], $options['from_numbers'], $options['to_numbers'], $options['log_level'], $options['bubble']);
             $formatter = new LineFormatter('%channel%.%level_name%: %message% %context%');
             $twilio->setFormatter($formatter);
             $this->pushHandler($twilio);
             break;
         default:
             throw new \Exception('Unknown Log Handler', 1);
             break;
     }
 }
 /**
  * Register the service provider.
  *
  * @return void
  */
 public function register()
 {
     $this->bindContracts();
     $this->registerSingletons();
     $this->app->singleton(RobinLogger::class, function (Application $app) {
         $monolog = $app->make('log');
         $syslog = new SyslogHandler(env('PAPERTRAIL_APP_NAME'));
         $formatter = new LineFormatter('%channel%.%level_name%: %message% %extra% %context%');
         $syslog->setFormatter($formatter);
         $monolog->pushHandler($syslog);
         return new RobinLogger($monolog);
     });
 }
Exemplo n.º 8
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;
 }
 public function setLevel($level)
 {
     if (!is_string($level)) {
         parent::setLevel((int) $level);
         return;
     }
     if (!defined('\\Monolog\\Logger::' . $level)) {
         return;
     }
     parent::setLevel(constant('\\Monolog\\Logger::' . $level));
 }
Exemplo n.º 10
0
 public function register(Container $app)
 {
     $app['logger'] = function () use($app) {
         return $app['monolog'];
     };
     $app['monolog'] = function ($app) {
         $logger = new Logger($app['monolog.name']);
         $rotate = $app['config']->get('app.log.rotate', 'single');
         $logger->pushHandler($app['monolog.handler.' . $rotate]);
         return $logger;
     };
     $app['monolog.formatter'] = function () {
         return new LineFormatter();
     };
     $app['monolog.handler.single'] = function ($app) {
         $handler = new StreamHandler($app['monolog.logfile'], $app['monolog.level']);
         $handler->setFormatter($app['monolog.formatter']);
         return $handler;
     };
     $app['monolog.handler.daily'] = function ($app) {
         $maxFiles = $app['config']->get('app.log.max_files', 5);
         $handler = new RotatingFileHandler($app['monolog.logfile'], $maxFiles, $app['monolog.level']);
         $handler->setFormatter($app['monolog.formatter']);
         return $handler;
     };
     $app['monolog.handler.error'] = function ($app) {
         $handler = new ErrorLogHandler(ErrorLogHandler::OPERATING_SYSTEM, $app['monolog.level']);
         $handler->setFormatter($app['monolog.formatter']);
         return $handler;
     };
     $app['monolog.handler.syslog'] = function ($app) {
         $handler = new SyslogHandler($app['monolog.name'], LOG_USER, $app['monolog.level']);
         $handler->setFormatter($app['monolog.formatter']);
         return $handler;
     };
     $level = $app['config']->get('app.log.level', 'debug');
     $app['monolog.level'] = $this->parseLevel($level);
     $app['monolog.logfile'] = $app['path.logs'] . $this->getSettings('app.log.logfile');
     $app['monolog.name'] = $this->getSettings('monolog.name', 'app.name');
 }
 /**
  * {@inheritdoc}
  */
 public function handle(array $record)
 {
     if (!$this->isHandling($record)) {
         return false;
     }
     $segmentedMessage = str_split($record['message'], $this->length - $this->identificationLength);
     $totalSegments = count($segmentedMessage);
     $messageId = substr(uniqid(), 3, 13);
     for ($index = 0; $index < $totalSegments; $index++) {
         $recordSegment = $record;
         $recordSegment['message'] = strval($messageId) . ':' . strval($index + 1) . ':' . strval($totalSegments) . ' ' . $segmentedMessage[$index];
         $segmentResult = parent::handle($recordSegment);
     }
     return $segmentResult;
 }
 /**
  * @param AgaviLoggerAppender $appender Agavi logger appender instance to use for \Monolog\Logger instance creation
  *
  * @return Monolog\Logger with Monolog\Handler\FingersCrossedHandler that logs to syslog and file
  */
 public static function getMonologInstance(AgaviLoggerAppender $appender)
 {
     // get and define all parameters and their default values
     $minimum_level = $appender->getParameter('minimum_level', Logger::DEBUG);
     $trigger_level = $appender->getParameter('trigger_level', Logger::CRITICAL);
     $buffer_size = $appender->getParameter('buffer_size', 0);
     $bubble = $appender->getParameter('bubble', true);
     $channel_name = $appender->getParameter('channel', $appender->getParameter('name', 'monolog-default'));
     $default_file_path = AgaviConfig::get('core.app_dir') . '/log/' . $channel_name . '.log';
     $file_path = preg_replace('/[^a-zA-Z0-9-_\\.\\/]/', '', $appender->getParameter('destination', $default_file_path));
     $syslog_identifier = $appender->getParameter('syslog_identifier', AgaviConfig::get('core.app_name', __METHOD__));
     $syslog_facility = $appender->getParameter('syslog_facility', LOG_USER);
     $formatter_template = $appender->getParameter('formatter_template', "%message% [%channel%.%level_name%] %context% %extra%\n");
     $formatter_datetime_format = $appender->getParameter('formatter_datetime_format', 'Y-m-d\\TH:i:s.uP');
     // create a new Monolog\Logger instance
     $logger = new Logger($channel_name);
     // LineFormatter defaults to "[%datetime%] %channel%.%level_name%: %message% %context% %extra%\n", but we don't
     // need the datetime string as we already have that from our own Agavi log message
     $formatter = new LineFormatter($formatter_template, $formatter_datetime_format);
     // define default processors to be added to handlers
     $processors = array();
     $processors[] = new DefaultProcessor();
     $processors[] = new PsrLogMessageProcessor();
     // define syslog and file handlers and group them together
     $stream_handler = new StreamHandler($file_path, $minimum_level);
     $stream_handler->setFormatter($formatter);
     $syslog_handler = new SyslogHandler($syslog_identifier, $syslog_facility, $minimum_level);
     $syslog_handler->setFormatter($formatter);
     $handlers = array($syslog_handler, $stream_handler);
     // add default processors to all handlers
     foreach ($handlers as $handler) {
         foreach ($processors as $processor) {
             $handler->pushProcessor($processor);
         }
     }
     // group handlers to have every handler handle all messages
     $group_handler = new GroupHandler($handlers, $bubble);
     // define fingers crossed handler to use the group handler
     $fingers_crossed_handler = new FingersCrossedHandler($group_handler, $trigger_level, $buffer_size, $bubble);
     $logger->pushHandler($fingers_crossed_handler);
     // return the Monolog\Logger instance to the caller
     return $logger;
 }
Exemplo n.º 13
0
/** Add information to the log file */
function add_log($text, $function, $type = LOG_INFO, $projectid = 0, $buildid = 0, $resourcetype = 0, $resourceid = 0)
{
    global $CDASH_LOG_FILE, $CDASH_LOG_FILE_MAXSIZE_MB, $CDASH_LOG_LEVEL, $CDASH_TESTING_MODE;
    $level = to_psr3_level($type);
    if (($buildid === 0 || is_null($buildid)) && isset($GLOBALS['PHP_ERROR_BUILD_ID'])) {
        $buildid = $GLOBALS['PHP_ERROR_BUILD_ID'];
    }
    $context = array('function' => $function);
    if ($projectid !== 0 && !is_null($projectid)) {
        $context['project_id'] = $projectid;
    }
    if ($buildid !== 0 && !is_null($buildid)) {
        $context['build_id'] = strval($buildid);
    }
    if ($resourcetype !== 0 && !is_null($resourcetype)) {
        $context['resource_type'] = $resourcetype;
    }
    if ($resourceid !== 0 && !is_null($resourceid)) {
        $context['resource_id'] = $resourceid;
    }
    $minLevel = to_psr3_level($CDASH_LOG_LEVEL);
    if (!is_null($CDASH_LOG_FILE)) {
        // If the size of the log file is bigger than 10 times the allocated memory
        // we rotate
        $logFileMaxSize = $CDASH_LOG_FILE_MAXSIZE_MB * 100000;
        if (file_exists($CDASH_LOG_FILE) && filesize($CDASH_LOG_FILE) > $logFileMaxSize) {
            $tempLogFile = $CDASH_LOG_FILE . '.tmp';
            if (!file_exists($tempLogFile)) {
                rename($CDASH_LOG_FILE, $tempLogFile);
                // This should be quick so we can keep logging
                for ($i = 9; $i >= 0; $i--) {
                    // If we do not have compression we just rename the files
                    if (function_exists('gzwrite') === false) {
                        $currentLogFile = $CDASH_LOG_FILE . '.' . $i;
                        $j = $i + 1;
                        $newLogFile = $CDASH_LOG_FILE . '.' . $j;
                        if (file_exists($newLogFile)) {
                            cdash_unlink($newLogFile);
                        }
                        if (file_exists($currentLogFile)) {
                            rename($currentLogFile, $newLogFile);
                        }
                    } else {
                        $currentLogFile = $CDASH_LOG_FILE . '.' . $i . '.gz';
                        $j = $i + 1;
                        $newLogFile = $CDASH_LOG_FILE . '.' . $j . '.gz';
                        if (file_exists($newLogFile)) {
                            cdash_unlink($newLogFile);
                        }
                        if (file_exists($currentLogFile)) {
                            $gz = gzopen($newLogFile, 'wb');
                            $f = fopen($currentLogFile, 'rb');
                            while ($f && !feof($f)) {
                                gzwrite($gz, fread($f, 8192));
                            }
                            fclose($f);
                            unset($f);
                            gzclose($gz);
                            unset($gz);
                        }
                    }
                }
                // Move the current backup
                if (function_exists('gzwrite') === false) {
                    rename($tempLogFile, $CDASH_LOG_FILE . '.0');
                } else {
                    $gz = gzopen($CDASH_LOG_FILE . '.0.gz', 'wb');
                    $f = fopen($tempLogFile, 'rb');
                    while ($f && !feof($f)) {
                        gzwrite($gz, fread($f, 8192));
                    }
                    fclose($f);
                    unset($f);
                    gzclose($gz);
                    unset($gz);
                    cdash_unlink($tempLogFile);
                }
            }
        }
        $pid = getmypid();
        if ($pid !== false) {
            $context['pid'] = getmypid();
        }
    }
    if (Registry::hasLogger('cdash') === false) {
        if ($CDASH_LOG_FILE === false) {
            $handler = new SyslogHandler('cdash', LOG_USER, $minLevel);
            $handler->getFormatter()->ignoreEmptyContextAndExtra();
        } else {
            if ($CDASH_TESTING_MODE) {
                $filePermission = 0666;
            } else {
                $filePermission = 0664;
            }
            $handler = new StreamHandler($CDASH_LOG_FILE, $minLevel, true, $filePermission);
            $handler->getFormatter()->allowInlineLineBreaks();
            $handler->getFormatter()->ignoreEmptyContextAndExtra();
        }
        $logger = new Logger('cdash');
        $logger->pushHandler($handler);
        Registry::addLogger($logger);
    } else {
        $logger = Registry::getInstance('cdash');
    }
    $logger->log($level, $text, $context);
}
Exemplo n.º 14
0
if (is_dir(join(\DIRECTORY_SEPARATOR, array(__DIR__, '..', 'src', 'app', 'Model', 'Entity'))) === false) {
    mkdir(join(\DIRECTORY_SEPARATOR, array(__DIR__, '..', 'src', 'app', 'Model', 'Entity')));
}
$di = new Container();
/* Config */
$di['config'] = function () {
    return ['server' => ['base_uri' => 'https://localhost'], 'orm' => ['driver' => 'pdo_sqlite', 'memory' => true], 'storage' => ['path' => '']];
};
/* Monolog */
$di['log'] = function () {
    $log = new Logger('api');
    //@note For debugging purposes
    $log->pushHandler(new SyslogHandler('minerva-debug'));
    //A simple release logging handler, which uses the system log. For multi-server setups,
    //this needs to be customized, if you want to collect all errors centralized.
    $syslogHandler = new SyslogHandler('minerva-warning');
    $syslogHandler->setLevel(Logger::ERROR);
    $log->pushHandler($syslogHandler);
    return $log;
};
/* Doctrine */
$di['orm'] = function () use($di) {
    //Create cached annotation reader
    AnnotationRegistry::registerFile(__DIR__ . '/../vendor/doctrine/orm/lib/Doctrine/ORM/Mapping/Driver/DoctrineAnnotations.php');
    //@note The ArrayCache is not very fast, if possible, replace with e.g. Memcached
    $cache = new ArrayCache();
    $annotationReader = new AnnotationReader();
    $cachedAnnotationReader = new CachedReader($annotationReader, $cache);
    //Hook annotation driver into driver chain
    $driverChain = new DriverChain();
    //Register entities