在日志文件中添加计数 python 3.6.4
add count in log file python 3.6.4
我正在写一个日志文件(第一次接触整个编程),我想让日志文件写入插入 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
我已经拆分了计数变量,然后是这样的消息:
logging.info(count)
logging.info('records entered in the database.')
但是由于显而易见的原因,这并没有产生正确的输出。感谢您的帮助。谢谢。
使用string format
:
logging.info('{0} records entered in the database.'.format(count))
我正在写一个日志文件(第一次接触整个编程),我想让日志文件写入插入 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
我已经拆分了计数变量,然后是这样的消息:
logging.info(count)
logging.info('records entered in the database.')
但是由于显而易见的原因,这并没有产生正确的输出。感谢您的帮助。谢谢。
使用string format
:
logging.info('{0} records entered in the database.'.format(count))