Python3自定义日志类 mylog
#encoding=utf-8
import os, sys
import datetime
import time
class Mylog(object):
# 根文件夹
root_dir = sys.path[0]
# 根目录
root_path = sys.path[0] + os.path.sep
# 系统目录分割线
sys_sep = os.path.sep
# 配置
option = {
# 日志级别: 0:全部,1:调试,2:警告,3:错误
'level': 0,
# 是否开启,如果关闭则不输出也不记录日志
'is_open': True,
# 是否print输出
'is_print': True,
# 是否记录到日志文件
'is_write': True,
# 是否在每条日志内容前面加前缀
'is_prefix': True,
# 如果开启了每条日志前加前缀,设置日志级别为1的前缀
'level_1_prefix': 'Test: ',
# 如果开启了每条日志前加前缀,设置日志级别为2的前缀
'level_2_prefix': 'Warning: ',
# 如果开启了每条日志前加前缀,设置日志级别为3的前缀
'level_3_prefix': 'Error: ',
# 存放日志文件的根文件夹名称
'root_dir_name': 'mylog',
# 自定义存放日志文件的文件名称,此文件夹是在 root_dir_name 文件夹下
'dir_name': ''
}
def __init__(self, config=None):
if config is not None:
self.option.update(dict(config))
# 日志保存的文件夹(全路径)
save_dir = self.root_path + self.option['root_dir_name']
# 创建文件夹
if os.path.isdir(save_dir) is not True:
os.mkdir(save_dir)
if len(self.option['dir_name']) > 0:
save_dir += self.sys_sep + self.option['dir_name']
if os.path.isdir(save_dir) is not True:
os.mkdir(save_dir)
self.save_dir = save_dir
self.save_path = save_dir + self.sys_sep
'''
输入日志/记录日志
'''
def log(self, content='', level=0):
self._print_log(content, level)
self._write_log(content, level)
'''
输入日志
'''
def _print_log(self, content, level):
if self.option['is_open'] is True and self.option['is_print'] is True:
if self.option['level'] == 0 or self.option['level'] == level:
if level > 0:
content = self.option['level_' + str(level) + '_prefix'] + content
print(content)
'''
记录日志
'''
def _write_log(self, content, level):
if self.option['is_open'] is True and self.option['is_print'] is True:
if self.option['level'] == 0 or self.option['level'] == level:
if self.option['is_prefix'] is True:
today = datetime.date.today()
file_name = str(today) + '.log'
now = time.strftime("%H:%M:%S")
log_file = self.save_path + file_name
if level > 0:
content = self.option['level_' + str(level) + '_prefix'] + content
if os.path.isfile(log_file):
save_file = open(log_file, 'a')
else:
save_file = open(log_file, 'w')
save_file.write(str(now) + "\r\n" + content + "\r\n")
save_file.close()
**重点内容
#!/usr/bin/env python
#-*- coding: GBK -*-
__author__ = 'DiaoHuabin'
import logging
import getpass
import sys
#定义MyLog类
class MyLog(object):
'''这个类用于创建一个自用的log'''
def __init__(self): #类MyLog的构造函数
user = getpass.getuser() #返回用户的登录名
self.logger = logging.getLogger(user) #返回一个特定名字的日志
self.logger.setLevel(logging.DEBUG) #对显示的日志信息设置一个阈值低于DEBUG级别的不显示
logFile = './'+sys.argv[1][0:-3] + '.log' # 日志文件名
formatter = logging.Formatter('%(asctime)-12s $(levelname)-8s %(name)-10s %(message)-12s')
'''日志显示到屏幕上并输出到日志文件内'''
logHand = logging.FileHandler(logFile) #输出日志文件,文件名是logFile
logHand.setFormatter(formatter) #为logHand以formatter设置格式
logHand.setLevel(logging.ERROR) #只有错误才被记录到logfile中
logHandSt = logging.StreamHandler() #class logging.StreamHandler(stream=None)
# 返回StreamHandler类的实例,如果stream被确定,使用该stream作为日志输出,反之,使用
#sys.stderr
logHandSt.setFormatter(formatter) #为logHandSt以formatter设置格式
self.logger.addHandler(logHand) #添加特定的handler logHand到日志文件logger中
self.logger.addHandler(logHandSt) #添加特定的handler logHandSt到日志文件logger中
'''日志的5个级别对应以下的五个函数'''
def debug(self,msg):
self.logger.debug(msg) #Logs a message with level DEBUG on this logger.
# The msg is the message format string
def info(self,msg):
self.logger.info(msg)
def warn(self,msg):
self.logger.warn(msg)
def error(self,msg):
self.logger.error(msg)
def critical(self,msg):
self.logger.critical(msg)
if __name__ == '__main__':
mylogw = MyLog()
mylogw.debug("I'm debug")
mylogw.info("I'm info")
mylogw.warn("I'm warn")
mylogw.error("I'm error")
mylogw.critical("I'm critical")
写图片描述
这里写图片描述
Python3自定义日志类 mylog的更多相关文章
- Python3自定义日志类教程
一.说明 Python3的logging功能是比较丰富的支持不同层次的日志输出,但或是我们想在日志前输出时间.或是我们想要将日志输入到文件,我们还是想要自定义日志类. 之前自己也尝试写过但感觉文档太乱 ...
- flask中自定义日志类
一:项目架构 二:自定义日志类 1. 建立log.conf的配置文件 log.conf [log] LOG_PATH = /log/ LOG_NAME = info.log 2. 定义日志类 LogC ...
- c#自定义日志记录
废话不多说,直接上代码: 很简单:将类复制到项目中,最后在配置文件上配置一下:logUrl即可. 默认保存在:项目/temp/log /// <summary> /// 日志类 /// & ...
- 《手把手教你》系列基础篇(八十五)-java+ selenium自动化测试-框架设计基础-TestNG自定义日志-下篇(详解教程)
1.简介 TestNG为日志记录和报告提供的不同选项.现在,宏哥讲解分享如何开始使用它们.首先,我们将编写一个示例程序,在该程序中我们将使用 ITestListener方法进行日志记录. 2.Test ...
- python3+selenium框架设计03-封装日志类
首先我们先来实现日志的功能,日志可以使用python3自带logging模块,不会的可以百度一下相关文章,也可以看我另外一篇文章Python3学习笔记24-logging模块 在封装日志类前,我们需要 ...
- python3+requests库框架设计02-封装日志类
首先我们先来实现日志的功能,日志可以使用python3自带logging模块,不会的可以百度一下相关文章,也可以看我另外一篇文章Python3学习笔记24-logging模块 在封装日志类前,我们需要 ...
- python3.4中自定义数组类(即重写数组类)
'''自定义数组类,实现数组中数字之间的四则运算,内积运算,大小比较,数组元素访问修改及成员测试等功能''' class MyArray: '''保证输入值为数字元素(整型,浮点型,复数)''' de ...
- python3 配置logging日志类
配置类config_file: from configparser import ConfigParser class config_file: def __init__(self,conf_file ...
- YII2 自定义日志路径
YII 提供的日志写入方法: 1.Yii::getLogger()->log($message, $level, $category = 'application') 2.Yii::trace( ...
随机推荐
- Postman教程
1.Postman的介绍 Postman是一款功能强大的用于发送 HTTP 请求的 Chrome插件 .做web页面开发和测试的人员应该都知道!其主要特点:创建 + 测试:创建和发送任何的HTTP请求 ...
- 005-优化web请求一-gzip压缩、http缓存控制和缓存校验[Pragma、Expires、Cache-Control、max-age、Last-Modified、用户刷新访问、避免过度304]
优化Web应用的典型技术:缓存控制头信息.Gzip.应用缓存.ETag.反应型技术[异步方法调用和WebSocket] 一.模板缓存 spring.thymeleaf.cache=true sprin ...
- 安全易用的云许可-VirboxLM许可管理平台
Virbox LM是深思推出的基于云许可管理的开放平台,旨在为开发者提供低成本.高强度.操作便捷的一站式软件保护方案. Virbox LM包括用户许可管理工具.加壳工具.API帮助工具.开发商管理工具 ...
- python-->(set /dict)交集 差集 并集 补集(功能用来做交差并补的)
# ### 集合 作用:交集 差集 并集 补集(功能用来做交差并补的) '''特征:自动去重 无序''' #定义一个空集合 setvar = set() #set()强制转换成一个空集合的数据类型 p ...
- https://www.cnblogs.com/beileixinqing/p/7724779.html vue-cli生成的项目配置开发和生产环境不同的接口 vue-cli生成的项目,vue项目配置了不同开发环境的接口地址,axios.defaults.baseURL如何引用这个地址,这是在我发布项目的时候考虑的,于是想到了
方法二:(集热心网友提供的方案) 一般项目webpack会有两个或多个配置文件,如: webpack.prod.conf.js 对应线上打包 webpack.dev.conf.js 对应开发环境 使用 ...
- 无法连接 MKS:套接字连接尝试次数太多正在放弃
我的电脑 -> 右键 -> 管理 -> 服务和应用程序 -> 服务: 开启下面的服务: 服务启动成功后,重启虚拟机; 或者先挂起虚拟机,等服务启动后,继续运行挂起的虚拟机:
- (转)Geth控制台使用及Web3.js使用实战
在开发以太坊去中心化应用,免不了和以太坊进行交互,那就离不开Web3.Geth 控制台(REPL)实现了所有的web3 API及Admin API,使用好 Geth 就是必修课.结合Geth命令用法阅 ...
- k8s 高级调度 亲和力和反亲和力、绑定标签、污点容忍污点
通过标签绑定 spec: nodeSelector: bigdata-node: bigdata containers: - env: pod只能运行在有bigdata-node: bigdata 标 ...
- 天气服务API文档 第1版
HTTP接口设计文档 此文档为开发HTTP接口的设计文档,目前用于提供天气查询的相关接口. 测试的时候使用 URL=http://www.dennisthink.com/test/api/weathe ...
- [Git/GitHub] Tutorial 1. Git download and commit first project
1. Install at https://git-scm.com/downloads 2. Set up your name and email $ git config --global user ...