pythonpython-3.xlogginglogfiles

add count in log file python 3.6.4


I am working on writing a log file (first time still new to programming as a whole) and I want to have the log file write the number of records inserted into a mysql database and a message. eg. 2018-03-15 09:09:59 - 30 records entered in the database I have two functions, one is the actual write function to the log file and the other is to send the message once the records have been entered.

write to log function

def write_log():
logger = logging.getLogger()
logger.setLevel(logging.DEBUG)

hf = logging.FileHandler(os.path.join(logdir, logfile), 'a')
hf.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s')
hf.setFormatter(formatter)
logger.addHandler(hf)
return True

executes query function

def execute(con):
sql = "INSERT INTO `table`(`value`, `value`, `value`)
    cursor = con.cursor()
try:
    cursor.execute(sql)
    con.commit()
    logging.info(count + 'records entered in the database.') # Obviously this is where I'm wrong.

except pyodbc.Error:
    con.rollback()
    logging.error('Could not enter records into the database.')


cursor.close()
con.close()
return True

and then I call the functions in another script. It all works fine but clearly the count and messages aren't being written the way I want them to be like this 2018-03-15 09:09:59 - 30 records entered in the database

I have split the count variable and then the message like this:

logging.info(count)
logging.info('records entered in the database.')

but that doesn't produce the right output for obvious reasons. I appreciate the help. Thank you.


Solution

  • Use string format:

    logging.info('{0} records entered in the database.'.format(count))