1

I am currently running a python script in a batch file. In the python, I have some print function to monitor the running code. The printed information then will be shown in the command window. In the meantime, I also want to save all these print-out text to a log-file, so I can track them in the long run.

Currently, to do this, I need to have both print function in the python and use the text.write function to write to a text file. This causes some troubles in maintenance because every time I change some printing text, I also need to change the text in the write function. Also I feel it is not the most efficient way to do that.

For example:

start_time = datetime.now()
print("This code is run at " + str(start_time) + "\n")
log_file.write("This code is run at " + str(start_time) + "\n")

I would like to use the print function in the python, so I can see that in the command window and then save all the print-out information to a log file at one time.

HoldOffHunger
  • 18,769
  • 10
  • 104
  • 133
Shenan
  • 338
  • 1
  • 6

2 Answers2

2

For a better solution in the long run, consider the built in logging module. You can give multiple destinations, such as stdout and files, log rotation, formatting, and importance levels.

Example:

import logging
logging.basicConfig(filename='log_file', filemode='w', level=logging.DEBUG)

logging.info("This code is run at %", start_time)
Brian
  • 628
  • 6
  • 13
  • Thank you for the suggestion, but I am not familiar with logging package. I have tried the code and it outputs too many info. Since my current project is a small program I am afraid this might be an overkill. – Shenan Aug 08 '19 at 19:14
0

Just make a function

def print_and_log(text):
    print(text)
    with open("logfile.txt", "a") as logfile:
        logfile.write(text+"\n")

Then wherever you need to print, use this function and it will also log.

whackamadoodle3000
  • 6,684
  • 4
  • 27
  • 44