[PYTHON] Notify the contents of the task before and after executing the task in Fabric

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.

Screen Shot 2017-01-19 at 01.21.02.png

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

Notify the contents of the task before and after executing the task in Fabric
[python] plot the values ​​before and after the conversion of yeojohnson conversion
Change the color of Fabric errors and warnings
Fill the missing value (null) of DataFrame with the values before and after with pyspark
Not being aware of the contents of the data in python
[Super easy! ] How to display the contents of dictionaries and lists including Japanese in Python
Define a task to set the fabric env in YAML
Remove double-byte spaces before and after the character string (python)
[Tips] Problems and solutions in the development of python + kivy
Simulation of the contents of the wallet
Get information from the Japan Meteorological Agency and notify Slack of weather warnings in the 23 wards of Tokyo
Process the contents of the file in order with a shell script
Count the number of Thai and Arabic characters well in Python
[EC2] How to install chrome and the contents of each command
Output the contents of ~ .xlsx in the folder to HTML with Python
Probability of getting the highest and lowest turnip prices in Atsumori
[TensorFlow 2] How to check the contents of Tensor in graph mode
Create a function to get the contents of the database in Go
Verify the compression rate and time of PIXZ used in practice
Get the title and delivery date of Yahoo! News in Python
I tried to take the difference of Config before and after work with pyATS / Genie self-made script
If you want to switch the execution user in the middle of a Fabric task, settings context manager
How to copy and paste the contents of a sheet in Google Spreadsheet in JSON format (using Google Colab)
The story of Python and the story of NaN
The story of participating in AtCoder
Understand the contents of sklearn's pipeline
See the contents of Kumantic Segumantion
The story of the "hole" in the file
The meaning of ".object" in Django
Explanation and implementation of the XMPP protocol used in Slack, HipChat, and IRC
Graph of the history of the number of layers of deep learning and the change in accuracy
Predict the amount of electricity used in 2 days and publish it in CSV
Comparing the basic grammar of Python and Go in an easy-to-understand manner
Change the saturation and brightness of color specifications like # ff000 in python 2.5
How to compare if the contents of the objects in scipy.sparse.csr_matrix are the same
Look up the names and data of free variables in function objects
Open an Excel file in Python and color the map of Japan
Notify the chat of new articles of Qiita Organization and improve the learning efficiency of the organization!