Reputation: 2243
Let's say I have a script script.py
that looks like this:
# script.py
import logging
logging.basicConfig(
filename='log.log',
filemode='w', # new log everytime
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
)
logging.logging('Sample log')
What I want to see in log.log
is:
2020/03/18 09:23:00 PM Sample log
# yes this is a new line
'''
import logging
logging.basicConfig(
filename='log.log',
filemode='w', # new log everytime
format='%(asctime)s %(message)s',
datefmt='%m/%d/%Y %I:%M:%S %p',
)
logging.logging('Sample log')
'''
So I have the actual log, and at the end of it, the contents of the script that was run. Is this possible?
Upvotes: 0
Views: 67
Reputation: 151
Use the atexit
module and at the end of your program, open the current file and write its contents into the logger.
To get the current filename, you can run
import pathlib
this_file = __file__
and then open the file and read it into a string
with open(this_file, 'r') as file:
data = file.read()
and finally,
logging.info("\n'''{}\n'''".format(data))
So your whole code could be
import atexit
def log_script_contents(filepath):
import logging
with open(filepath, 'r') as file:
data = file.read()
logging.info("\n'''{}\n'''".format(data))
this_file = __file__
atexit.register(log_script_contents, this_file)
Upvotes: 1