Created
June 10, 2022 07:44
-
-
Save XDo0/205313386afbeb44d9dbaad346602370 to your computer and use it in GitHub Desktop.
python console2log
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import sys | |
import os | |
import time | |
# 控制台输出记录到文件 | |
class Logger(object): | |
def __init__(self, file_name="Default.log", stream=sys.stdout): | |
self.terminal = stream | |
self.log = open(file_name, "a") | |
def write(self, message): | |
self.terminal.write(message) | |
self.log.write(message) | |
def flush(self): | |
pass | |
if __name__ == '__main__': | |
# 自定义目录存放日志文件 | |
log_path = './Logs/' | |
if not os.path.exists(log_path): | |
os.makedirs(log_path) | |
# 日志文件名按照程序运行时间设置 | |
log_file_name = log_path + 'log-' + time.strftime("%Y%m%d-%H%M%S", time.localtime()) + '.log' | |
# 记录正常的 print 信息 | |
sys.stdout = Logger(log_file_name) | |
# 记录 traceback 异常信息 | |
sys.stderr = Logger(log_file_name) | |
print(5555) | |
print(2/0) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment