This is an archived version of the course. Please find the latest version of the course on the main webpage.

Chapter 3: Using decorators

Example - Logger

face Josiah Wang

Let us look at some example applications of decorators.

The example below creates a @logger decorator that you can wrap around any function to print out the execution status of the function to a file. If you run the code below, you should get a file called "add.log" that prints out the two lines that indicate that the add function has been called.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
def logger(filename="log.txt"):
    def logger_decorator(func):
        def wrapper(*args, **kwargs):
            with open(filename, "a") as logfile:
                logfile.write(f"Calling {func.__name__}\n")
                func(*args, **kwargs)
                logfile.write(f"{func.__name__} returned\n")
        return wrapper

    return logger_decorator


@logger(filename="add.log")
def add():
    pass


add()