Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/312.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
为python日志添加文件格式化程序_Python - Fatal编程技术网

为python日志添加文件格式化程序

为python日志添加文件格式化程序,python,Python,我有以下代码要写入文件: 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') 这将把单词hello写入file.txt文件。但是,我想将其格式化,因此将其写入文件,如下所示: 'format': '[%(ascti

我有以下代码要写入文件:

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')
这将把单词hello写入file.txt文件。但是,我想将其格式化,因此将其写入文件,如下所示:

'format': '[%(asctime)s] %(filename)s:%(lineno)d@%(funcName)s [%(levelname)s] %(message)s'
如何添加此格式,使其以这种方式写入文件?

您可以向其添加格式化程序,使其如下所示:

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')
更多信息可在此处找到: