为什么我的记录器信息在服务 类 上不起作用,但在控制器中却起作用?

Why my logger info its not working on service classes, but in controller it is?

我正在尝试调试我的应用程序。

在我的控制器上,一切看起来都很好。

class AccountsController < ApplicationController
  rescue_from PaymentGateway::CreateSubscriptionServiceError do |e|
    redirect_to root_path, alert: e.message
  end
 def change_plan
    logger.info('Changing the Plan')

但是当我尝试在我的服务文件夹中做同样的事情时:

class PaymentGateway::CreateSubscriptionService < PaymentGateway::Service
  ERROR_MESSAGE = "There was an error while creating the subscription"
  attr_accessor :user, :plan, :token, :subscription, :success

def run
 logger.info('Starting the PaymentGateway::CreateSubscriptionService.run')
    begin
      Subscription.transaction do
        create_client_subscription
        self.subscription = create_subscription
        self.success = true
      end
    rescue PaymentGateway::CreateCustomerService, 
      PaymentGateway::CreatePlanService,
      PaymentGateway::ClientError => e
      raise PaymentGateway::CreateSubscriptionServiceError,e.message

    end
  end

我收到一个错误:

undefined local variable or method `logger' for #<PaymentGateway::CreateSubscriptionService:0x007f2f4eaff788>

我这里做错了什么?

因为在所有控制器上都有一个名为logger的方法。

def logger
  ActionController::Base.logger
end

您可以在 类 中添加一个,或者只使用 Rails.logger 而不是 logger

def logger
  Rails.logger
end

您的服务文件夹中似乎没有初始化记录器。

我认为如果您在服务文件夹中初始化记录器,那么它应该可以工作。

试试这个:logger = Logger.new(STDOUT)