public
Last active

MongoDB logging in Lithium PHP

  • Download Gist
MongoLogger.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382
<?php
 
namespace li3_common\analysis;
 
use lithium\action\Request;
use lithium\console\Request as ConsoleRequest;
use lithium\core\Environment;
use lithium\data\Connections;
use lithium\util\String;
use MongoDate;
use MongoId;
 
/**
* A class to enable logging of Mongo database commands
*/
class MongoLogger extends \lithium\core\StaticObject {
 
/**
* A cache of MongoDb source filters that have been set
*
* @var array
*/
protected static $_filters = array();
 
/**
* A list of database connections to log
*
* @var array
*/
protected static $_connections = array('default');
 
/**
* The `lithium\analysis\Logger` priority
*
* @var string
*/
protected static $_priority = 'debug';
 
/**
* Configurable classes to use for logging and MongoDb command exporting
*
* @var array
*/
protected static $_classes = array(
'logger' => 'lithium\analysis\Logger',
'exporter' => 'lithium\data\source\mongo_db\Exporter'
);
 
/**
* `String::insert`-style log formats
*
* Note: default formats can be found in the code inside
* `MongoLogger::config()` because they were too long to
* fit on one line here without breaking the coding standards.
*
* @see affin_common\analysis\MongoLogger::config()
* @var array
*/
protected static $_formats;
 
/**
* A reference to a `Request` object so we can prefix our logs
* with the url or command that the log is for
*
* @param object
*/
protected static $_request;
 
/**
* Configures the logger
*
* @param array $config Valid keys include:
* - `'classes'`: sets the `Logger` and `Exporter` classes
* - `'formats'`: updates the `String::insert()` style log formats
* - `'connections'`: an array of connection names to log
* - `'priority'`: Where to write logs. Defaults to `'debug'`
* - `'request'`: The request object. Defaults to null.
* @return boolean
*/
public static function config($config = array()) {
$defaultFormats = array(
"read" => "{:prefix} - {:dbConn}: db.{:collection}.find({:conditions}, " .
"{:fields}).sort({:sort}).limit({:limit}).skip({:skip})",
"update" => "{:prefix} - {:dbConn}: db.{:collection}.update({:conditions}, " .
"{:update}, {:upsert}, {:multiple})",
"delete" => "{:prefix} - {:dbConn}: db.{:collection}.remove({:conditions}, " .
"{:options})"
);
$defaults = array(
'classes' => static::$_classes,
'connections' => static::$_connections,
'formats' => static::$_formats ?: $defaultFormats,
'priority' => static::$_priority,
'request' => static::$_request
);
$config += $defaults;
foreach ($config as $property => $value) {
$property = "_" . $property;
static::$$property = $value;
}
return true;
}
 
/**
* Converts php mongo classes to their equivalent
* in native mongo javascript for use in the
* mongo shell
*
* @param mixed $value
* @return string
*/
public static function phpToMongoNative($value) {
$js = $value;
switch (true) {
case $value instanceof MongoDate:
$sec = $value->sec;
$js = 'ISODate("' . gmdate('Y-m-d\TH:i:s\Z', $sec) . '")';
break;
case $value instanceof MongoId:
$js = 'ObjectId("' . $value->{'$id'} . '")';
break;
}
return $js;
}
 
/**
* Removes quotes from native javascript objects that
* were escaped by json_encode
*
* @param string $json
* @return string
*/
public static function removeExtraQuotes($json) {
return preg_replace(
array('/"ISODate\(\\\"(.*)\\\"\)"/mU', '/\"ObjectId\(\\\"(.*)\\\"\)\"/mU'),
array('ISODate("$1")', 'ObjectId("$1")'),
$json
);
}
 
/**
* Uses the request to create a prefix to append to the beginning of the log lines.
*
* Either the request url or the li3 command
*
* @return string
*/
public static function prefix() {
$prefix = '';
switch (true) {
case !isset(static::$_request):
$prefix = '';
break;
case static::$_request instanceof \lithium\action\Request:
$prefix = static::$_request->url;
break;
case static::$_request instanceof \lithium\console\Request:
$prefix = "li3 " . implode(' ', static::$_request->argv);
break;
}
return $prefix;
}
 
/**
* Returns whether or not the logged has been enabled
*
* @todo is it possible to get a reference to those connection filters
* so we have the ability to turn off logging after they have been enabled?
*
* @return boolean
*/
public static function enabled() {
return !empty(static::$_filters);
}
 
/**
* Caches logging filters so we know which have been set so we
* have the option to disable them later
*
* @param string $connection Configured connection name
* @param string $method
* @param callback $filter
* @return boolean
*/
protected static function _cacheFilter($connection, $method, &$filter) {
if (!isset(static::$_filters[$connection])) {
static::$_filters[$connection] = array();
}
static::$_filters[$connection][$method] = &$filter;
return true;
}
 
/**
* Enables logging on the configured connections
*
* @see affin_common\analysis\MongoLogger::config()
* @param array $config The same options accepted by `MongoLogger::config()`
* @return boolean `true` on success, `false` if there was a problem
*/
public static function enable($config = array()) {
if (!empty($config)) {
static::config($config);
}
$connections = static::$_connections;
$classes = static::$_classes;
$formats = static::$_formats;
$priority = static::$_priority;
$logger = get_called_class();
 
$toMongoNative = function(&$value, $key) use ($logger) {
$value = $logger::phpToMongoNative($value);
};
$removeExtraQuotes = function($json) use ($logger) {
return $logger::removeExtraQuotes($json);
};
$prefix = static::prefix();
 
$use = compact(
'classes', 'formats', 'priority',
'prefix', 'toMongoNative', 'removeExtraQuotes'
);
 
foreach ($connections as $name) {
$conn = Connections::get($name);
$filter = function($self, $params, $chain) use ($use) {
extract($use);
$logger = $classes['logger'];
$query = $params['query'];
$options = $params['options'];
$args = $query->export($self);
$source = $args['source'];
$conditions = array();
if (isset($args['conditions'])) {
$conditions = $args['conditions'];
array_walk_recursive($conditions, $toMongoNative);
}
 
$logger::write(
$priority,
String::insert($formats['read'], array(
'prefix' => $prefix,
'dbConn' => $self->connection->$source,
'collection' => $source,
'conditions' => $removeExtraQuotes(json_encode((object) $conditions)),
'fields' => json_encode((object) $args['fields']),
'sort' => json_encode((object) $args['order']),
'limit' => (int) $args['limit'],
'skip' => (int) $args['offset']
))
);
return $chain->next($self, $params, $chain);
};
$conn->applyFilter('read', $filter);
static::_cacheFilter($name, 'read', $filter);
 
$filter = function($self, $params, $chain) use ($use) {
extract($use);
$logger = $classes['logger'];
$options = $params['options'];
$query = $params['query'];
$args = $query->export($self, array('keys' => array('conditions', 'source', 'data')));
$source = $args['source'];
$data = $args['data'];
 
$_exp = $classes['exporter'];
if ($query->entity()) {
$data = $_exp::get('update', $data);
}
$update = $query->entity() ? $_exp::toCommand($data) : $data;
 
$conditions = array();
if (isset($args['conditions'])) {
$conditions = $args['conditions'];
array_walk_recursive($conditions, $toMongoNative);
}
 
array_walk_recursive($update, $toMongoNative);
 
if ($options['multiple'] && !preg_grep('/^\$/', array_keys($update))) {
$update = array('$set' => $update);
}
$logger::write(
$priority,
String::insert($formats['update'], array(
'prefix' => $prefix,
'dbConn' => $self->connection->$source,
'collection' => $source,
'conditions' => $removeExtraQuotes(json_encode((object) $conditions)),
'update' => $removeExtraQuotes(json_encode((object) $update)),
'upsert' => (int) ((boolean) $options['upsert']),
'multiple' => (int) ((boolean) $options['multiple'])
))
);
return $chain->next($self, $params, $chain);
};
$conn->applyFilter('update', $filter);
static::_cacheFilter($name, 'read', $filter);
 
$filter = function($self, $params, $chain) use ($use) {
extract($use);
$logger = $classes['logger'];
$query = $params['query'];
$options = $params['options'];
$args = $query->export($self, array('keys' => array('source', 'conditions')));
$source = $args['source'];
$conditions = array();
if (isset($args['conditions'])) {
$conditions = $args['conditions'];
array_walk_recursive($conditions, $toMongoNative);
}
 
$logger::write(
$priority,
String::insert($formats['delete'], array(
'prefix' => $prefix,
'dbConn' => $self->connection->$source,
'collection' => $source,
'conditions' => $removeExtraQuotes(json_encode((object) $conditions)),
'options' => json_encode((object) $options)
))
);
return $chain->next($self, $params, $chain);
};
$conn->applyFilter('delete', $filter);
static::_cacheFilter($name, 'delete', $filter);
}
return true;
}
 
/**
* I'd love to be able to disable the logging mid-request, but it's just
* not possible unless we patch `lithium\core\Object` with a
* `removeFilter` method. Maybe I'll do that...
*
* @param array $connections (optional) A list of connections to remove
* the logging filters from. If omitted, removes from all connections
* @return boolean `true` on success, `false` if there was a problem
*/
public static function disable() {
foreach (static::_filters as $name => $filters) {
$conn = Connections::get($name);
foreach ($filters as $method => $filter) {
// $conn->removeFilter($method, $filter);
}
}
return false;
}
 
/**
* Retrieves a logger function suitable for use as a filter
* for `lithium\action\Dispatcher` and `lithium\console\Dispatcher`
*
* It makes sure that the `Environment` has been configured and if
* not and the `Request` is present in `$params`, it uses the `Request`
* object to set the `Environment`. This is necessary to make sure
* `Connections::get()` won't cause an error.
*
* @see affin_common\analysis\MongoLogger::enable()
* @see affin_common\analysis\MongoLogger::config()
* @param array $config The same options accepted by `MongoLogger::config()`
* @return callback
*/
public static function filter($config = array()) {
$logger = get_called_class();
$use = compact('config', 'logger');
return function($self, $params, $chain) use ($use) {
extract($use);
$prefix = '';
if (isset($params['request'])) {
$environment = Environment::get();
if ($environment == '') {
Environment::set($params['request']);
}
$config['request'] = $params['request'];
}
$logger::enable($config);
return $chain->next($self, $params, $chain);
};
}
}
 
?>
usage.php
PHP
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15
<?php
 
// usage:
use affin_common\analysis\MongoLogger;
use lithium\analysis\Logger;
 
Logger::config(array(
'default' => array('adapter' => 'File')
));
 
$dbLogger = MongoLogger::filter();
Filters::apply('lithium\action\Dispatcher', 'run', $dbLogger);
Filters::apply('lithium\console\Dispatcher', 'run', $dbLogger);
 
?>

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.