Example #1
0
 /**
     this function registers the login actions of users
 */
 public static function logreg($action)
 {
     try {
         $log = new Monolog\Logger('login');
         $log->pushHandler(new Monolog\Handler\StreamHandler('../log/login.log', Monolog\Logger::INFO));
         $usr = Session::get('user_name');
         $message = $action . " Successfully";
         $log->addInfo($message, array('username' => $usr));
     } catch (Exception $e) {
         echo 'Caught exception: ', $e->getMessage(), "\n";
     }
 }
Example #2
0
 /**
  * Adds new website alias.
  *
  * @param Data\WebDomain $websiteAlias
  * @return int website alias id
  */
 public function addWebsiteAlias(Data\WebDomain $websiteAlias)
 {
     // apply the default values
     $webInfo = $this->getServerInfo($websiteAlias->serverId, self::SERVER_INFO_WEB);
     /* @var $webInfo Data\Server\Web */
     $websiteAlias->applyDefaultValues(array('documentRoot' => $webInfo->websitePath, 'phpOpenBasedir' => $webInfo->phpOpenBasedir, 'systemUser' => $webInfo->user, 'systemGroup' => $webInfo->group, 'type' => Data\WebDomain::TYPE_ALIAS, 'hdQuota' => -1, 'trafficQuota' => -1, 'subdomain' => '*', 'allowOverride' => 'all', 'active' => 'y'));
     $data = $websiteAlias->toData();
     $clientId = $data['client_id'];
     unset($data['client_id']);
     $id = $this->server->sites_web_domain_add($this->sessionId, $clientId, $data);
     $websiteAlias->id = $id;
     $this->log->addInfo("Created new website alias {$websiteAlias->domain}[{$id}]");
     return $id;
 }
