开发者

How can I implement "object dumping" with log4php?

开发者 https://www.devze.com 2023-03-05 17:42 出处:网络
I\'m currently in the process of moving from our own proprietary logging solution to log4php in one of our projects. Our own solution has a helper method which I posted below. The purpose of the metho

I'm currently in the process of moving from our own proprietary logging solution to log4php in one of our projects. Our own solution has a helper method which I posted below. The purpose of the method is to write the contents of a variable (and any of it's members recursively) to the log.

The equivalent place for this method in log4php would be the Logger class (I assume). But I wonder what the proper way would be to integrate the functionali开发者_高级运维ty.

Should I just derive from Logger and extend it? Or is there a way to "plug in" this functionality.

Thanks in advance.

/**
* Dump the complete content of the target object to the log.
*
* @param mixed $target The object to dump.
* @param int $level The verbosity level.
* @param int $indent Indentation level.
*/
public static function dump( $target, $level = Logging::eDEBUG, $indent = 0 ) {
  if( $level < self::getInstance()->logLevel ) return;

  if( null == $target ) {
    self::log( "d", "> " . str_repeat( "\t", $indent ) . "null", $level );
    return;
  }

  if( is_string( $target ) || is_numeric( $target ) ) {
    self::log( "d", "> " . str_repeat( "\t", $indent ) . $target, $level );
    return;
  }

  foreach( $target as $key => $value ) {
    if( is_array( $value ) ) {
      self::log( "d", "> " . str_repeat( "\t", $indent ) . $key . " -> Array (", $level );
      self::dump( $value, $level, $indent + 1 );
      self::log( "d", "> " . str_repeat( "\t", $indent ) . ")", $level );
      continue;
    }

    if( is_object( $value ) ) {
      self::log( "d", "> " . str_repeat( "\t", $indent ) . $key . " -> Object (", $level );
      self::dump( (array)$value, $level, $indent + 1 );
      self::log( "d", "> " . str_repeat( "\t", $indent ) . ")", $level );

    } else {
      self::log( "d", "> " . str_repeat( "\t", $indent ) . $key . " -> " . $value, $level );
    }
  }
} 


This is all explained in the log4php docs.

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号