keywords
- python 实现自己定制的print
- print 定制: print,同时存储log文件
0 引言
python有一个logging模块,支持存储文件,但是有时候集成logging,不免有点重,因此自己撸了一个定制的python print函数,支持:
- print输出到控制台
- 存储到log文件
- 可自行定制...
1 定制print
def my_print(*args):
'''
py2 & py3
'''
now = time.strftime("%Y%m%d %H%M%S", time.localtime())
msg = "[" + now + "]"
for val in args:
msg += str(val) + " "
print(msg)
with open("/tmp/log.txt", "a") as f:
f.write(msg)
f.write("\r\n")
对于日志文件输出,需要做精细化管理的,也可以自行实现
代码重构分割线
对于python3来说,除了上面代码,还有更加精辟的代码,但是,只支持python3
def my_print(*args):
# '''
# only py3
# '''
now = time.strftime("%Y%m%d %H%M%S", time.localtime())
print(*args)
print(now, *args, file=open("/tmp/log.txt", "a"))