/** * Записывает сообщение в лог. * @param string $level уровень критичности сообщения * @param string $message сообщение, поддерживает плейсхолдеры в формате {placeholder} * @param array $placeholders список плейсхолдеров * @return self */ protected function log($level, $message, array $placeholders = []) { if ($this->traitLogger) { $this->traitLogger->log($level, $message, $placeholders); } return $this; }
/** * Appends the given message along with the additional information into the log. * * @param string $message The message to log * @param integer $severity One of the LOG_* constants * @param mixed $additionalData A variable containing more information about the event to be logged * @param string $packageKey Key of the package triggering the log (determined automatically if not specified) * @param string $className Name of the class triggering the log (determined automatically if not specified) * @param string $methodName Name of the method triggering the log (determined automatically if not specified) * @return void * @api */ public function append($message, $severity = LOG_INFO, $additionalData = NULL, $packageKey = NULL, $className = NULL, $methodName = NULL) { switch ($severity) { case LOG_EMERG: $monologLevel = Logger::EMERGENCY; break; case LOG_ALERT: $monologLevel = Logger::ALERT; break; case LOG_CRIT: $monologLevel = Logger::CRITICAL; break; case LOG_ERR: $monologLevel = Logger::ERROR; break; case LOG_WARNING: $monologLevel = Logger::WARNING; break; case LOG_NOTICE: $monologLevel = Logger::NOTICE; break; case LOG_DEBUG: $monologLevel = Logger::DEBUG; break; default: $monologLevel = Logger::INFO; break; } $this->logger->log($monologLevel, $message, ['packageKey' => $packageKey, 'className' => $className, 'methodName' => $methodName, 'additionalData' => $additionalData]); }
/** * The three arguments below are provided by: * @dataProvider provideMappedSeverities * */ public function testNotifyGetsPassedCorrectlyMappedSeverity($monologLevel, $expectedSeverity) { // Update the tested handler to always send messages rather than just errors. $this->monolog->popHandler($this->testedHandler); $this->testedHandler = new BugsnagHandler($this->mockBugsnag->reveal(), Logger::DEBUG); $this->monolog->pushHandler($this->testedHandler); $errorMessage = "Oh no!"; $this->mockBugsnag->notifyError($expectedSeverity, Argument::any(), Argument::any(), $expectedSeverity)->shouldBeCalledTimes(1); $this->monolog->log($monologLevel, $errorMessage); }
/** * Get tasks that are due to run * * @access public * @return array A list of {@link Task} objects. */ public function getDueTasks() { $this->logger->log(Logger::DEBUG, 'Checking tasks that are due to run. ' . count($this->tasks) . ' total tasks.'); $t = []; foreach ($this->tasks as $task) { $this->logger->log(Logger::DEBUG, 'Checking on "' . $task->getName() . '" (' . $task->getCronString() . ')'); if ($task->isDue()) { $t[] = $task; $this->logger->log(Logger::DEBUG, '"' . $task->getName() . '" IS set to run'); } else { $this->logger->log(Logger::DEBUG, '"' . $task->getName() . '" is not set to run'); } } return $t; }
/** * 写入日志 * @param $msg * @param $name * @param int $level * @param AbstractHandler $handler */ public static function write($msg, $name, $level = Logger::INFO, AbstractHandler $handler = null) { $name .= '_' . $level; $name = $name . '_' . date('Y-m-d-H', Date::now()); if (isset(self::$loggers[$name])) { $logger = self::$loggers[$name]; if ($handler != null) { $logger->pushHandler($handler); } } else { $logger = new Logger($name); if ($handler == null) { $path = ConfigManager::get('log'); $handler = new StreamHandler($path . DIRECTORY_SEPARATOR . $name . '.log', $level); $formatter = new LineFormatter(ConfigManager::get('log_formatter'), 'Y-m-d H:i:s'); $handler->setFormatter($formatter); } $logger->pushHandler($handler); self::$loggers[$name] = $logger; } if (is_scalar($msg) === false) { $msg = json_encode($msg); } $logger->log($level, $msg); }
/** * Extract metadatas from XML * * @param \DOMDocument $document wanted document * @return array */ private function extractDatasFromXML(\DOMDocument $document) { $datas = array(); $xpath = new \DOMXPath($document); $xPathQuery = CssSelector::toXPath('description > *'); $structure = $this->config->get('structure'); foreach ($xpath->query($xPathQuery) as $node) { $nodeName = $node->nodeName; $value = $node->nodeValue; $meta = isset($structure[$nodeName]) ? $structure[$nodeName] : null; $isMulti = !isset($meta['multi']) ? false : !!$meta['multi']; if (!$meta) { $this->logger->log(sprintf('undefined meta name %s', $nodeName)); continue; } if (!isset($datas[$nodeName])) { $datas[$nodeName] = array('values' => array(), 'meta_src' => $meta['src'], 'multi' => $isMulti); } if ($nodeName == 'Date' || $nodeName == 'DatePrisedeVue') { $value = str_replace('/', ':', $value); } $datas[$nodeName]['values'][] = $value; } return $datas; }
/** * Performs an authentication attempt * * @return \Zend\Authentication\Result * @throws \Zend\Authentication\Adapter\Exception\ExceptionInterface If authentication cannot be performed */ public function authenticate() { $result = null; foreach ($this->adapters as $adapter) { $result = $adapter->authenticate(); if ($this->logger !== null) { foreach ($result->getMessages() as $message) { $this->logger->log($result->getCode() > 0 ? Logger::INFO : Logger::ERROR, $message); } } if ($result->isValid()) { //Stop processing on first success result break; } } return $result; }
/** * block and log the user request */ private function blockRequest() { if ($this->logger instanceof Logger) { $this->logger->log(Logger::INFO, sprintf("blocked a requests flood for page %s%s from ip: %s with cookie %s", $this->getHttpHost(), $this->getRequestUri(), $this->getIpAddress(), $this->getCookie())); header('HTTP/1.0 403 Forbidden'); } exit(sprintf('please wait %s seconds and refresh the page', $this->blockingPeriod)); }
/** * On dispatch event listener - called on any event * * @param Event $event * @param string $eventName * @return void */ private function log($level, $message, $ev, array $context = []) { if ($this->logger) { $message = sprintf("QueueGet [1;36m%s@%s[0m %s", $ev->getRoutingKey(), $ev->getExchangeName(), $message); $context["command"] = AddonsEvent::QUEUE_GET_COMMAND; $this->logger->log($level, $message, $context); } }
/** * {@inheritdoc} */ public function flushBuffer($force = false) { if (!empty($this->request_arguments) || $force) { foreach ($this->buffer as $log_entry) { $this->logger->log($log_entry['level'], $log_entry['message'], array_merge($this->env_arguments, $this->request_arguments, $log_entry['context'])); } $this->buffer = []; } }
function primeExceptionHandler(Exception $exc) { $logger = new Logger('app_runtime'); $logger->pushHandler(new RotatingFileHandler(Filesystem::getInstance()->getPath('log') . '/app.log')); $code = $exc->getCode(); if ($code == 0) { $code = Logger::ALERT; } $logger->log($code, $exc->getMessage()); }
/** * Run task * * Note that the optional params are here because the lib expects this * functionality but if a developer were to extend the lib, these may * no longer be relevant. For more on this, see the comment that's inside * {@link Shideon\Tasker\AbstractCommand::getConfigOptions()} * * @access public * @param bool $async Run asynchronously * @param string $configFile Config file to send to command. * @param string $logFile Log file to send to command. * @param string $logLevel Log level to pass to command. */ public function run($async, $configFile = null, $logFile = null, $logLevel = null) { $this->validate(); $cmd = $this->buildRunCommand($async, $configFile, $logFile, $logLevel); $this->logger->log(Logger::INFO, "Running task '" . $this->getName() . "' in background: {$cmd}"); // note that we use shell_exec instead of symfony's // Process because it's causing issues with // sub process having open file handle. shell_exec($cmd); }
/** * @see \Monolog\Logger::log() * * @param string $level [debug,info,notice,warning,error,critical,alert,emergency] * @param string $message * @param array $context * @return bool */ public static function log($level, $message, array $context = []) { if (self::$logger == null) { if (self::$strict) { $e = new Exception("Logger has not been set!"); $e->setData(array("level" => $level, "message" => $message, "context" => $context)); throw $e; } else { return false; } } return self::$logger->log($level, $message, $context); }
public function log($level = Logger::INFO, $message = '[no message]', $context = array(), $description = null, $tags = array(), $serialiseContext = false) { $this->initLogger(); // collect pertinent information for log $this->callingClass = $this->callingMethod = null; $this->tags = $tags; $this->description = $description; $backtrace = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS); $this->callingClass = isset($backtrace[1]['class']) ? $backtrace[1]['class'] : null; $this->callingMethod = isset($backtrace[1]['function']) ? $backtrace[1]['function'] : null; // optionally serialise the context data if ($serialiseContext && !empty($context)) { $context = ['context-serialised' => serialize($context)]; } try { $this->logger->log($level, $message, is_array($context) ? $context : [$context]); } catch (Exception $e) { // something went wrong - investigation will be conducted when it is seen that no new logs are created } }
/** * @param \stdClass $dataRow * @param string $type for logging * @param string $outerObjectHash * @return string */ protected function getPrimaryKeyValue(\stdClass $dataRow, $type, $outerObjectHash = null) { // Try to find a "real" parent ID if (!empty($this->primaryKeys[$this->createSafeName($type)])) { $pk = $this->primaryKeys[$this->createSafeName($type)]; $pKeyCols = explode(',', $pk); $pKeyCols = array_map('trim', $pKeyCols); $values = []; foreach ($pKeyCols as $pKeyCol) { if (empty($dataRow->{$pKeyCol})) { $values[] = md5(serialize($dataRow) . $outerObjectHash); $this->log->log("WARNING", "Primary key for type '{$type}' was set to '{$pk}', but its column '{$pKeyCol}' does not exist! Using hash to link child objects instead.", ['row' => $dataRow]); } else { $values[] = $dataRow->{$pKeyCol}; } } return $type . "_" . join(";", $values); } else { // Of no pkey is specified to get the real ID, use a hash of the row return $type . "_" . md5(serialize($dataRow) . $outerObjectHash); } }
/** * Analyze row of input data & create $this->struct * * @param mixed $row * @param string $type * @return void */ protected function analyzeRow($row, $type) { // Current row's structure $struct = []; $rowType = $this->getType($row); // If the row is scalar, make it a {"data" => $value} object if (is_scalar($row)) { $struct[Parser::DATA_COLUMN] = $this->getType($row); } elseif (is_object($row)) { // process each property of the object foreach ($row as $key => $field) { $fieldType = $this->getType($field); if ($fieldType == "object") { // Only assign the type if the object isn't empty if (Utils::isEmptyObject($field)) { continue; } $this->analyzeRow($field, $type . "." . $key); } elseif ($fieldType == "array") { $arrayType = $this->analyze($field, $type . "." . $key); if (false !== $arrayType) { $fieldType = 'arrayOf' . $arrayType; } else { $fieldType = 'NULL'; } } $struct[$key] = $fieldType; } } elseif ($this->nestedArrayAsJson && is_array($row)) { $this->log->log("WARNING", "Unsupported array nesting in '{$type}'! Converting to JSON string.", ['row' => $row]); $rowType = $struct[Parser::DATA_COLUMN] = 'string'; } elseif (is_null($row)) { // do nothing } else { throw new JsonParserException("Unsupported data row in '{$type}'!", ['row' => $row]); } $this->getStruct()->add($type, $struct); return $rowType; }
/** * Sends a message to Monolog. * * @param string $message The message to write * @param int $level One of the levels defined by Monolog (e.g. INFO, DEBUG, ERROR, etc.) * @param array $context */ private function log($message, $level = Logger::DEBUG, $context = array()) { if ($this->logger instanceof Logger) { $this->logger->log($level, $message, $context); } }
public function log($message, $level = self::DEBUG, array $context = []) { $level = $this->translateLevel($level); return parent::log($level, $message, $context); }
/** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $context * @return null */ public function log($level, $message, array $context = array()) { $this->logger->log($level, $message, $context); }
/** * Adds a log record at an arbitrary level. * * This method allows for compatibility with common interfaces. * * @param mixed $level The log level * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed * @static */ public static function log($level, $message, $context = array()) { return \Monolog\Logger::log($level, $message, $context); }
/** * Convenience method to log a message. * * @param string $message * @param array $context * @param string $level */ private function log($message, $context = array(), $level = 'info') { $this->logger->log($level, $message, $context); }
/** * @param mixed $level * @param string $message * @param array $context * @return bool */ public function log($level, $message, array $context = array()) { return parent::log($level, $message, $context); }
/** * Logs with an arbitrary level. * * @param mixed $level * @param string $message * @param array $params * @param array $context * @return null */ public function log($level, $message, array $params = array(), array $context = array()) { $logMessage = $this->createMessage($message, $params); $this->logger->log($level, $logMessage, $context); }
/** * Logs a message with the given type and category. * * @param string $message the message to be logged. * @param integer $level the level of the message. This must be one of the following: * `Logger::LEVEL_ERROR`, `Logger::LEVEL_WARNING`, `Logger::LEVEL_INFO`, `Logger::LEVEL_TRACE`, * `Logger::LEVEL_PROFILE_BEGIN`, `Logger::LEVEL_PROFILE_END`. * @param string $category the category of the message. * * @return boolean Whether the record has been processed. */ public function yiiLog($message, $level, $category = 'application') { return $this->_monolog->log($level, $message, ['category' => $category]); }
/** * Adds a log record at an arbitrary level. * * This method allows for compatibility with common interfaces. * * @param mixed $level The log level * @param string $message The log message * @param array $context The log context * @return Boolean Whether the record has been processed */ public function log($level, $message, array $context = array()) { if (defined('NFWP_LOG') && NFWP_LOG) { return $this->logger->log($level, $message, $context); } }
/** * Common function to log, wrapper for comunicate with monolog * * @param string $channel The loggin channel * @param string $message The log message * @param integer $level The level to log [optional] * @param array $context The log context * @return void * @todo - Add custom way for log location */ public function log($message, $level = Logger::DEBUG, array $context = []) { self::$logger->log($level, $message, $context); }
public function log($level, $log, array $context = array()) { parent::log($level, $log, $context); }
<?php $start = microtime(true); require_once 'vendor/autoload.php'; use Monolog\Formatter\LogstashFormatter; use Monolog\Logger; $log = new Logger('myapp_logger'); $logPath = 'C:\\Programs\\dev\\logstash-2.1.1\\bin\\logstash.log'; $stream = new Monolog\Handler\StreamHandler($logPath); $log->pushHandler($stream); $eventSourceName = '127.0.0.1'; $eventTypeName = 'monolog_sourced_log'; $formater = new LogstashFormatter($eventTypeName, $eventSourceName, null, 'ctxt_', LogstashFormatter::V1); $stream->setFormatter($formater); $processor = new Monolog\Processor\WebProcessor(); $log->pushProcessor($processor); usleep(rand(1, 100) * 1000); $elapsed = (microtime(true) - $start) * 1000; $log->log(Logger::DEBUG, 'Request logged', ['timing' => $elapsed]);
/** * Adds a log record. * * @param integer $level The logging level * @param string $message The log message * @param array $context The log context * @return bool Whether the record has been processed */ public function log($level, $message, array $context = []) { return $this->monolog->log($level, $message, $context); }
/** * If enabled, and an object contains an array where * an array is not expected, a "link" ID is saved in place * of the string and a child CSV is created. * * This should **only** be used with $analyzeRows = -1 * * Only enable this as a last resort if you cannot supply a JSON * without inconsistent array/object conflicts * @param bool $enable * @experimental */ public function setAutoUpgradeToArray($enable) { $this->log->log('debug', "Using automatic conversion of single values to arrays where required."); $this->autoUpgradeToArray = (bool) $enable; }