You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

生产环境Appsignal设为:warn级别仍接收info日志问题

Rails生产环境日志级别不生效(Info日志仍发送至Appsignal)

问题描述

生产环境配置3个日志记录器,已将config.log_level设置为:warn,但Rails默认日志和自定义Info级日志仍会发送至Appsignal;预发布(staging)和开发环境配置完全相同,却无此问题。

配置代码(production.rb)

# production.rb

file_logger = ActiveSupport::Logger.new(File.join('log', "#{Rails.env}.log").to_s, 5, 10.megabytes) # keep 5 files with 10 megas
appsignal_logger = Appsignal::Logger.new("#{Rails.application.class.module_parent_name}_#{Rails.env}")

logger = AppLogger.new do |cacheable_logger|
  cacheable_logger.broadcast_to file_logger
  cacheable_logger.broadcast_to appsignal_logger
  cacheable_logger.broadcast_to ActiveSupport::Logger.new($stdout)

  cacheable_logger.appsignal_logger = appsignal_logger
end

config.logger = ActiveSupport::TaggedLogging.new(logger)
config.log_level = :warn

# AppLogger inherits from ActiveSupport::BroadcastLogger
# AppLogger < ActiveSupport::BroadcastLogger

已尝试的无效方案

  • 修改日志级别
  • 移除自定义日志
  • 重写AppLogger子类,尝试在Info级别取消订阅Appsignal日志记录器

解决方案

1. 显式设置每个子Logger的级别

ActiveSupport::BroadcastLogger不会自动将自身级别同步给所有广播的子Logger,需手动为每个子Logger设置级别:

# production.rb
config.log_level = :warn

# 初始化子Logger并显式设置级别
file_logger = ActiveSupport::Logger.new(File.join('log', "#{Rails.env}.log").to_s, 5, 10.megabytes)
file_logger.level = Logger.const_get(config.log_level.upcase)

appsignal_logger = Appsignal::Logger.new("#{Rails.application.class.module_parent_name}_#{Rails.env}")
appsignal_logger.level = Logger.const_get(config.log_level.upcase)

stdout_logger = ActiveSupport::Logger.new($stdout)
stdout_logger.level = Logger.const_get(config.log_level.upcase)

# 初始化自定义Logger并广播
logger = AppLogger.new do |cacheable_logger|
  cacheable_logger.broadcast_to file_logger
  cacheable_logger.broadcast_to appsignal_logger
  cacheable_logger.broadcast_to stdout_logger

  cacheable_logger.appsignal_logger = appsignal_logger
end

# 确保顶层Logger级别正确
logger.level = config.log_level
config.logger = ActiveSupport::TaggedLogging.new(logger)

2. 检查Appsignal独立配置

Appsignal自身有独立的日志级别设置,可能在config/appsignal.yml的生产环境段中覆盖了Rails的配置:

# config/appsignal.yml
production:
  log_level: warn # 将此处改为warn,避免与Rails级别冲突

3. 确认AppLogger的级别继承逻辑

如果AppLogger重写了level=方法,需确保调用super并将级别同步到所有子Logger,包括appsignal_logger:

class AppLogger < ActiveSupport::BroadcastLogger
  def level=(level)
    super
    # 同步级别到所有广播的Logger
    @broadcasts.each { |logger| logger.level = level }
    # 额外同步到自定义的appsignal_logger
    @appsignal_logger&.level = level
  end
end

4. 核对Rails初始化顺序

确保config.log_level的设置在Logger初始化之前,否则顶层Logger可能无法正确获取级别。

内容的提问来源于stack exchange,提问作者pedro

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.13 15:22:47