python日志(Logger)的输出

方法一:

import sys

class Logger(object):
    def __init__(self, filename='default.log', stream=sys.stdout):
        self.terminal = stream
        self.log = open(filename, 'a')  # add content

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

    def flush(self):
        pass


# now it works
sys.stdout = Logger('a.txt', sys.stdout)

print('print something')

import time
for i in range(10):
    now = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(time.time()))  # get time
    print("now-->", now)  # 将会输出到控制台,且同时输出到日志文件中去 
    time.sleep(1)  # 间隔1秒输出

说明:

方法二:

mylog = open('a.txt', mode='a', encoding='utf-8')  # 设置输出的文件及设置

print("now we will start!!!")  # 输出到控制台
print("now we will start!!!", file=mylog)  # 输出到日志文件中去

import time
for i in range(10):
    now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    print("now --> {} \n".format(now), file=mylog)
    time.sleep(1)
    print(time.time())

mylog.close()  # 关闭日志流

或者这样写(全部只输出到log文件中去)


sys.stdout = open('a.txt', mode='a', encoding='utf-8')  # 设置输出的文件及设置

print("now we will start!!!")  # 输出到日志文件中去

import time
for i in range(10):
    now = time.strftime('%Y%m%d_%H%M%S', time.localtime(time.time()))
    print("now --> {} \n".format(now))
    time.sleep(1)
    print(time.time())

方法3:

在终端执行,如:python your_program.py > logger.txt

©️2020 CSDN 皮肤主题: 技术黑板 设计师:CSDN官方博客 返回首页