Example #3
0
 /**
  * @param $data
  * @param string $code
  */
 public static function log($data, $code = 'debug')
 {
     $logfile = DATA . 'log/run.log';
     $log = new \Monolog\Logger('run');
     $log->pushHandler(new \Monolog\Handler\StreamHandler($logfile, \Monolog\Logger::WARNING));
     if ($code == 'info') {
         $log->addInfo($data);
     } elseif ($code == 'warn') {
         $log->addWarning($data);
     } elseif ($code == 'error') {
         $log->addError($data);
     } else {
         $log->addDebug($data);
     }
 }
        if (endpoints\Auth::validateToken($token)) {
            return $next($request, $response);
        }
    }
    return $response->withStatus(401);
});
$checkProxyHeaders = true;
// Note: Never trust the IP address for security processes!
$trustedProxies = ['10.0.0.1', '10.0.0.2'];
// Note: Never trust the IP address for security processes!
$app->add(new \RKA\Middleware\IpAddress($checkProxyHeaders, $trustedProxies));
$stream = new \Monolog\Handler\StreamHandler(__DIR__ . '/../log/app.log', \Monolog\Logger::DEBUG);
$logger = new \Monolog\Logger('app');
$logger->pushHandler($stream);
$app->add(function ($request, $response, $next) use($logger) {
    $response = $next($request, $response);
    $uri = $request->getUri()->getPath();
    $statusCode = $response->getStatusCode();
    switch ($response->getStatusCode()) {
        case 500:
            $logger->addCritical('Oops!!! the server got 500 error', ['ip' => $request->getAttribute('ip_address'), 'uri' => $uri, 'status' => $statusCode]);
            break;
        case 404:
            $logger->addWarning('Someone calling un-existing API endpoint', ['ip' => $request->getAttribute('ip_address'), 'uri' => $uri, 'status' => $statusCode]);
            break;
        default:
            $logger->addInfo('Someone calling existing API endpoint', ['ip' => $request->getAttribute('ip_address'), 'uri' => $uri, 'status' => $statusCode]);
            break;
    }
    return $response;
});
Example #5
0
}
// prepare demo paths
$exePath = '/usr/bin/git';
$source = '/projects/MySQL-to-object-mapper';
$path = '/run/media/bogdan/My Passport/up/';
$branch = 'master';
// prepare logger
$logger = new \Monolog\Logger('console');
$logger->pushHandler(new \Monolog\Handler\StreamHandler(fopen('php://stderr', 'w')));
$launcherEngine = new \PHPVCSControl\Support\Launchers\Exec($logger, new \PHPVCSControl\Support\Filesystem());
$demoRepository = \PHPVCSControl\Git\Repository::build($launcherEngine, $exePath, $source, $branch, $path);
//////////////////////////////////////////////////
// Do sample actions
//////////////////////////////////////////////////
// Clone repository
$logger->addInfo(sprintf('Cloning demo repository [%s]', $source));
$demoRepository->cloneRepository();
// Check if the repository is deployed
$isDeployed = $demoRepository->isDeployed();
$logger->addInfo(sprintf('Is the repository deployed? [%s]', $isDeployed ? 'yes' : 'no'));
// Get the repository's configuration
$logger->addInfo('Get configuration: ' . $demoRepository->getConfiguration()->toJSON());
// Fetch
$demoRepository->fetch();
$logger->addInfo('Fetched');
// Get the commits
$commitCollection = $demoRepository->commits('2000-01-01', VCS_FLAG_NO_MERGES + VCS_FLAG_NO_WALK + VCS_FLAG_TAGS);
$logger->addInfo('Get commit count: ' . $commitCollection->count());
// List commits' details
$commitCollection->forAll(function ($i, $item) use($logger) {
    $logger->info($item->sha . ' [' . $item->date . '] [lines added: ' . $item->linesAdded . '] [lines removed: ' . $item->linesRemoved . ']');
Example #6
0
 public function installBundle($bundle, $zipFile, $date = null)
 {
     $logFile = $this->getLogFile();
     if ($date) {
         $logFile = $logFile . '-' . $date;
     }
     $logFile .= '.log';
     @unlink($logFile);
     $fileLogger = new \Monolog\Logger('package.update');
     $fileLogger->pushHandler(new \Monolog\Handler\StreamHandler($logFile));
     $fileLogger->addInfo('Downloading archive...');
     $version = $this->getBundleLastInstallableVersion($bundle, $this->getCoreBundleVersion());
     $fs = new FileSystem();
     //extract and unzip in the correct directory
     $extractPath = sys_get_temp_dir() . '/' . uniqid();
     $zip = new \ZipArchive();
     $zip->open($zipFile);
     $fileLogger->addInfo("Extraction...");
     $zip->extractTo($extractPath);
     //rename the $extractPath root (it currently has -version at the end)
     $iterator = new \DirectoryIterator($extractPath);
     foreach ($iterator as $el) {
         //there should be only one directory so...
         if ($el->isDir() && !$el->isDot()) {
             $parts = explode('-', $el->getBaseName());
             $fs->rename($el->getPathName(), $extractPath . '/' . $parts[0]);
         }
     }
     //move the source where they should be
     $composer = $extractPath . "/{$bundle}/composer.json";
     $json = file_get_contents($composer);
     $data = json_decode($json);
     $targetDir = 'target-dir';
     $parts = explode('/', $data->{$targetDir});
     $newPath = $this->vendorDir . '/' . $data->name . '/' . $data->{$targetDir};
     $vendor = $parts[0];
     $baseParts = explode('Bundle', $parts[1]);
     $baseName = $baseParts[0];
     $fileLogger->addInfo("Removing old sources...");
     $fs->rmdir($newPath, true);
     $fileLogger->addInfo("Copying sources from temporary directory...");
     $fs->copyDir($extractPath . "/{$bundle}", $newPath);
     //then we update the autoloader
     $parts = explode('/', $data->name);
     $vname = $parts[0];
     $bname = $parts[1];
     $bundleType = $data->type;
     $updatedTarget = str_replace('/', '\\', $data->{$targetDir});
     $fqcn = $updatedTarget . '\\' . str_replace('\\', '', $updatedTarget);
     $fileLogger->addInfo("Updating vendor/composer/autoload_namespace.php...");
     $this->updateAutoload($vendor, $baseName, $vname, $bname);
     $fileLogger->addInfo("Updating app/config/bundle.ini...");
     $this->updateIniFile($vendor, $baseName);
     $fileLogger->addInfo("Generating app/config/operations.xml...");
     $this->generateUniqueOperationFile($bundle, $version, $bundleType, $fqcn, $logFile);
     //We need a different process to execute the update as the new sources were
     //not loaded by php yet.
     //It's much easier than trying to load/refresh everything.
     //TODO: use Sf2 proces library to avoid mistakes
     //sanitize this
     $executor = $this->kernelRootDir . '/../vendor/claroline/core-bundle/Claroline/CoreBundle/Library/Installation/scripts/operation_executor.php';
     $phpErrors = $this->kernelRootDir . "/logs/php_errors_{$date}.log";
     exec("php {$executor} {$date} > {$phpErrors}");
 }
Example #7
0
<!DOCTYPE html>

<?php 
$webAppVersion = "2.0.0";
$webAppTitle = "Démonstration Azure Web Apps & PHP";
require __DIR__ . '/vendor/autoload.php';
$log = new Monolog\Logger('WebAppLogger');
$log->pushHandler(new Monolog\Handler\StreamHandler('webapp.log', Monolog\Logger::INFO));
$log->addInfo('Index.php called');
?>

<html lang="en">
  <head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <!-- The above 3 meta tags *must* come first in the head; any other head content must come *after* these tags -->
    <meta name="description" content="">
    <meta name="author" content="">
    <link rel="icon" href="../../favicon.ico">

    <title>Azure Web App - PHP</title>

    <!-- Bootstrap core CSS -->
    <link href="css/bootstrap.min.css" rel="stylesheet">
    <link href="css/bootstrap-theme.min.css" rel="stylesheet">

    <!-- HTML5 shim and Respond.js for IE8 support of HTML5 elements and media queries -->
    <!--[if lt IE 9]>
      <script src="https://oss.maxcdn.com/html5shiv/3.7.2/html5shiv.min.js"></script>
      <script src="https://oss.maxcdn.com/respond/1.4.2/respond.min.js"></script>
Example #8
0
 /**
  * @EXT\Route(
  *     "/request/friend/name/{name}",
  *     name="oauth_request_friend_new",
  *     options = {"expose"=true}
  * )
  *
  * @return Response
  */
 public function newFriendRequestAction($name)
 {
     $logFile = $this->container->getParameter('claroline.param.claroline_log');
     $host = $this->request->query->get('host');
     //uncomment this for debugging puroposes...
     if ($this->container->get('kernel')->getEnvironment() === 'dev') {
         $fileLogger = new \Monolog\Logger('claroline.debug.log');
         $fileLogger->pushHandler(new \Monolog\Handler\StreamHandler($logFile));
         $fileLogger->addInfo(var_export($this->oauthManager->isAutoCreated($host), true));
     }
     $this->oauthManager->addPendingFriendRequest($name, $host, $this->oauthManager->isAutoCreated($host));
     return new JsonResponse(array('name' => $name, 'host' => $host));
 }
Example #9
0
<?php

require __DIR__ . '/../vendor/autoload.php';
$log = new Monolog\Logger('name');
$log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::INFO));
$app = new \Slim\Slim();
$app->get('/hello/:name', function ($name) {
    echo "Hello, {$name}";
    $log->addInfo('It works! I <3 Composer.');
});
$app->run();
Example #10
0
<?php

