1. logging模块
def log():
logger = logging.getLogger()
logger.setLevel(logging.INFO)
fmt = logging.Formatter('%(asctime)s - %(filename)s[line: %(lineno)d] - %(levelname)s: %(message)s')
fh = logging.FileHandler(filename=test_para.abs_path + 'b_report/log.txt', mode='a', encoding='utf-8')
fh.setFormatter(fmt)
logger.addHandler(fh)
return logger
调用:
#第一种:直接掉方法
log().info('aaabbb')
# 第二种:通过方法返回的logger,通过logger调用info()方法
logger = log()
logger.info('cccddd')
文件中显示:2023-11-29 11:00:16,756 - log.py[line: 107] - INFO: aaabbb
文件中显示:2023-11-29 11:00:16,756 - log.py[line: 107] - INFO: cccddd
2. 自定义存储log的方法,写入StringIO内容中,然后再写入到log文件中
from io import StringIO
# log file
filename = test_para.abs_path + "c_log/new_log.log"
# StringIO变量
string_io = StringIO()
# use the self-defined log function
def log_record(message):
str_message = str(datetime.now()) + " " + str(message) + '\n'
global string_io
global count_num
# count the amount of calling the method
count_num = count_num + 1
string_io.write(str_message)
string_io.flush()
# write the recorded log into log file
def log_write(message_string_io):
message_string_io.seek(0, 0)
for i in message_string_io.readlines():
with open(filename, 'a', encoding='utf-8') as f:
f.write(i)
f.flush()
调用:
log_record('aaabbb')
log_record('cccddd')
log_write(string_io) # 一次性将内存中的StringIO内容写入到log文档
文件中显示:
文件中显示:2023-11-29 11:00:16,756 - log.py[line: 107] - INFO: aaabbb
文件中显示:2023-11-29 11:00:16,756 - log.py[line: 107] - INFO: cccddd
3. 自定义存储log方法,最简单的直接将log写入到log文档
from datetime import datetime
# log file
filename = test_para.abs_path + "c_log/new_log.log"
# use the self-defined log function
def log_record(message):
str_message = str(datetime.now()) + " " + str(message) + '\n'
with open(filename, mode='a', encoding='utf-8') as f:
print(str_message)
f.write(str_message)
f.flush()
调用:
log_record('aaabbb')
文件中显示:2023-11-29 11:00:16,756 - log.py[line: 107] - INFO: aaabbb