symfony 2.3.40 通过 config.yml 配置 monolog 的 handler(如 stream、console、fingers_crossed)和 formatter(需手动注册 jsonformatter 服务),支持多 handler 并行、自定义 abstractprocessinghandler 拦截日志,以及按 channel 隔离业务日志。

直接修改 config.yml 配置 handler 输出目标
在 app/config/config.yml 中,可通过 monolog 配置块指定日志写入位置和格式基础:
- 用
type: stream写入文件(最常用),例如:path: "%kernel.logs_dir%/custom.log" - 用
type: console在命令行显示(开发调试用) - 用
type: fingers_crossed实现“仅错误时才落盘”,减少 I/O 开销 - 支持多个 handler 并行,比如同时写文件 + 发 Slack(需自定义 handler)
指定 Formatter 实现结构化输出(如 JSON)
Symfony 2.3.40 的 Monolog 默认用 LineFormatter,输出类似:[2026-10-20 13:24:00] app.DEBUG: hello world [] []
要改成 JSON 格式,需手动注册一个 JsonFormatter 服务,并在 handler 中引用:
- 在 app/config/config.yml 的
monolog下为某个 handler 添加:formatter: monolog.formatter.json - 在 app/config/services.yml 中注册 formatter 服务:
class: Monolog\Formatter\JsonFormatter
arguments: [true]
第二个参数 true 表示启用“将上下文和额外字段扁平化”,更适合解析。
自定义 Handler 拦截日志数据(不落盘,供程序处理)
如果目标不是写文件,而是想在运行时拿到每条日志的数组(比如做审计、触发告警),就要写一个继承 Monolog\Handler\AbstractProcessingHandler 的类:
- 重写
write()方法,把$record(已含 message/context/level/channel/datetime)存入静态数组或注入的服务中 - 在 services.yml 中声明该 handler,并加标签
monolog.handler - 在 config.yml 的 monolog 配置里启用它,注意设置
channels和level,避免干扰主日志流
使用独立 logger 通道隔离业务日志
避免所有日志混在一起,可为支付、API、爬虫等模块创建专用 channel:
- 在 config.yml 中添加新 handler,指定
channels: [payment] - 在代码中获取对应 logger:
$logger = $this->get('logger')->withContext(['channel' => 'payment']);
或更规范地:用$this->get('monolog.logger.payment')(需先在 services.yml 中定义该 service) - 这样就能把支付相关日志单独输出到
payment.log,排查问题时更聚焦