require __DIR__ . "/vendor/autoload.php";
$log = new Monolog\Logger('Log');
$log->pushHandler(new Monolog\Handler\StreamHandler('herapp.log', Monolog\Logger::INFO));
$log->pushHandler(new Monolog\Handler\StreamHandler('php://stderr', Monolog\Logger::INFO));
$log->addInfo('Start App');
$path = parse_url($_SERVER['REQUEST_URI'], PHP_URL_PATH);
if (preg_match('/messages\\/\\d+/', $path)) {
    echo 'messages/id';
} elseif (preg_match('/messages(\\/)*$/', $path)) {
    echo 'messages';
} else {
    $log->addInfo('Not exists ' . $path);
    echo 'not found';
}
Example #11
0
/**
 * jet Log 函数 用于记录日志
 * @param   string $type 日志类型
 * @param   string $message 日志的内容
 * @param   string $file_name 日志文件的位置
 */
function jet_log($message, $type = 'SYSTEM', $file_name = 'log.txt')
{
    $log = new Monolog\Logger($type);
    $log->pushHandler(new Monolog\Handler\StreamHandler(RUNTIME . '/logs/' . $file_name));
    $log->addInfo($message);
}
Example #12
0
 /**
  * Setup logging
  */
 protected function setupLogging()
 {
     $path = $this->_config->getVarPath() . '/log';
     //create an access log with browser information
     $accessLog = new \Monolog\Logger('access');
     $accessLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/access_log'));
     $accessMessage = "[{$_SERVER['REQUEST_METHOD']} {$_SERVER['REQUEST_URI']} {$_SERVER['SERVER_PROTOCOL']}] " . '[' . (!empty($_SERVER['HTTP_REFERER']) ? $_SERVER['HTTP_REFERER'] : '-') . '] ' . '[' . (!empty($_SERVER['HTTP_USER_AGENT']) ? $_SERVER['HTTP_USER_AGENT'] : '-') . ']';
     $accessLog->addInfo($accessMessage);
     //create an authenticationLog
     $this->_authLog = new \Monolog\Logger('authentication');
     $this->_authLog->pushHandler(new \Monolog\Handler\StreamHandler($path . '/authentication_log'));
     //create an authenticationLog
     $this->_404Log = new \Monolog\Logger('404');
     $this->_404Log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/404_log'));
     $this->_log = new \Monolog\Logger('jazzee');
     $this->_log->pushProcessor(new \Monolog\Processor\WebProcessor());
     $this->_log->pushProcessor(new \Monolog\Processor\IntrospectionProcessor());
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/strict_log'));
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/messages_log', \Monolog\Logger::INFO));
     $this->_log->pushHandler(new \Monolog\Handler\StreamHandler($path . '/error_log', \Monolog\Logger::ERROR));
     $this->_log->pushHandler(new \Monolog\Handler\SyslogHandler('jazzee', 'syslog', \Monolog\Logger::ERROR));
     //Handle PHP errors with out logs
     set_error_handler(array($this, 'handleError'));
     //catch any excpetions
     set_exception_handler(array($this, 'handleException'));
 }
