举个例子:比如我们要实现根据当前时间的年月日来新建目录来存放每天的日志,当前时间作为日志文件名称;代码如下:

  

#!/usr/bin/env python3
# _*_ coding: utf-8 _*_
import logging
import os.path
import time project_path = 'Exercise' #定义项目目录 class Logger(object):
def __init__(self):
'''''
指定保存日志的文件路径,日志级别,以及调用文件
将日志存入到指定的文件中
'''
current_time=time.strftime('%Y%m%d%H%M',
time.localtime(time.time())) # 返回当前时间
current_path=os.path.dirname(os.path.abspath(project_path)) # 返回当前目录
path1=current_path.split(project_path) #指定分隔符对字符串进行切片
path2=[path1[0], project_path]
path3=''
new_name=path3.join(path2) + '/logs/' #在该路径下新建下级目录 dir_time = time.strftime('%Y%m%d', time.localtime(time.time())) #返回当前时间的年月日作为目录名称
isExists=os.path.exists(new_name + dir_time) #判断该目录是否存在
if not isExists:
os.makedirs(new_name + dir_time)
print(new_name + dir_time + "目录创建成功") else:
# 如果目录存在则不创建,并提示目录已存在
print(new_name + "目录 %s 已存在" % dir_time) try:
# 创建一个logger(初始化logger)
self.log = logging.getLogger()
self.log.setLevel(logging.DEBUG) # 创建一个handler,用于写入日志文件 # 如果case组织结构式 /testsuit/featuremodel/xxx.py , 那么得到的相对路径的父路径就是项目根目录
log_name = new_name + dir_time + '/' + current_time + '.log' #定义日志文件的路径以及名称 fh = logging.FileHandler(log_name)
fh.setLevel(logging.INFO) # 再创建一个handler,用于输出到控制台
ch = logging.StreamHandler()
ch.setLevel(logging.INFO) # 定义handler的输出格式
formatter = logging.Formatter('[%(asctime)s] - %(name)s - %(levelname)s - %(message)s')
fh.setFormatter(formatter)
ch.setFormatter(formatter) # 给logger添加handler
self.log.addHandler(fh)
self.log.addHandler(ch)
except Exception as e:
print("输出日志失败! %s" % e) # 日志接口,用户只需调用这里的接口即可,这里只定位了INFO, WARNING, ERROR三个级别的日志,可根据需要定义更多接口 def info(cls,msg):
cls.log.info(msg)
return def warning(cls,msg):
cls.log.warning(msg)
return def error(cls, msg):
cls.log.error(msg)
return if __name__ == '__main__': logger = Logger()
logger.info('This is info')
logger.warning('This is warning')
logger.error('This is error')

python实现根据当前时间创建目录并输出日志的更多相关文章

  1. 转【Python】同时向控制台和文件输出日志logging

    #-*- coding:utf-8 -*-import logging # 配置日志信息logging.basicConfig(level=logging.DEBUG, format='%(ascti ...

  2. Python中日期和时间格式化输出的方法

    本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...

  3. python操作日期和时间的方法

    不管何时何地,只要我们编程时遇到了跟时间有关的问题,都要想到 datetime 和 time 标准库模块,今天我们就用它内部的方法,详解python操作日期和时间的方法.1.将字符串的时间转换为时间戳 ...

  4. 【转】Python之日期与时间处理模块(date和datetime)

    [转]Python之日期与时间处理模块(date和datetime) 本节内容 前言 相关术语的解释 时间的表现形式 time模块 datetime模块 时间格式码 总结 前言 在开发工作中,我们经常 ...

  5. python入门6 字符串拼接、格式化输出

    字符串拼接方式    1  使用 + 拼接字符串 2 格式化输出:%s字符串 %d整数 %f浮点数 %%输出% %X-16进制 %r-原始字符串 3 str.format() 代码如下: #codin ...

  6. python中常用的时间操作

    python中常用的时间模块有time和datetime,以下是这两个模块中常用的方法: #先引入模块 import timefrom datetime import datetiem, timezo ...

  7. 【转】kettle 的内存设置及输出日志的时间类型

    本文转载自:http://blog.csdn.net/dqswuyundong/archive/2010/10/19/5952004.aspx 设置kettle的内存 REM ************ ...

  8. Python标准库02 时间与日期 (time, datetime包)

    作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python具有良好的时间和日期管理功能.实际上,计算机只会维护一个挂钟时间(wa ...

  9. Python同时向控制台和文件输出日志logging的方法 Python logging模块详解

    Python同时向控制台和文件输出日志logging的方法http://www.jb51.net/article/66756.htm 1 #-*- coding:utf-8 -*- 2 import ...

随机推荐

  1. python multiprocess pool模块报错pickling error

    问题 之前在调用class内的函数用multiprocessing模块的pool函数进行多线程处理的时候报了以下下错误信息: PicklingError: Can't pickle <type ...

  2. Centos7 安装PHP7版本及php-fpm,redis ,php-redis,hiredis,swoole 扩展安装

    ============================PHP7.1 ========================================= 1. 更换rpm 源,执行下面两个 rpm - ...

  3. [Tensorflow] RNN - 03. MultiRNNCell for Digit Prediction

    Ref: http://blog.csdn.net/u014595019/article/details/52759104 Time: 2min Successfully downloaded tra ...

  4. [Python] Python 虚拟机 - virtualenv

    virtualenv virtualenv 用于创建一个隔离的 Python 环境. 每个项目都有自己的依赖包,这些依赖包有时存在版本冲突,处理这种情况最好方法就是为每个项目创建一个专属的环境. 安装 ...

  5. Django读取Mysql数据并显示在前端

    一.首先按添加网页的步骤添加网页,我的网页名为table.html, app名为web table.html放到相应目录下, froms文件提前写好 修改views.py ? 1 2 3 4 5 6 ...

  6. FileInputFormat看这一段源码

    这是FileInputFormat中的一个方法,看一下它的功能,多看源码,理解hadoop,同时提高自己的java编程能力: private static String[] getPathString ...

  7. Spark RDD Action 简单用例(一)

    collectAsMap(): Map[K, V] 返回key-value对,key是唯一的,如果rdd元素中同一个key对应多个value,则只会保留一个./** * Return the key- ...

  8. 洛谷P1040 加分二叉树【记忆化搜索】

    题目链接:https://www.luogu.org/problemnew/show/P1040 题意: 某一个二叉树的中序遍历是1~n,每个节点有一个分数(正整数). 二叉树的分数是左子树分数乘右子 ...

  9. [No0000F9]C# 运算符重载

    您可以重定义或重载 C# 中内置的运算符.因此,程序员也可以使用用户自定义类型的运算符.重载运算符是具有特殊名称的函数,是通过关键字 operator 后跟运算符的符号来定义的.与其他函数一样,重载运 ...

  10. [No0000CA]什么是“普瑞马法则”?以及 如何利用“普瑞马法则”,三步克服惰性

    一般在学习和生活中,我们都可能有这样的经验,就是当说想要作某件事情的时候,但过了好久发现还是没有做:或者觉得有力气使不出来:或者总觉得生活是灰色和抑郁的等等. 这类情况反映在生活中,就是生活好像总是被 ...