博客
关于我
强烈建议你试试无所不能的chatGPT,快点击我
新版python logging 封装,支持同时向console,file,socket输出
阅读量:5816 次
发布时间:2019-06-18

本文共 4882 字,大约阅读时间需要 16 分钟。

将python的logging封装更新了一下,目前支持同时向console,file,socket输出,同时在config_logging或者config_logging_plus的时候先清除根logger的所有handler,避免在某些情况下的重复输出。

具体代码如下:

# -*- coding: utf-8 -*-'''Modified on 2012-11-27@summary: clear old root logger handlers when reconfig logging@author: JerryKwanCreated on 2012-06-14 19:50@summary:  logging config@author: JerryKwan'''import loggingimport logging.handlersimport osimport sysLEVELS = {
'NOSET': logging.NOTSET, 'DEBUG': logging.DEBUG, 'INFO': logging.INFO, 'WARNING': logging.WARNING, 'ERROR': logging.ERROR, 'CRITICAL': logging.CRITICAL}#set up logging to file#logging.basicConfig(level = logging.NOTSET,# format = "%(asctime)s %(name)-12s %(levelname)-8s %(message)s"# )## filename = "./log.txt",## filemode = "w")# create logs file folderdef config_logging(file_name = "log.txt", log_level = "NOSET"): ''' @summary: config logging to write logs to local file @param file_name: name of log file @param log_level: log level ''' logs_dir = os.path.join(os.path.dirname(__file__), "logs") if os.path.exists(logs_dir) and os.path.isdir(logs_dir): pass else: os.makedirs(logs_dir) # clear old root logger handlers logging.getLogger("").handlers = [] file_name = os.path.join(logs_dir, file_name) # define a rotating file handler rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =file_name, maxBytes = 1024 * 1024 * 50, backupCount = 5) formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") rotatingFileHandler.setFormatter(formatter) logging.getLogger("").addHandler(rotatingFileHandler) # define a handler whitch writes messages to sys console = logging.StreamHandler() # set a format which is simple for console use formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s") # tell the handler to use this format console.setFormatter(formatter) # add the handler to the root logger logging.getLogger("").addHandler(console) # set initial log level logger = logging.getLogger("") level = LEVELS[log_level.upper()] logger.setLevel(level)def config_logging_plus(file_name = "log.txt", log_level = "NOSET", remote_address = ("127.0.0.1", 8888), write_console = False): ''' @summary: config logging to write logs to remote service @param host: hostname or ip address of the log server @param port: port to be used for log server @log_level: log level ''' logs_dir = os.path.join(os.path.dirname(__file__), "logs") if os.path.exists(logs_dir) and os.path.isdir(logs_dir): pass else: os.makedirs(logs_dir) # format file name if file_name is None: file_name = os.path.splitext(sys.argv[0])[0] file_name = os.path.join(logs_dir, "%s_%s.log"%(file_name, os.getpid())) else: file_name = os.path.join(logs_dir, file_name) # clear old root logger handlers logging.getLogger("").handlers = [] # define a rotating file handler rotatingFileHandler = logging.handlers.RotatingFileHandler(filename =file_name, maxBytes = 1024 * 1024 * 50, backupCount = 5) formatter = logging.Formatter("%(asctime)s %(name)-12s %(levelname)-8s %(message)s") rotatingFileHandler.setFormatter(formatter) # add log handler logging.getLogger("").addHandler(rotatingFileHandler) if write_console is not None and write_console == True: # define a handler whitch writes messages to sys console = logging.StreamHandler() console.setLevel(logging.NOTSET) # set a format which is simple for console use formatter = logging.Formatter("%(name)-12s: %(levelname)-8s %(message)s") # tell the handler to use this format console.setFormatter(formatter) # add log handler logging.getLogger("").addHandler(console) if remote_address is not None and hasattr(remote_address, "__iter__") and len(remote_address) > 1: # define a socket handler socketHandler = logging.handlers.SocketHandler(remote_address[0], remote_address[1]) formatter = logging.Formatter("%(asctime)s %(processName)s %(process)s %(name)-12s %(levelname)-8s %(message)s") socketHandler.setFormatter(formatter) # add log handler logging.getLogger("").addHandler(socketHandler) # set initial log level logger = logging.getLogger("") level = LEVELS[log_level.upper()] logger.setLevel(level)

使用方法很简单,只需要需要config logging的时候config一下即可,示例代码如下:

import loggingconfigloggingconfig.config_logging(file_name = "log.log", log_level = "NOSET")

转载地址:http://jzmbx.baihongyu.com/

你可能感兴趣的文章
django 目录结构修改
查看>>
win8 关闭防火墙
查看>>
Android实例-录音与回放(播放MP3)(XE8+小米2)
查看>>
CSS——(2)与标准流盒模型
查看>>
MYSQL 基本SQL语句
查看>>
C#中的Marshal
查看>>
linux命令:ls
查看>>
Using RequireJS in AngularJS Applications
查看>>
hdu 2444(二分图最大匹配)
查看>>
shell编程笔记六:实现ll命令
查看>>
【SAP HANA】关于SAP HANA中带层次结构的计算视图Cacultation View创建、激活状况下在系统中生成对象的研究...
查看>>
[nodejs] nodejs开发个人博客(五)分配数据
查看>>
《Linux内核修炼之道》 之 高效学习Linux内核
查看>>
Java数据持久层框架 MyBatis之API学习九(SQL语句构建器详解)
查看>>
30分钟Git命令“从入门到放弃”
查看>>
nginx : TCP代理和负载均衡的stream模块
查看>>
MYSQL数据库间同步数据
查看>>
DevOps 前世今生 | mPaaS 线上直播 CodeHub #1 回顾
查看>>
iOS 解决UITabelView刷新闪动
查看>>
让前端小姐姐愉快地开发表单
查看>>