Example #13
0
<?php

require __DIR__ . '/vendor/autoload.php';
function getUserIP()
{
    $client = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote = $_SERVER['REMOTE_ADDR'];
    if (filter_var($client, FILTER_VALIDATE_IP)) {
        $ip = $client;
    } elseif (filter_var($forward, FILTER_VALIDATE_IP)) {
        $ip = $forward;
    } else {
        $ip = $remote;
    }
    return $ip;
}
$dateFormat = "Y-m-d H:i:s";
$outputFormat = "%datetime% %level_name% %message% %context% %extra%  (%channel%)\n";
$formatter = new Monolog\Formatter\LineFormatter($outputFormat, $dateFormat);
$logHandler = new Monolog\Handler\RotatingFileHandler(__DIR__ . '\\logs\\notif.log', Monolog\Logger::DEBUG);
$logHandler->setFormatter($formatter);
$log = new Monolog\Logger('G');
$log->pushHandler($logHandler);
$requestBodyStr = file_get_contents('php://input');
$info = array("REMOTE_ADDR" => @$_SERVER['REMOTE_ADDR'], "IP" => getUserIP(), "AUTH_USER" => @$_SERVER['PHP_AUTH_USER'], "AUTH_PW" => @$_SERVER['PHP_AUTH_PW'], "GET" => $_GET, "POST" => $_POST, "PostBody" => $requestBodyStr);
$log->addInfo("Received:", $info);
echo "<pre>";
print_r($info);
echo "</pre>";
//phpinfo();
Example #14
0
use Guzzle\Http\Client;
use Guzzle\Http\EntityBody;
use Guzzle\Http\Message\Request;
use Guzzle\Http\Message\Response;
# Logs
/** Setting logs **/
$logger = new Monolog\Logger('client');
$logger->pushHandler(new Monolog\Handler\StreamHandler('guzzle.log'));
$logAdapter = new Guzzle\Log\MonologLogAdapter($logger);
$logPlugin = new Guzzle\Plugin\Log\LogPlugin($logAdapter, Guzzle\Log\MessageFormatter::DEBUG_FORMAT);
/** @var $client Client */
$client = new Client("http://google.com.br", array('curl.options' => array('CURLOPT_RETURNTRANSFER' => TRUE)));
$client->addSubscriber($logPlugin);
/** @var $request Request */
$request = $client->get();
/** @var $response Response */
$response = $request->send();
/** @var $body EntityBody */
$body = $response->getBody(true);
/*
echo $response->getStatusCode();      // >>> 200
echo $response->getReasonPhrase();    // >>> OK
echo $response->getProtocol();        // >>> HTTP
echo $response->getProtocolVersion(); // >>> 1.1
*/
/** @var $responseInfo O retorno HTTP da requisição **/
$responseInfo = $response->getInfo();
$arrayInfoTransfer = array('http_code' => $responseInfo['http_code'], 'total_time' => $responseInfo['total_time'], 'redirect_count' => $responseInfo['redirect_count'], 'content_type' => $responseInfo['content_type'], 'content' => base64_encode($body));
$returnString = json_encode($arrayInfoTransfer);
$logger->addInfo(base64_encode($body));
echo $returnString;
Example #15
0
 public function log($type, $text)
 {
     $log = new Monolog\Logger($type);
     $log->pushHandler(new Monolog\Handler\StreamHandler('app.log', Monolog\Logger::INFO));
     $log->addInfo($text);
 }