0

I am looking for the best way to log the content of a file when it is created. The process creates a file from some data, and I would like to log the content that has been written to the file.

I perform the following.

    with open(file_path, "a") as new_file:
        wr = csv.writer(new_file, delimiter=delimiter, quoting=csv.QUOTE_NONE,)
        wr.writerows(file_content)

The variable file_content is a list that is passed to this function.

What I am looking for is that with the logging module of Python, logging the content of the file. I want to avoid having to read the newly created file in read mode and read the contents. And I want the content of the log to be the plain text as it is written in the file.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
RodriKing
  • 822
  • 2
  • 10
  • 20
  • Could you get the data to be written to the file as a string (see https://stackoverflow.com/q/9157314/3001761), then use that to both log and write the file? – jonrsharpe Mar 12 '21 at 11:17
  • You could open two files in the same with block and write the content to both. `with open(new_file_path, "w") as new_file, open(log_file_path, "a") as log_file:` – Håken Lid Mar 12 '21 at 11:23

1 Answers1

0
import logging
import csv

logging.basicConfig(
    filename='history.log',
    level=logging.INFO,
    format='%(asctime)s %(levelname)-8s [%(filename)s:%(lineno)d:%(process)s] %(message)s',
    datefmt='%Y-%m-%d %H:%M:%S',
)

FILE_PATH = ''
CONTENT = ''

try:
    with open(FILE_PATH, "a") as writeFile:
        WR = csv.writer(
            writeFile,
            delimiter=delimiter,
            quoting=csv.QUOTE_NONE
        )
        WR.writerows(CONTENT)
        logging.info(
            'Status: Successful '
        )
except Exception as e:
    logging.error(
        'Error: {} '.format(e)
    )
finally:
    writeFile.close()