代码如下
import sys
from os import mkdir
from os. path import ( abspath, dirname, join, isdir)
from datetime import date
from time import localtime
def defaultfilename ( ) :
"""设置默认日志目录"""
dir_log = 'logfile'
filename = date. strftime( date. today( ) , '%Y-%m-%d' ) + '.log'
path = abspath( __file__)
dir = join( dirname( path) , dir_log)
if not isdir( dir ) : mkdir( dir )
return join( dir , filename)
class Logger ( object ) :
def __init__ ( self, filename= defaultfilename( ) , stream= sys. stdout) :
"""
初始化参数并打开日志文件
:param filename:
:param stream:
"""
self. terminal = stream
self. log = open ( filename, 'a+' , encoding= 'utf-8' )
self. time = None
def write ( self, message) :
"""
写日志
:param message: str
:return:
"""
self. gettime( )
self. terminal. write( self. time + ' >> ' + message)
self. terminal. write( '\n' )
self. log. write( self. time + ' >> ' + message)
self. log. write( '\n' )
def gettime ( self) :
"""
输出时间格式化
:return:
"""
tm = localtime( )
self. time = ':' . join(
[ str ( tm. tm_hour) . rjust( 2 , '0' ) , str ( tm. tm_min) . rjust( 2 , '0' ) , str ( tm. tm_sec) . rjust( 2 , '0' ) ] )
if __name__ == '__main__' :
log = Logger( )
log. write( 'Hello world' )
运行结果
D: \Python\Python310\python. exe E: / DataAnalysis/ CustomClassLibrary/ CCLLogger. py
11 : 05 : 20 >> Hello world
11 : 05 : 20 >> First log
Process finished with exit code 0