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

本文共 4953 字,大约阅读时间需要 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")

转载于:https://www.cnblogs.com/Jerryshome/archive/2012/11/27/2791416.html

你可能感兴趣的文章
第四十期百度技术沙龙笔记整理
查看>>
推荐系统那点事 —— 基于Spark MLlib的特征选择
查看>>
linux 下RTL8723/RTL8188调试记录(命令行)【转】
查看>>
SpringMVC案例1——对User表进行CRUD操作
查看>>
[Contiki系列论文之1]Contiki——为微传感器网络而生的轻量级的、灵活的操作系统...
查看>>
Android 网络编程 记录
查看>>
微软同步发行Windows 10和Windows 10 Mobile系统更新
查看>>
Zeppelin的入门使用系列之使用Zeppelin运行shell命令(二)
查看>>
form表单下的button按钮会自动提交表单的问题
查看>>
那些年追过的......写过的技术博客
查看>>
python基础教程_学习笔记19:标准库:一些最爱——集合、堆和双端队列
查看>>
C# 解决窗体闪烁
查看>>
CSS魔法堂:Transition就这么好玩
查看>>
【OpenStack】network相关知识学习
查看>>
centos 7下独立的python 2.7环境安装
查看>>
[日常] 算法-单链表的创建
查看>>
前端工程化系列[01]-Bower包管理工具的使用
查看>>
使用 maven 自动将源码打包并发布
查看>>
Spark:求出分组内的TopN
查看>>
Python爬取豆瓣《复仇者联盟3》评论并生成乖萌的格鲁特
查看>>