python实现根据当前时间创建目录并输出日志
举个例子:比如我们要实现根据当前时间的年月日来新建目录来存放每天的日志,当前时间作为日志文件名称;代码如下:
#!/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实现根据当前时间创建目录并输出日志的更多相关文章
- 转【Python】同时向控制台和文件输出日志logging
#-*- coding:utf-8 -*-import logging # 配置日志信息logging.basicConfig(level=logging.DEBUG, format='%(ascti ...
- Python中日期和时间格式化输出的方法
本文转自:https://www.jb51.net/article/62518.htm 本文实例总结了python中日期和时间格式化输出的方法.分享给大家供大家参考.具体分析如下: python格式化 ...
- python操作日期和时间的方法
不管何时何地,只要我们编程时遇到了跟时间有关的问题,都要想到 datetime 和 time 标准库模块,今天我们就用它内部的方法,详解python操作日期和时间的方法.1.将字符串的时间转换为时间戳 ...
- 【转】Python之日期与时间处理模块(date和datetime)
[转]Python之日期与时间处理模块(date和datetime) 本节内容 前言 相关术语的解释 时间的表现形式 time模块 datetime模块 时间格式码 总结 前言 在开发工作中,我们经常 ...
- python入门6 字符串拼接、格式化输出
字符串拼接方式 1 使用 + 拼接字符串 2 格式化输出:%s字符串 %d整数 %f浮点数 %%输出% %X-16进制 %r-原始字符串 3 str.format() 代码如下: #codin ...
- python中常用的时间操作
python中常用的时间模块有time和datetime,以下是这两个模块中常用的方法: #先引入模块 import timefrom datetime import datetiem, timezo ...
- 【转】kettle 的内存设置及输出日志的时间类型
本文转载自:http://blog.csdn.net/dqswuyundong/archive/2010/10/19/5952004.aspx 设置kettle的内存 REM ************ ...
- Python标准库02 时间与日期 (time, datetime包)
作者:Vamei 出处:http://www.cnblogs.com/vamei 欢迎转载,也请保留这段声明.谢谢! Python具有良好的时间和日期管理功能.实际上,计算机只会维护一个挂钟时间(wa ...
- Python同时向控制台和文件输出日志logging的方法 Python logging模块详解
Python同时向控制台和文件输出日志logging的方法http://www.jb51.net/article/66756.htm 1 #-*- coding:utf-8 -*- 2 import ...
随机推荐
- [Stats385] Lecture 04: Convnets from Probabilistic Perspective
本篇围绕“深度渲染混合模型”展开. Lecture slices Lecture video Reading list A Probabilistic Framework for Deep Learn ...
- PHP实现删除非站内外部链接实例代码
/** * 删除非站内链接 * * @access public * @param string $body 内容 * @param array $allow_urls ...
- [Linux] 如何禁止使用口令只允许使用密钥建立 SSH 连接
1. 创建 SSH KEY 使用 ssh-keygen 生成一个密钥对,并且将公钥注册到服务器的 $HOME/.ssh/authorized_keys 文件. 2. 确保启用 SSH 公钥认证功能 查 ...
- 什么是IOC为什么要使用IOC
概念: 作用: 结论:借助于“第三方”实现具有依赖关系的对象之间的解耦 在使用IOC之前的情况 如果有一个齿轮出了问题,就可能会影响到整个齿轮组的正常运 使用IOC之后 对象A获得依赖对象B的过程,由 ...
- Android 更改按钮样式 Button Styles
extends:http://stackoverflow.com/questions/26346727/android-material-design-button-styles I will a ...
- react-native 搭建环境
1.安装 nodejs 配置环境变量 node -v npm -v 2.安装 javaSE 1.8以上 http://www.oracle.com/technetwork/java/javase/ar ...
- 引用了System.Configuration命名空间,却找不到ConfigurationManager类
用ConfigurationManager类来读取应用程序配置文件的信息时,提示:System.Configuration命名空间下找不到ConfigurationManager类 查过资料后得知:要 ...
- 第一章:初识Python
一个Python列表 movies = ["The Holy Grail",1975,"Terry Jones&Terry Gilliam",91,[& ...
- js callback 和 js 混淆
function test(a,callback){ a+=100; callback(a) } function abc(a){ a+=100; alert(a); } test(5,abc) js ...
- UVALive - 6185 Find the Outlier暴力填表+高斯消元+卡eps
https://cn.vjudge.net/problem/UVALive-6185 我真的是服了orz eps 1e5,1e6过不了 开1e2 1e1都能过 题意:给你一个d阶多项式f的f(0),f ...