DEV Community

Cover image for Day 16 - Log execution time with oneliner - 100 days 100 python scripts
Ganesh Raja
Ganesh Raja

Posted on

Day 16 - Log execution time with oneliner - 100 days 100 python scripts

Day 16: exection_time_log_decorator

This is a decorator script in Python, When you use @log as a decorator for the function it can automatically log the function name and the execution time it took.

import logging
import functools,time
from os.path import expanduser,join

def log(fun):
    functools.wraps(fun)
    def wrapper(*args,**kwargs):
        logger=logging.getLogger("execution_time_log")
        if not logger.hasHandlers():
            logger.setLevel(logging.INFO)
            filehandler=logging.FileHandler(join(expanduser("~"),"execution_time.log"))
            formatter=logging.Formatter('%(asctime)s - %(function_name)s - %(exec_time)f')
            filehandler.setFormatter(formatter)
            logger.addHandler(filehandler)
        start_time=time.time()
        called_return=fun(*args,**kwargs)
        end_time=time.time()
        logger.info(None,extra={'exec_time':end_time-start_time,'function_name':fun.__name__})
        return called_return
    return wrapper


# Examples

@log
def test1():
    time.sleep(10)

@log
def test2():
    time.sleep(20)
@log
def test3():
    time.sleep(15)


test1()
test2()
test3()

Enter fullscreen mode Exit fullscreen mode

Please Visit my Git Repo to check out all the previous day challenges.

https://github.com/ganeshraja10/automated-python-scripts

OutPut

Output

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

Top comments (0)

Image of Docusign

🛠️ Bring your solution into Docusign. Reach over 1.6M customers.

Docusign is now extensible. Overcome challenges with disconnected products and inaccessible data by bringing your solutions into Docusign and publishing to 1.6M customers in the App Center.

Learn more