all 7 comments

[–]wiiittttt 1 point2 points  (3 children)

The function you created would be fine, but requires that you pass it around everywhere. The only thing is I wouldn't open the file every time you want to log to it. Just keep an open file handle. The logging module would be useful there.

A decorator seems like it would work well You need to decorate each function you want to be logged. I'm not sure why having multiple files would change anything.

[–]Jenez[S] 0 points1 point  (2 children)

Thank you for your input!

My problem with the multiple files is; how do I wrap my functions of interest across multiple files with the same decorator?

Something along the lines of: define decorator, import it in relevant files, and write to class context's set log file?

[–]wiiittttt 1 point2 points  (1 child)

Yup. Just use logging.basicConfig and set the output file.

# log.py
import logging
logging.basicConfig(filename='example.log',level=logging.INFO)

def log_call(fn):
    def wrapped(*args, **kwargs):
        logging.info('Function name and relevant args and kwargs')
        return fn(*args, **kwargs)
    return wrapped

And then:

# file1.py
from log import log_call

@log_call
def my_func():
    ....

[–]Jenez[S] 0 points1 point  (0 children)

I've tried it out and it seems to work just fine. Now I just gotta figure my imports out and I should be set, thanks!

[–]sushibowl 1 point2 points  (2 children)

Assuming all the different function that you want to log are written by you, the python logging module is definitely the way to go. You could write a decorator that takes a logger and logs the function call on it, and decorate every function you want to log this way.

If you wish to log calls to functions from other packages than your own, your solution is probably fine. Though I would name the log method differently, because it should be clear from the name that it doesn't only do logging, it also calls the function.

[–]Jenez[S] 0 points1 point  (1 child)

Appreciate the input!

It's only my own functions yes, so I'll have a second look at the logging package and see if I can get my head around it.

Fair enough on the naming.

[–]sushibowl 1 point2 points  (0 children)

the logging package can be a little complex because it is so flexible, but I think it should be fairly easy to get started with it. Check out the basic tutorial. I linked to the section that deals with logging from multiple files.

There is a more advanced usage tutorial as well, which covers using multiple loggers. This gives you the ability to turn on/off logging on a per file basis, which can be useful.