0

I have the following code to write to a file:

import logging
log=logging.getLogger('avails')
log_file = 'file.txt'
fh = logging.FileHandler(log_file)
fh.setLevel(logging.INFO)
log.addHandler(fh)

log.info('hello')

This will write the word "hello" to the file file.txt. However, I would like to format this, so it is written to the file as follows:

'format': '[%(asctime)s] %(filename)s:%(lineno)d@%(funcName)s [%(levelname)s] %(message)s'

How would I add this format in so it writes that way to the file?

1 Answer 1

1

You can add a formatter to it so it would be like this:

import logging
log=logging.getLogger('avails')
log_file = 'file.txt'
fh = logging.FileHandler(log_file)
fh.setLevel(logging.INFO)

# Add Formatting
formatter = logging.Formatter('[%(asctime)s] %(filename)s:%(lineno)d@%(funcName)s [%(levelname)s] %(message)s')
fh.setFormatter(formatter)

log.addHandler(fh)
log.info('hello')

More information can be found here: https://docs.python-guide.org/writing/logging/

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.