Skip to main content
 首页 » 编程设计

python之将日志记录信息作为参数传递给函数

2025年04月02日8del

我使用一个使用 logging 模块的 Python 库。但是,我创建了自己的 log 函数供我的脚本在内部使用。

这是我想使用的日志记录功能:

def log(name, content, swtch : bool = None, time = None): 
    time = time or datetime.now(pytz.timezone('US/Pacific')) 
    if swtch == True or swtch == None: 
        toPrint = '{1.RED}{2}/{3}/{4} {5}:{6}:{7}:{8} {9} {0.BRIGHT}{1.GREEN}{10} {0.RESET_ALL}{11}{0.RESET_ALL}'.format( 
            Style, 
            Fore, 
            str(time.month).zfill(2), 
            str(time.day).zfill(2), 
            str(time.year)[2:], 
            str(time.hour % 12).zfill(2), 
            str(time.minute).zfill(2), 
            str(time.second).zfill(2), 
            str(int(time.microsecond / 1000)).zfill(3), 
            'AM' if time.hour < 12 else 'PM', 
            name, 
            content 
        ) 
 
        print(toPrint) 
 
    log_txt = '' 
 
    if swtch == False or swtch == None: 
        file = open('log.txt', 'r') 
        log_txt = file.read() 
        file.close() 
 
        with open('log.txt', 'w') as file: 
            text = '{0}/{1}/{2} {3}:{4}:{5}:{6} {7} {8} {9}'.format( 
                str(time.month).zfill(2), 
                str(time.day).zfill(2), 
                str(time.year)[2:], 
                str(time.hour % 12).zfill(2), 
                str(time.minute).zfill(2), 
                str(time.second).zfill(2), 
                str(int(time.microsecond / 1000)).zfill(3), 
                'AM' if time.hour < 12 else 'PM', 
                name, 
                content 
            ) 
            file.write(log_txt + text + '\n') 

让我们假设有一个名为 some_logger 的记录器。

import logging 
 
log = logging.getLogger('some_logger') 

有没有办法不打印到标准输出,而是将位置参数(代表日志信息)传递给另一个函数? (澄清一下:将使用所需参数调用 log 的函数)

请您参考如下方法:

我发现你可以使用类似 Handler 的东西反对这样做。您需要定义一个实现 emit 的子类.有关基本设置,请参见下面的示例:

import logging 
 
class CustomHandler(logging.Handler): 
    def emit(record): 
        log(record.levelname, record.msg) 
 
logging.getLogger('some_logger').addHandler(CustomHandler())