Reputation: 2412
I have a python function which prints some lines on terminal.
Here is how I execute the function:
python3 test.py
Here is some code from the file:
column1 = "|=========="
column2 = "|==============================================================="
column3 = "|==================================="
column4 = "|======================="
print("\n"+column1+column2+column3+column4+"|")
print("|SCRIPT ID |SCRIPT NAME |Start Time |RUN ID |")
print(column1+column2+column3+column4+"|")
It prints the following in terminal:
|==========|===============================================================|===================================|=======================|
|SCRIPT ID |SCRIPT NAME |Start Time | RUN ID |
|==========|===============================================================|===================================|=======================|
|1 |TEST_SCRIPT |2020-04-17 11:46:28.054074+05:30 |201 |
|==========|===============================================================|===================================|=======================|
Entering - SCRIPT
Verification Started
Verification Completed in 0 Hours 00 Min 00.000602 sec
Methods Execution Started
Methods Execution Completed
EXITING - SCRIPT
I want to maintain the output of the function in a log file. So, if I run python3 test.py
, it should create a file called test.py-202004171148.log
in a folder called as logs
storing all the output in the file.
How can I do this?
Upvotes: 4
Views: 1078
Reputation: 581
Adding these few lines of code to the top of your script should redirect all output to be printed to console AND ALSO written to a file
import sys
import datetime
class Printer(object):
def __init__(self, *files):
self.files = files
def write(self, obj):
for file in self.files:
file.write(obj)
file.flush()
def flush(self):
for file in self.files:
file.flush()
f = open(f"{__file__}-{datetime.datetime.now().strftime('%Y%m%d%H%M%S')}.log", 'w')
sys.stdout = Printer(sys.stdout, f)
#Your print statements below
print("Hello world!")
Upvotes: 1
Reputation: 41
save file with datetime:
import datetime
file = open(str(datetime.now().strftime('test.py-%Y%m%d%H%M%S.log')), "w")
file.write("yourlogs")
file.close()
Upvotes: 3
Reputation: 400
to saving file you can use:
import datetime
file = open("test.py-"+str(datetime.datetime.now().timestamp())+".log", "w")
file.write("yourlogs")
file.close()
Upvotes: 1
Reputation: 34704
You can use the logging module for that. You will have to replace print()
with logging.info()
, logging.warning()
, or logging.error()
depending on your desired log level.
import logging
from datetime import datetime
fn = datetime.now().strftime('logs/test.py-%Y%m%d%H%M%S.log')
logging.basicConfig(filename=fn, level=logging.INFO)
logging.info('Entering - SCRIPT')
logging.info('etc...')
The default format will prefix every message with the log level and logger name. If you don't want that, you can override it with format
.
logging.basicConfig(filename=fn, level=logging.INFO, format='%(message)s')
Upvotes: 0