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

Symfony 6 Command运行时日志无法写入日志文件问题求助

Symfony 6 自定义命令日志无法写入文件问题修复

核心原因

  • 代码存在属性名不一致的笔误:类声明的私有属性是$subscriptionLogger,构造函数内却给未声明的$this->logger赋值,依赖动态属性运行,存在兼容风险。
  • 未给自定义的subscription日志频道配置文件写入handler:Symfony的日志写入规则由Monolog组件配置控制,和services.yml无关。默认配置下CLI命令的日志仅绑定控制台输出handler,且默认触发级别为error,低于该级别的日志会被直接过滤,也不会写入磁盘文件。
  • cron场景额外存在工作目录、执行路径、权限的潜在问题,会加剧日志写入失败的情况。

修复步骤

  • 修正代码属性笔误,统一属性名避免动态属性问题:
namespace App\Command;
use Symfony\Component\Console\Command\Command;
use Symfony\Component\Console\Input\InputInterface;
use Symfony\Component\Console\Output\OutputInterface;
use Psr\Log\LoggerInterface;

class StillSubscriberReminderCommand extends Command
{
    protected static $defaultName = 'app:still_subscriber_reminder';
    // 统一属性名,和后续调用、构造函数赋值对齐
    private $logger;

    public function __construct(LoggerInterface $subscriptionLogger)
    {
        $this->logger = $subscriptionLogger;
        parent::__construct();
    }
    protected function configure()
    {
        $this->setDescription('Still subscriber reminder');
    }
    protected function execute(InputInterface $input, OutputInterface $output): int
    {
        $this->logger->info('logging test');
        return Command::SUCCESS;
    }   
}
  • 配置Monolog给自定义日志频道添加文件写入能力,打开config/packages/monolog.yaml修改配置:
monolog:
    # 确保已经声明自定义的subscription频道
    channels:
        - subscription
    handlers:
        # 新增subscription频道的文件日志handler
        subscription_file:
            type: stream
            level: info # 记录info及以上所有级别的日志
            path: "%kernel.logs_dir%/%kernel.environment%.subscription.log" # 使用框架内置变量拼绝对路径,避免相对路径偏移问题
            channels: ["subscription"]
        # 可选:如果需要CLI下info级别日志也输出到终端,添加控制台handler
        subscription_console:
            type: console
            level: info
            channels: ["subscription"]
        # 原有默认handlers配置保留即可
  • 调整cron执行配置,规避环境差异问题:

    • 用which php查询php的绝对安装路径(通常为/usr/bin/php)
    • 执行命令前先切换到项目根目录,避免相对路径解析错误
    • 调整后的crontab配置参考:
    * * * * * root cd /var/app/current && /usr/bin/php bin/console app:still_subscriber_reminder
    
    • 给日志目录开放对应权限,确保执行用户可写:
    chmod -R 755 /var/app/current/var/log/
    chown -R root:root /var/app/current/var/log/
    
  • 清除项目缓存生效配置:

php /var/app/current/bin/console cache:clear

完成以上操作后,手动执行命令、cron定时执行命令都会正常把info及以上级别的日志写入指定的日志文件。

内容的提问来源于stack exchange,提问作者And Row ID

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.28 13:54:25