前言

曾经转载过一篇关于python日志模块logging的详解 https://www.cnblogs.com/linuxchao/p/linuxchao-log.html, 虽然这篇文章是别人写的, 但是我就是靠着这篇文章入门的logging,所以我觉得没必要再继续说些理论的东西,今天就简单的对日志做个封装,实际工作中直接拿去用吧

方法1

"""
------------------------------------
@Time : 2019/5/22 8:12
@Auth : linux超
@File : logfile.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import logging class Log(object):
def __init__(self, name=__name__, path='mylog.log', level='DEBUG'):
self.__name = name
self.__path = path
self.__level = level
self.__logger = logging.getLogger(self.__name)
self.__logger.setLevel(self.__level) def __ini_handler(self):
"""初始化handler"""
stream_handler = logging.StreamHandler()
file_handler = logging.FileHandler(self.__path, encoding='utf-8')
return stream_handler, file_handler def __set_handler(self, stream_handler, file_handler, level='DEBUG'):
"""设置handler级别并添加到logger收集器"""
stream_handler.setLevel(level)
file_handler.setLevel(level)
self.__logger.addHandler(stream_handler)
self.__logger.addHandler(file_handler) def __set_formatter(self, stream_handler, file_handler):
"""设置日志输出格式"""
formatter = logging.Formatter('%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]'
'-%(levelname)s-[日志信息]: %(message)s',
datefmt='%a, %d %b %Y %H:%M:%S')
stream_handler.setFormatter(formatter)
file_handler.setFormatter(formatter) def __close_handler(self, stream_handler, file_handler):
"""关闭handler"""
stream_handler.close()
file_handler.close() @property
def Logger(self):
"""构造收集器,返回looger"""
stream_handler, file_handler = self.__ini_handler()
self.__set_handler(stream_handler, file_handler)
self.__set_formatter(stream_handler, file_handler)
self.__close_handler(stream_handler, file_handler)
return self.__logger if __name__ == '__main__':
log = Log(__name__, 'file.log')
logger = log.Logger
logger.debug('I am a debug message')
logger.info('I am a info message')
logger.warning('I am a warning message')
logger.error('I am a error message')
logger.critical('I am a critical message')

初始化方法参数说明

name:自定义日志的名字, 默认是root, 但是我这里是使用调用文件的__name__ 作为默认名字

path:生成的日志的文件名

level:日志的级别,我这里把所有的级别都默认设置了level=DEBUG

方法2

使用logging.fileconfig这个模块实现(不知道这个模块的找度娘恶补一下把)

1.使用配置文件构造日志配置信息

logger.ini

[loggers]
keys = root, example01, example02
[logger_root]
level = DEBUG
handlers = hand01, hand02
[logger_example01]
handlers = hand01, hand02
qualname = example01
propagate = 0
[logger_example02]
handlers = hand01, hand03
qualname = example02
propagate = 0
[handlers]
keys = hand01, hand02, hand03
[handler_hand01]
class = StreamHandler
level = INFO
formatter = form01
args=(sys.stdout, )
[handler_hand02]
class = FileHandler
level = DEBUG
formatter = form01
args = ('log/test_case_log.log', 'a')
[handler_hand03]
class = handlers.RotatingFileHandler
level = INFO
formatter = form01
args = ('log/test_case_log.log', 'a', 10*1024*1024,3)
[formatters]
keys = form01, form02
[formatter_form01]
format = %(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s-[LogInfoMessage]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S
[formatter_form02]
format = %(name)-12s: %(levelname)-8s-[日志信息]: %(message)s
datefmt = %a, %d %b %Y %H:%M:%S

封装python代码

"""
------------------------------------
@Time : 2019/5/22 9:37
@Auth : linux超
@File : Log.py
@IDE : PyCharm
@Motto: Real warriors,dare to face the bleak warning,dare to face the incisive error!
------------------------------------
"""
import logging
from logging import config class MyLog(object): def __init__(self):
config.fileConfig('logger.ini')
self.logger = logging.getLogger('example01') @property
def my_logger(self): return self.logger if __name__ == '__main__':
log = MyLog()
log.my_logger.info('it is my test log message info')

总结

两种方法各有好处吧

第一种代码很好理解思路清晰 , 但是不利于项目都维护,比如日志文件名,日志格式等无法修改,只能通过代码内部修改

第二种其实是使用config模块内部使用配置文件操作模块ConfigParser做了封装, 用配置文件来构造自定义日志器,好处很明显,我们只要通过修改配置文件就能修改日志的格式,名字,级别等等一些设置,无需改动代码,而且使用很简单, 其实这种方法完全不需要封装一个python代码,哪个模块需要输出日志,直接调用config模块获得logger就可以了(就是上面文件的那几行代码),今天就到这吧......

python操作日志的封装的更多相关文章

  1. python操作日志

    # # import nnlog# my_log=nnlog.Logger('nhy.log',when='S',backCount=5)# my_log.debug('这是dedug')# my_l ...

  2. LightMysql:为方便操作MySQL而封装的Python类

    原文链接:http://www.danfengcao.info/python/2015/12/26/lightweight-python-mysql-class.html mysqldb是Python ...

  3. 通过python操作GeoLite2-City.mmdb库将nginx日志访问IP转换为城市写入数据库

    通过python操作GeoLite2-City.mmdb库将nginx日志写入数据库 # 创建存放nginx日志的表accesslog2 CREATE TABLE `accesslog2` ( `id ...

  4. python 日志的配置,python对日志封装成类,日志的调用

    # python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...

  5. 基于SqlSugar的开发框架循序渐进介绍(8)-- 在基类函数封装实现用户操作日志记录

    在我们对数据进行重要修改调整的时候,往往需要跟踪记录好用户操作日志.一般来说,如对重要表记录的插入.修改.删除都需要记录下来,由于用户操作日志会带来一定的额外消耗,因此我们通过配置的方式来决定记录那些 ...

  6. 【转】Python之日志处理(logging模块)

    [转]Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging ...

  7. Python之路:Python操作 RabbitMQ、Redis、Memcache、SQLAlchemy

    Memcached Memcached 是一个高性能的分布式内存对象缓存系统,用于动态Web应用以减轻数据库负载.它通过在内存中缓存数据和对象来减少读取数据库的次数,从而提高动态.数据库驱动网站的速度 ...

  8. Python 配置日志的几种方式

    Python配置日志的几种方式 作为开发者,我们可以通过以下3种方式来配置logging: (1)使用Python代码显式的创建loggers,handlers和formatters并分别调用它们的配 ...

  9. Python logging(日志)模块

    python日志模块 内容简介 1.日志相关概念 2.logging模块简介 3.logging模块函数使用 4.logging模块日志流处理流程 5.logging模块组件使用 6.logging配 ...

随机推荐

  1. HDU-1556-Color the ball (线段树和差分数组两种解法)

    N个气球排成一排,从左到右依次编号为1,2,3....N.每次给定2个整数a b(a <= b),lele便为骑上他的"小飞鸽"牌电动车从气球a开始到气球b依次给每个气球涂一 ...

  2. SocLib的安装

    一.soclib的安装 1.安装g++,一般Ubuntu系统都自带了,所以无需安装.后面这两个软件需要提前安装,不然后面执行相关操作是会报错:sudo apt-get install automake ...

  3. @Slf4j注解的使用

    项目中使用Slf4j日志: private static final Logger log=LoggerFactory.getLogger(TestMain.class); 使用@Slf4j以后,默认 ...

  4. Elasticsearch优化

    2.out of memory错误 因为默认情况下es对字段数据缓存(Field Data Cache)大小是无限制的,查询时会把字段值放到内存,特别是facet查询,对内存要求非常高,它会把结果都放 ...

  5. 在前端解決顯示null值一例

    用.net core2.1 api返回的JSON里包含null值,前端直接顯示出來了,影響閱讀, 用以下語句將null轉換為空字符串: // Build html. html += "< ...

  6. 超文本传输协议(HTTP)

    超文本传输协议(HyperText Transfer Protocol,Http)是从服务器传输数据到客户端的传输协议. HTTP协议的主要特点可概括如下: 1.支持客户/服务器模式. 2.简单快速: ...

  7. spring4、hibernate4整合xml配置

    <?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.sp ...

  8. Xiaocms 去版权

    Xiaocms 去版权 后台去版权: 1.  登录页面 修改文件:\admin\template\login.tpl.php 代码: <td width="190" rows ...

  9. SQL Server 填充因子

    在创建聚集索引时,表中的数据按照索引列中的值的顺序存储在数据库的数据页中.在表中插入新的数据行或更改索引列中的值时,Microsoft®   SQL   Server™   2000   可能必须重新 ...

  10. windows 密钥

    server 2016数据中心CB7KF-BWN84-R7R2Y-793K2-8XDDG