user10332687
user10332687

Reputation:

Adding a file formatter for python logging

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?

Upvotes: 0

Views: 326

Answers (1)

user10332687
user10332687

Reputation:

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/

Upvotes: 1

Related Questions