python对日志处理的封装
一个适应性范围较广的日志处理
# coding=utf8
"""
@author bfzs
"""
import os
import logging
from logging.handlers import TimedRotatingFileHandler, RotatingFileHandler
from cloghandler import ConcurrentRotatingFileHandler format_dict = {
1: logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S"),
2: logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S"),
3: logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S"),
4: logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S"),
5: logging.Formatter('%(asctime)s - %(name)s - %(lineno)d - %(levelname)s - %(message)s', "%Y-%m-%d %H:%M:%S"),
} class LogLevelException(Exception):
def __init__(self, log_level):
err = '设置的日志级别是 {0}, 设置错误,请设置为1 2 3 4 5 范围的数字'.format(log_level)
Exception.__init__(self, err) class Log(object):
"""
一个日志类,用于创建和捕获日志,支持将日志打印到控制台打印和写入日志文件。
""" def __init__(self, logger_name=None, log_level_int=1, is_add_stream_handler=True, log_path=None, log_filename=None):
"""
:param logger_name: 日志名称,当为None时候打印所有日志
:param log_level_int: 日志级别,设置为 1 2 3 4 5,分别对应DEBUG,INFO,WARNING,ERROR,CRITICAL
:param is_add_stream_handler: 是否打印日志到控制台
:param log_path: 设置存放日志的文件夹路径
:param log_filename: 日志的名字,仅当log_path和log_filename都不为None时候才写入到日志文件。
:type logger_name :str
:type log_level_int :int
:type is_add_stream_handler :bool
:type log_path :str
:type log_filename :str
"""
self.logger = logging.getLogger(logger_name)
self.__check_log_level(log_level_int)
self._logger_level = self.__transform_logger_level(log_level_int)
self._is_add_stream_handler = is_add_stream_handler
self._log_path = log_path
self._log_filename = log_filename
self._formatter = format_dict[log_level_int]
self.__set_logger_level()
self.__add_handlers() def debug(self, msg):
self.logger.debug(msg) def info(self, msg):
self.logger.info(msg) def warning(self, msg):
self.logger.warning(msg) def error(self, msg):
self.logger.error(msg) def critical(self, msg):
self.logger.critical(msg) def __set_logger_level(self):
self.logger.setLevel(self._logger_level) @staticmethod
def __check_log_level(log_level_int):
if log_level_int not in [1, 2, 3, 4, 5]:
raise LogLevelException(log_level_int) @staticmethod
def __transform_logger_level(log_level_int):
logger_level = None
if log_level_int == 1:
logger_level = logging.DEBUG
elif log_level_int == 2:
logger_level = logging.INFO
elif log_level_int == 3:
logger_level = logging.WARNING
elif log_level_int == 4:
logger_level = logging.ERROR
elif log_level_int == 5:
logger_level = logging.CRITICAL
return logger_level def __add_handlers(self):
if self._is_add_stream_handler:
self.__add_stream_handler()
if all([self._log_path, self._log_filename]):
self.__add_file_handler() def __add_stream_handler(self):
"""
日志显示到控制台
"""
stream_handler = logging.StreamHandler()
stream_handler.setLevel(self._logger_level)
stream_handler.setFormatter(self._formatter)
self.logger.addHandler(stream_handler) def __add_file_handler(self):
"""
日志写入日志文件
"""
if not os.path.exists(self._log_path):
os.makedirs(self._log_path)
log_file = os.path.join(self._log_path, self._log_filename)
os_name = os.name
print os_name
rotate_file_handler = None
if os_name == 'nt':
# windows下用这个,非进程安全
rotate_file_handler = RotatingFileHandler(log_file, mode="a", maxBytes=10 * 1024 * 1024, backupCount=10, encoding="utf-8")
if os_name == 'posix':
# linux下可以使用ConcurrentRotatingFileHandler,进程安全的日志方式
rotate_file_handler = ConcurrentRotatingFileHandler(log_file, mode="a", maxBytes=10 * 1024 * 1024, backupCount=10, encoding="utf-8")
rotate_file_handler.setLevel(logging.DEBUG)
rotate_file_handler.setFormatter(self._formatter)
self.logger.addHandler(rotate_file_handler) def test_func():
"""测试日志打印,单独运行test_func函数是不会打印出这条日志,没有添加handler"""
logger = logging.getLogger('test')
logger.info(u'需要被打印的日志') if __name__ == "__main__":
test_log = Log('test', 1, log_path='./logs', log_filename='test.log')
test_func()
test_log.info(u'添加一条日志') import requests request_log = Log('urllib3.connectionpool', 1) # 测试三方包的日志
resp = requests.get('https://www.baidu.com')
场景:将不同的日志写入到不同的文件,分析业务问题,查看三方包的日志。
有的三方包的日志是必须捕获,例如concurrent包的日志,线程池运行错误都是通过日志的方式报错,如果不对日志进行打印捕获,很多语法错误或者流程错误都看不到,可能会以为写的东西没毛病呢。
python对日志处理的封装的更多相关文章
- python 日志的配置,python对日志封装成类,日志的调用
# python 日志的配置,python对日志封装成类,日志的调用 import logging # 使用logging模块: class CLog: # --------------------- ...
- python操作日志的封装
前言 曾经转载过一篇关于python日志模块logging的详解 https://www.cnblogs.com/linuxchao/p/linuxchao-log.html, 虽然这篇文章是别人写的 ...
- python logging 日志轮转文件不删除问题
前言 最近在维护项目的python项目代码,项目使用了 python 的日志模块 logging, 设定了保存的日志数目, 不过没有生效,还要通过contab定时清理数据. 分析 项目使用了 logg ...
- python标准日志模块logging及日志系统设计
最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下. python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果你想开发 ...
- Python脚本日志系统
Python通过logging模块提供日志功能,关于logging模块的使用网络上已经有很多详细的资料,这里要分享的是怎样在实际工程中使用日志功能. 假设要开发一个自动化脚本工具,工程结构如下,Com ...
- 【转】Python之日志处理(logging模块)
[转]Python之日志处理(logging模块) 本节内容 日志相关概念 logging模块简介 使用logging提供的模块级别的函数记录日志 logging模块日志流处理流程 使用logging ...
- 使用python实现日志功能
Python脚本日志系统 Python通过logging模块提供日志功能,关于logging模块的使用网络上已经有很多详细的资料,这里要分享的是怎样在实际工程中使用日志功能. 假设要开发一个自动化 ...
- python标准日志模块logging的使用方法
参考地址 最近写一个爬虫系统,需要用到python的日志记录模块,于是便学习了一下.python的标准库里的日志系统从Python2.3开始支持.只要import logging这个模块即可使用.如果 ...
- Python 配置日志的几种方式
Python配置日志的几种方式 作为开发者,我们可以通过以下3种方式来配置logging: (1)使用Python代码显式的创建loggers,handlers和formatters并分别调用它们的配 ...
随机推荐
- [开发笔记]-实现winform半透明毛玻璃效果
亲测win7下可用,win8下由于系统不支持Aero效果,所以效果不是半透明的. 代码: 博客园插入不了代码了..... public partial class Form1 : Form { int ...
- DataTable 行删除
今天在阅读一个项目中的代码时,发现删除DataTable的数据时用的dataTable.Clear(); 由于以前自己习惯都是用dataTable.Rows.Clear();因此突然感觉到很茫然,难道 ...
- map-reduce 优化
map阶段优化 参数:io.sort.mb(default 100) 当map task开始运算,并产生中间数据时,其产生的中间结果并非直接就简单的写入磁盘. 而是会利用到了内存buffer来进行已经 ...
- 初入android驱动开发之字符设备(四-中断)
上一篇讲到android驱动开发中,应用是怎样去操作底层硬件的整个流程,实现了按键控制led的亮灭.当然,这是一个非常easy的实例,只是略微演变一下,就能够得到广泛的应用. 如开发扫描头,应用透过监 ...
- SpringBoot(三):文件下载
SpringBoot(三):文件下载 2017年08月02日 10:46:42 阅读数:6882 在原来的SpringBoot–uploadfile项目基础上添加文件下载的Controller: @R ...
- altium designer 快捷键
2010年03月27日 环境快捷键 F1 访问文档库 (in context with object under cursor) Ctrl + O 访问选择的文档打开对话框 Ctrl + F4 关闭活 ...
- hibernate+pageBean实现分页dao层功能代码
今天闲来无事,摆弄了一下分页,突然发现很多代码长时间不用就生梳了,虽然有些基础,但没有一篇整合的.这里还是简单示例,主要是以后自己翻着看不用百度找啊找找不到一篇想要的 1.PageBean实体类,一页 ...
- 第三百四十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—cookie禁用、自动限速、自定义spider的settings,对抗反爬机制
第三百四十九节,Python分布式爬虫打造搜索引擎Scrapy精讲—cookie禁用.自动限速.自定义spider的settings,对抗反爬机制 cookie禁用 就是在Scrapy的配置文件set ...
- 第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令
第三百三十一节,web爬虫讲解2—Scrapy框架爬虫—Scrapy安装—Scrapy指令 Scrapy框架安装 1.首先,终端执行命令升级pip: python -m pip install --u ...
- Java如何使用线程解决死锁?
在Java编程中,如何使用线程解决死锁? 以下示例演示如何使用线程的概念解决死锁问题. // from W w w .Y I I b AI.c o M package com.yiibai; impo ...