Celery的日志配置及日志按天切分
一. Celery定时任务启动
- Celery定时任务的启动是通过命令启动的,可以通过-f logfilename或–logfile=logfilename指定日志保存的文件名,可以通过-loglevel=level 指定日志的等级(info,warning,error,critical…)
- 如果不指定日志文件,则celery会根据进程自动在项目启动的目录下自动生成日志文件,这是celery的默认日志文件
如:work.log,work-1.log,work-2.log
二. celery日志配置
- python进行日志管理的模块为logging,celery的日志也是用logging实现的,如果我们要将需要的内容写到日志文件中,也是使用logging实现,代码目录结构
# 目录结构
- celery_crontab
- config.py
- main.py
- tasks.py
- 同时,为了实现celery的日志按天切分,需要使用logging模块及logging.handlers中的TimedRotatingFileHandler来设置日志切分的相关配置,在celery定时任务的config.py中设置日志相关配置
from celery import Celery
from kombu import Exchange, Queue
import logging
from logging.handlers import TimedRotatingFileHandler
# celery
app = Celery('demo', broker='amqp://guest@localhost:5672//')
# Queue
queue = (
# 定义专用的queue,定义Exchange,以及与route对应的key
Queue('queue_demo', Exchange('exchange_demo', type='direct'),
routing_key='queue_demo_key'),
)
# Route
route = {
# 定义任务crontab_func1的queue,routing_key
'tasks.crontab_func1': {'queue': 'queue_demo', 'routing_key': 'queue_demo_key'},
'tasks.crontab_func2': {'queue': 'queue_demo', 'routing_key': 'queue_demo_key'},
}
# 指定queue和route的配置应用到celery定时任务的配置中,设置时区
app.conf.update(CELERY_QUEUES=queue, CELERY_ROUTES=route, CELERY_TIMEZONE='Asia/Shanghai', CELERY_ENABLE_UTC=False)
class Config(object):
# 设置日志
log_fmt = '%(asctime)s\tFile \"%(filename)s\",line %(lineno)s\t%(levelname)s: %(message)s'
# log_file_handler = TimedRotatingFileHandler(filename="log", when="MIDNIGHT", interval=1, backupCount=30)
log_file_handler = TimedRotatingFileHandler(filename="log", when="M", interval=1, backupCount=7)
formatter = logging.Formatter(log_fmt)
log_file_handler.setFormatter(formatter)
logging.basicConfig(format=log_fmt)
LOGGER = logging.getLogger()
LOGGER.setLevel(logging.INFO)
LOGGER.addHandler(log_file_handler)
- 在tasks.py的任务函数中设置自己需要的日志内容
from config import app, Config
config_obj = Config()
@app.task
def crontab_func1():
print('在此编写任务要实现的代码')
config_obj.LOGGER.info('coding something')
@app.task
def crontab_func2():
print('在此调用实现了定时任务功能的函数或方法')
config_obj.LOGGER.info('coding something again')
- 在main.py中实现定时任务
from celery.schedules import crontab
from tasks import *
app.conf.update(
CELERYBEAT_SCHEDULE={
"crontab_func1": {
'task': 'tasks.crontab_func1',
'schedule': crontab(minute='*/1'),
'args': ()
},
"crontab_func2": {
'task': 'tasks.crontab_func2',
'schedule': crontab(minute='*/1'),
'args': ()
},
},
)
三、通过外部配置实现celery日志切分
- 设置好以上相关配置后,在main.py所在目录启动定时任务,发现日志写入到了文件中,但是并没有按我们想要的结果进行切分(直接在配置中使用日志,直接调用任务函数都可以实现切分,但是使用命令启动定时任务后不能完成切分)
# 启动命令
celery multi start demo_work -A main -Q queue_demo -l info -B --logfile=crontablog.log
原因是celery并没有帮我们实现切分日志的功能,以上TimedRotatingFileHandler的配置没有生效
- 所以要实日志切分,需要使用其他方法,将以上config.py中的TimedRotatingFileHandler设置生效
- 在/etc/logrotate.d/目录下创建日志外部切分的配置文件celery,通过外部方式对日志文件进行切分
# 指定被切分的日志文件所在的路径(即定时任务指定的日志的绝对路径)
/root/celery_logging/*.log{
# 按小时切分,也可以换成自己需要的,如:daily按天
hourly
missingok
# 保存的日志文件数量
rotate 7
compress
delaycompress
notifempty
# 设置切分日志
copytruncate
}
- 在celery定时任务的main.py所在目录执行启动命令重新启动定时任务,如果不指定日志文件,会在当前目录下生成默认日志文件如work.log,work-1.log,work-2.log
# 启动命令
celery multi start demo_work -A main -Q queue_demo -l info -B --logfile=crontablog.log
- 执行命令/usr/sbin/logrotate -f /etc/logrotate.conf,使刚才编写的配置文件/etc/logrotate.d/celery生效,此时即完成日志切分了,并且后续会按照设置的周期进行切分,按设置的数量保留日志文件的个数
注意:以上命令需要使用root权限执行,redhat或centos上使用su并输入密码切换到root,ubuntu上在命令前加上sudo并输入密码用root权限执行