在日志文件python 3.6.4中添加计数

时间:2018-03-15 08:26:06

标签: python python-3.x logging logfiles

我正在编写一个日志文件(第一次仍然是整个编程的新手),我希望让日志文件写入插入到mysql数据库和消息中的记录数。 例如。 2018-03-15 09:09:59 - 30 records entered in the database 我有两个函数,一个是对日志文件的实际写入函数,另一个是在输入记录后发送消息。

写入日志功能

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

执行查询功能

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

然后我在另一个脚本中调用这些函数。这一切都很好但很明显,计数和信息都没有像我希望的那样写成2018-03-15 09:09:59 - 30 records entered in the database

我已将count变量拆分,然后将消息拆分为:

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

但由于显而易见的原因,这并没有产生正确的输出。我很感激帮助。谢谢。

1 个答案:

答案 0 :(得分:0)

使用string format

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