0

can logging outputs which appear on the terminal be redirected to a text file? I have tried

                z = open('/mnt/sdc1/Ryan/Marx/newfile.txt'.format(file), 'w')
                sys.stdout= sys.stderr = z
                print ('Running the Algoritm Now for case {}'.format(file))
                run_liver_mpct_algorithms(data_paths, model_paths,[0], int(data_paths['batch_size']), data_paths['task_str']))
                z.close()

In th file z This gives me only the traceback of the error and print statements ,inside of the run_liver_mpct_algorithms there are many logging outputs which i would also like to go in the file.

Any ideas would be helpful,Thanks !

1 Answers1

2

Why not use the logging module from the standard library? Here's a simple example:

import logging
log_file = 'my_log_file.log'
log_fh = logging.FileHandler(log_file)
log_sh = logging.StreamHandler(sys.stdout)
log_format = '%(asctime)s %(levelname)s: %(message)s'
# Possible levels: DEBUG, INFO, WARNING, ERROR, CRITICAL    
log_level = 'INFO' 
logging.basicConfig(format=log_format, level=log_level, 
    handlers=[log_sh, log_fh])

You create logging messages like this:

logging.info('This is a log message on level INFO')
logging.warning('This is a log message on level WARNING')

Messages will be written to the console and to the file you specified.

uwain12345
  • 356
  • 2
  • 21