python logging and self-define log

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值