python logging 单例模式范例
2016-01-07 12:56
639 查看
#logger.py #author: Zilu.Tang #date: 20160107 import logging import os class SingleLogger(object): __instance = None def __init__(self): pass def __new__(cls, *args, **kwd): if SingleLogger.__instance is None: SingleLogger.__instance = object.__new__(cls, *args, **kwd) SingleLogger.__instance.__logger = logging.getLogger("logger1") SingleLogger.__instance.__logger.setLevel(logging.DEBUG) formatter = logging.Formatter('%(name)-12s %(asctime)s %(levelname)-8s %(message)s', '%a, %d %b %Y %H:%M:%S',) file_handler = logging.FileHandler(r"test.log") file_handler.setLevel(logging.INFO) stream_handler = logging.StreamHandler() file_handler.setFormatter(formatter) SingleLogger.__instance.__logger.addHandler(file_handler) SingleLogger.__instance.__logger.addHandler(stream_handler) SingleLogger.__instance.__logger.info("log info: " + os.getcwd()) return SingleLogger.__instance def info(self, message): SingleLogger.__instance.__logger.info(message)
Usage:
from logger import SingleLogger class Usage(): def __init__(self): self.__logger = SingleLogger() def test(self): self.__logger.info("Test logger")
相关文章推荐
- Python动态类型的学习---引用的理解
- Python3写爬虫(四)多线程实现数据爬取
- 垃圾邮件过滤器 python简单实现
- 下载并遍历 names.txt 文件,输出长度最长的回文人名。
- install and upgrade scrapy
- Scrapy的架构介绍
- Centos6 编译安装Python
- 使用Python生成Excel格式的图片
- 让Python文件也可以当bat文件运行
- [Python]推算数独
- Python中zip()函数用法举例
- Python中map()函数浅析
- 设计模式之创建型模式 - 特别的变量问题
- Python将excel导入到mysql中
- Python在CAM软件Genesis2000中的应用
- 使用Shiboken为C++和Qt库创建Python绑定
- FREEBASIC 编译可被python调用的dll函数示例