1.获取当前时间
import osfrom datetime import datetimeimport pytzdef get_cur_time():# 获取当前时间return datetime.strftime(datetime.now(pytz.timezone('Asia/Singapore')), '%Y-%m-%d_%H-%M-%S')# 基础目录basedir = 'a'logdir = os.path.join(basedir, 'logs', str('args.net'), get_cur_time())print(logdir)输出:
2.使用logging写入日志
import loggingshotdir='aa'logging.basicConfig(filename=shotdir + "/" + "snapshot.txt", level=logging.INFO,format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S')logging.info(str(args))logging.basicConfig(filename=shotdir + "/" + "snapshot.txt", level=logging.INFO, format='[%(asctime)s.%(msecs)03d] %(message)s', datefmt='%H:%M:%S'): 这一行代码对 logging.basicConfig 进行了更多配置。日志文件的路径通过 shotdir + "/" + "snapshot.txt" 来设置,即将日志文件放在 shotdir 目录下,并命名为 "snapshot.txt"。
format='[%(asctime)s.%(msecs)03d] %(message)s': 这一行代码修改了日志的格式。%(asctime)s 和 %(msecs)03d 表示日志的时间,精确到毫秒,格式为 "[时:分:秒.毫秒]",%(message)s 表示日志的具体内容。
logging.info(str(args)): 这一行代码使用 logging.info 记录了一个日志,内容为 str(args),即将 args 转换为字符串后输出。这个日志信息将被写入到之前设置的 "snapshot.txt" 文件中。
来看个例子,上述代码放入训练文件中使用,直接套用。
import logging# 配置日志记录器logging.basicConfig(filename='app.log', level=logging.INFO,format='%(asctime)s - %(levelname)s - %(message)s',datefmt='%H:%M:%S')# 编写日志消息logging.debug('1这是一个调试消息')logging.info('这是一个信息消息')logging.warning('这是一个警告消息')logging.error('这是一个错误消息')logging.critical('这是一个严重错误消息')这个文件很是奇怪,即使代码中改了日志的文件名,再次运行代码,日志还是会写进之前的那个日志文件。