一种使记录实例变量在ruby中更干的方法?

时间:2017-04-28 04:27:32

标签: ruby logging dry

我在开发模式下正在进行日志记录,但我发现有时我会记录更多的代码而不是代码本身。

正如我调试问题一样,我意识到我需要让日志更加冗长,所以我知道发生了什么。

但后来我最终得到了类似的东西:

    json_log      =  {:replace_hash => @replace_hash}
    logger.info json_log.to_json

    json_log      =  {:outbound_text => @outbound_text}
    logger.info  json_log.to_json

    json_log      =  {:xtest => @xtest_array}
    logger.info  json_log.to_json

    json_log      =  {:tags => @tag_hash.keys, :last_response => @last_response }
    logger.info   json_log.to_json


    @json_event = { :bot_client_id => @bot_client_id,
                    :that          => @that,
                    :topic         => @topic,
                    :input         => @inbound_text,
                    :last_response => @last_response,
                    :via           => @via
                  }

    send_to_amplitude

    json_log = {:conversation => {:inbound_text => @inbound_text, :outbound_text => @outbound_text}}
    logger.debug json_log.to_s

    Keen.publish(:bot_response_run, @json_event)

1 个答案:

答案 0 :(得分:0)

我想到的第一件事 - 您的哈希键通常与实例变量相同,因此您可以拥有一个记录器类,假定它需要记录实例变量的哈希值

    <?php
// Include FB config file && User class
require_once 'fbConfig.php';
require_once 'User.php';

if(isset($accessToken)){
    if(isset($_SESSION['facebook_access_token'])){
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }else{
        // Put short-lived access token in session
        $_SESSION['facebook_access_token'] = (string) $accessToken;

        // OAuth 2.0 client handler helps to manage access tokens
        $oAuth2Client = $fb->getOAuth2Client();

        // Exchanges a short-lived access token for a long-lived one
        $longLivedAccessToken = $oAuth2Client->getLongLivedAccessToken($_SESSION['facebook_access_token']);
        $_SESSION['facebook_access_token'] = (string) $longLivedAccessToken;

        // Set default access token to be used in script
        $fb->setDefaultAccessToken($_SESSION['facebook_access_token']);
    }

    // Redirect the user back to the same page if url has "code" parameter in query string
    if(isset($_GET['code'])){
        header('Location: ./');
    }

    // Getting user facebook profile info
    try {
        $profileRequest = $fb->get('/me?fields=name,first_name,last_name,email,gender');
        $fbUserProfile = $profileRequest->getGraphNode()->asArray();
    } catch(FacebookResponseException $e) {
        echo 'Graph returned an error: ' . $e->getMessage();
        session_destroy();
        // Redirect user back to app login page
        header("Location: ./");
        exit;
    } catch(FacebookSDKException $e) {
        echo 'Facebook SDK returned an error: ' . $e->getMessage();
        exit;
    }

    // Initialize User class
    $user = new User();

    // Insert or update user data to the database
    $fbUserData = array(
        'oauth_provider'=> 'facebook',
        'user_id'   => $fbUserProfile['id'],
        'first_name'    => $fbUserProfile['first_name'],
        'last_name'     => $fbUserProfile['last_name'],
        'email'         => $fbUserProfile['email'],
        'gender'        => $fbUserProfile['gender']
    );
    $userData = $user->checkUser($fbUserData);

    // Put user data into session
    $_SESSION['userData'] = $userData;

    // Get logout url
    $logoutURL = $helper->getLogoutUrl($accessToken, $redirectURL.'logout.php');

    // Render facebook profile data
    if(!empty($userData)){
        $output  = '<h1>Facebook Profile Details </h1>';
        $output .= '<img src="'.$userData['picture'].'">';
        $output .= '<br/>Facebook ID : ' . $userData['user_id'];
        $output .= '<br/>Name : ' . $userData['first_name'].' '.$userData['last_name'];
        $output .= '<br/>Email : ' . $userData['email'];
        $output .= '<br/>Gender : ' . $userData['gender'];


        $output .= '<br/>Logout from <a href="'.$logoutURL.'">Facebook</a>'; 
    }else{
        $output = '<h3 style="color:red">Some problem occurred, please try again.</h3>';
    }

}else{
    // Get login url
    $loginURL = $helper->getLoginUrl($redirectURL, $fbPermissions);

    // Render facebook login button
    $output = '<a href="'.htmlspecialchars($loginURL).'"><img src="images/fblogin-btn.png"></a>';
}
?>
<html>
<head>
<title>Login with Facebook using PHP by CodexWorld</title>
<style type="text/css">
    h1{font-family:Arial, Helvetica, sans-serif;color:#999999;}
</style>
</head>
<body>
    <!-- Display login button / Facebook profile information -->
    <div><?php echo $output; ?></div>
</body>
</html>

所以稍后在您的代码中而不是

class MyLogger
  def initialize(rails_logger, context)
    @loger = rails_logger
    @context = context
  end

  def log(*args)
    @logger.info(extract_data(*args).to_json)
  end

  def log_with_prefix(prefix, *args)
    @logger.debug({ prefix: extract_data(*args) }.to_s)
  end    

  private

  def extract_data(*args)
    args.reduce({}) do |result, variable|
      result[variable] = extract_value(variable)
      result
    end
  end

  def extract_value(variable)
    name, method = variable.to_s.split('.')
    method.present? ? context.instance_variable_get("@#{name}") : context.instance_variable_get("@#{variable}").public_send(method)
  end       
end

你会有

json_log      =  {:replace_hash => @replace_hash}
logger.info json_log.to_json

json_log      =  {:outbound_text => @outbound_text}
logger.info  json_log.to_json

json_log      =  {:xtest => @xtest_array}
logger.info  json_log.to_json

json_log      =  {:tags => @tag_hash.keys, :last_response => @last_response }
logger.info   json_log.to_json

而不是

@logger = MyLogger.new(logger, self)
@logger.log(:replace_hash)
@logger.log(:outbound_text)
@logger.log(:xtest)
@logger.log(:tag_hash.keys, :last_response)

你会有

json_log = {:conversation => {:inbound_text => @inbound_text, :outbound_text => @outbound_text}}
logger.debug json_log.to_s