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

Airflow日志优化诉求:分割大日志文件+实时查看运行中日志

Airflow服务器端日志优化方案

日志存储路径说明

Airflow日志的标准存储路径格式为:

base_log_folder/dag_id/task_id/date_time/1.log

实际示例路径:

base_log_folder/dag_id={dag_id}/run_id={run_id}/task_id={task_id}/attempt={try_number}.log

现存问题

  • 大体积日志无法通过Web UI查看:Chrome无法处理过大的日志文件,导致Airflow Web UI无法加载完整日志
  • 任务运行时服务器端无法实时查看日志:{try_number}.log仅在任务完成后才会生成,虽然Web UI能实时展示日志,但对应服务器目录中无实时日志文件

需求

  • 将大型日志自动分割为多个小文件,格式示例:
    {try_number}_1.log
    {try_number}_2.log
    {try_number}_3.log
    ...
    
  • 任务运行时可在服务器端实时查看日志文件

一、实现日志自动分割

通过自定义Airflow日志配置,使用RotatingFileHandler实现按文件大小分割日志:

  1. 编辑Airflow配置文件airflow.cfg,在[logging]段修改日志配置类路径:
    logging_config_class = custom_logging.LOGGING_CONFIG
    
  2. 创建自定义日志配置文件custom_logging.py(可放在Airflow可导入的路径下,比如$AIRFLOW_HOME/dags/目录):
    import logging
    from logging.handlers import RotatingFileHandler
    from airflow.config_templates.airflow_local_settings import DEFAULT_LOGGING_CONFIG
    
    LOGGING_CONFIG = DEFAULT_LOGGING_CONFIG.copy()
    
    # 替换默认FileHandler为RotatingFileHandler
    for handler_name, handler in LOGGING_CONFIG['handlers'].items():
        if handler.get('class') == 'logging.FileHandler':
            handler['class'] = 'logging.handlers.RotatingFileHandler'
            # 设置单日志文件最大容量(示例:50MB)
            handler['maxBytes'] = 50 * 1024 * 1024
            # 设置保留的日志文件最大数量
            handler['backupCount'] = 10
            # 修改文件名模板,添加序号后缀
            handler['filename'] = handler['filename'].replace('.log', '_%(index)d.log')
    
  3. 重启Airflow所有服务(webserver、scheduler、worker),配置即可生效。后续日志文件达到设定大小后,会自动分割为带序号的小文件。

二、实现服务器端实时查看日志

Airflow默认会缓冲日志到内存,任务完成后才写入文件。修改配置关闭缓冲,即可实现实时写入:

  1. 在上述custom_logging.py中,给日志处理器添加实时刷新配置:
    for handler_name, handler in LOGGING_CONFIG['handlers'].items():
        if handler.get('class') in ['logging.FileHandler', 'logging.handlers.RotatingFileHandler']:
            # 关闭文件缓冲,写入即刷新
            handler['buffering'] = 1
            # 设置触发刷新的日志级别(INFO及以上均实时刷新)
            handler['flushLevel'] = logging.INFO
    
  2. 检查airflow.cfg中的task_log_reader配置,确保设置为file:
    task_log_reader = file
    
  3. 重启Airflow服务后,任务运行时日志会实时写入对应目录的日志文件,可直接在服务器上使用tail -f {log_file_path}命令实时查看。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.08 10:50:17