Python重写print实现输出带时间截的日志log文件




import os,sys,time,io
import builtins as __builtin__
#下以内容放在所有代码之前
def print(*args, **kwargs):
    # __builtin__.print('New print function')
    return __builtin__.print(time.strftime("%Y-%m-%d %H:%M:%S -----  ", time.localtime()) ,*args, **kwargs)
class Logger(object):
    def __init__(self, filename="Default.log", path="./"):
        sys.stdout = io.TextIOWrapper(sys.stdout.buffer, encoding='utf-8')
        self.terminal = sys.stdout
        self.log = open(os.path.join(path, filename), "a", encoding='utf8')

    def write(self, message):
        self.terminal.write(message)
        self.log.write(message)

    def flush(self):
        pass
sys.stdout = Logger('tmp.log', path="")
print("我要写在日志里,还要加上时间截,哈哈哈")

 

上一篇:2021-11-05


下一篇:多层嵌套对象得取值和赋值问题