Since I was using Fabric and had a lot of tasks for my own purposes, I wanted to output what tasks were performed and what tasks were performed before and after the tasks were executed, so I created a CustomTask class.
report.py
# -*- coding: utf-8 -*-
import logging
import time
from fabric.tasks import Task
from fabric.operations import *
from fabric.colors import *
class ReportStatus(Task):
"""
CustomTask class that tells you that the task is about to be executed and that it has been executed before and after the task is executed.
@task(task_class=ReportStatus, task_name="Display test before and after execution")
def something_task():
print green("Task execution")
"""
def __init__(self, func, task_name, *args, **kwargs):
super(ReportStatus, self).__init__(*args, **kwargs)
self.func = func
self.task_name = task_name
if hasattr(func, '__doc__') and func.__doc__:
self.__doc__ = func.__doc__
else:
self.__doc__ = task_name
if hasattr(callable, '__module__'):
self.__module__ = callable.__module__
def run(self, *args, **kwargs):
print cyan("[%s] [%s]To run" % (self.task_name, self.func.__name__))
logging.info("[%s][%s] executing" % (self.func.__name__, self.task_name))
result = self.func(*args, **kwargs)
print green("[%s] [%s]Completed" % (self.task_name, self.func.__name__), bold=True)
logging.info("[%s][%s] done" % (self.func.__name__, self.task_name))
print "\n"
return result
def __call__(self, *args, **kwargs):
return self.run(*args, **kwargs)
def __getattr__(self, k):
return getattr(self.func, k)
def __details__(self):
return get_task_details(self.func)
Since logging is also used to spit out log, if you set it appropriately, it will also output the log.
fabfile.py
# -*- coding: utf-8 -*-
import datetime
import logging
from fabric.colors import *
from fabric.api import *
from report import ReportStatus
log_file_name = "%s.log" % (datetime.datetime.today().strftime("%Y%m%d"))
logging.basicConfig(
format='[%(asctime)s][%(levelname)s] %(message)s',
filename=log_file_name, datefmt='%Y/%m/%d %I:%M:%S',
level=logging.INFO
)
@task(task_class=ReportStatus, task_name="Display test before and after execution")
def something_task():
print green("Task execution")
When executed, it looks like this.
log is output in the specified format
[2017/01/19 01:20:18][INFO] [something_task][Display test before and after execution] executing
[2017/01/19 01:20:18][INFO] [something_task][Display test before and after execution] done
Recommended Posts