python实现的系统实用log类实例


Posted in Python onJune 30, 2015

本文实例讲述了python实现的系统实用log类。分享给大家供大家参考。具体如下:

每个系统都必不可少会需要一个log类,方便了解系统的运行状况和排错,python本身已经提供了一个logger了,很强大,只要稍微封装一下就可以放到自己的系统了,下面是我自己的log类

文件名:logger.py

"""This module takes care of the logging
logger helps in creating a logging system for the application 
Logging is initialised by function LoggerInit.
"""
import logging
import os
import sys
class logger(object):
  """Class provides methods to perform logging."""
  m_logger = None
  def __init__(self, opts, logfile):
    """Set the default logging path."""
    self.opts = opts
    self.myname = 'dxscs'
    self.logdir = '.'
    self.logfile = logfile
    self.filename = os.path.join(self.logdir, self.logfile)
  def loginit(self):
    """Calls function LoggerInit to start initialising the logging system."""
    logdir = os.path.normpath(os.path.expanduser(self.logdir))
    self.logfilename = os.path.normpath(os.path.expanduser(self.filename))
    if not os.path.isdir(logdir):
      try:
        os.mkdir(logdir)
      except OSError, e:
        msg = ('(%s)'%e)
        print msg
        sys.exit(1)
    self.logger_init(self.myname)
  def logger_init(self, loggername):
    """Initialise the logging system.
    This includes logging to console and a file. By default, console prints
    messages of level WARN and above and file prints level INFO and above.
    In DEBUG mode (-D command line option) prints messages of level DEBUG
    and above to both console and file.
    Args:
     loggername: String - Name of the application printed along with the log
     message.
    """
    fileformat = '[%(asctime)s] %(name)s: [%(filename)s: %(lineno)d]: %(levelname)-8s: %(message)s'
    logger.m_logger = logging.getLogger(loggername)
    logger.m_logger.setLevel(logging.INFO)
    self.console = logging.StreamHandler()
    self.console.setLevel(logging.CRITICAL)
    consformat = logging.Formatter(fileformat)
    self.console.setFormatter(consformat)
    self.filelog = logging.FileHandler(filename=self.logfilename, mode='w+')
    self.filelog.setLevel(logging.INFO)
    self.filelog.setFormatter(consformat)
    logger.m_logger.addHandler(self.filelog)
    logger.m_logger.addHandler(self.console)
    if self.opts['debug'] == True:
      self.console.setLevel(logging.DEBUG)
      self.filelog.setLevel(logging.DEBUG)
      logger.m_logger.setLevel(logging.DEBUG)
    if not self.opts['nofork']:
      self.console.setLevel(logging.WARN)
  def logstop(self):
    """Shutdown logging process."""
    logging.shutdown()
#test    
if __name__ == '__main__':
  #debug mode & not in daemon
  opts = {'debug':True,'nofork':True}
  log = logger(opts, 'dxscs_source.log')
  log.loginit()
  log.m_logger.info('hello,world')

执行结果:

终端和文件中都显示有:[2012-09-06 16:56:01,498] dxscs: [logger.py: 88]: INFO    : hello,world

如果只需要显示在文件中可以将debug和nofork选项都置为false

希望本文所述对大家的Python程序设计有所帮助。

Python 相关文章推荐
python访问纯真IP数据库的代码
May 19 Python
python+selenium识别验证码并登录的示例代码
Dec 21 Python
python调用opencv实现猫脸检测功能
Jan 15 Python
详解Python基础random模块随机数的生成
Mar 23 Python
Python flask框架post接口调用示例
Jul 03 Python
Python箱型图绘制与特征值获取过程解析
Oct 22 Python
python 在右键菜单中加入复制目标文件的有效存放路径(单斜杠或者双反斜杠)
Apr 08 Python
Python自省及反射原理实例详解
Jul 06 Python
Python 列表推导式需要注意的地方
Oct 23 Python
Flask-SocketIO服务端安装及使用代码示例
Nov 26 Python
Python 中如何使用 virtualenv 管理虚拟环境
Jan 21 Python
用python基于appium模块开发一个自动收取能量的小助手
Sep 25 Python
python实现在windows服务中新建进程的方法
Jun 30 #Python
python实现线程池的方法
Jun 30 #Python
python实现的简单FTP上传下载文件实例
Jun 30 #Python
编写Python CGI脚本的教程
Jun 29 #Python
Python访问纯真IP数据库脚本分享
Jun 29 #Python
Python实现把数字转换成中文
Jun 29 #Python
Python中if __name__ == '__main__'作用解析
Jun 29 #Python
You might like
用Apache反向代理设置对外的WWW和文件服务器
2006/10/09 PHP
编写安全 PHP应用程序的七个习惯深入分析
2013/06/08 PHP
Yii2.0中使用js异步删除示例
2017/03/10 PHP
Laravel中使用Queue的最基本操作教程
2017/12/27 PHP
jQuery查询数据返回object和字符串影响原因是什么
2013/08/09 Javascript
jQuery Mobile的loading对话框显示/隐藏方法分享
2013/11/26 Javascript
浅谈JavaScript对象与继承
2016/07/10 Javascript
JavaScript优化以及前段开发小技巧
2017/02/02 Javascript
网页中的图片查看器viewjs使用方法
2017/07/11 Javascript
为jquery的ajax请求添加超时timeout时间的操作方法
2018/09/04 jQuery
Servlet返回的数据js解析2种方法
2019/12/12 Javascript
JavaScript 如何计算文本的行数的实现
2020/09/14 Javascript
[01:09:50]VP vs Pain 2018国际邀请赛小组赛BO2 第二场
2018/08/20 DOTA
Python常用正则表达式符号浅析
2014/08/13 Python
在Python中操作时间之mktime()方法的使用教程
2015/05/22 Python
Python中列表元素转为数字的方法分析
2016/06/14 Python
详解Python网络框架Django和Scrapy安装指南
2019/04/01 Python
pandas dataframe的合并实现(append, merge, concat)
2019/06/24 Python
利用python list完成最简单的DB连接池方法
2019/08/09 Python
python多线程使用方法实例详解
2019/12/30 Python
Python中的整除和取模实例
2020/06/03 Python
PyCharm2020.1.2社区版安装,配置及使用教程详解(Windows)
2020/08/07 Python
Python中logging日志的四个等级和使用
2020/11/17 Python
CSS3 @keyframes简单动画实现
2018/02/24 HTML / CSS
IE10 Error.stack 让脚本调试更加方便快捷
2013/04/22 HTML / CSS
英国领先的在线鱼贩:The Fish Society
2020/08/12 全球购物
行政专员工作职责
2013/12/22 职场文书
海南地接欢迎词
2014/01/14 职场文书
大学生在校学习的自我评价
2014/02/18 职场文书
美术教师岗位职责
2014/03/18 职场文书
县政协领导班子群众路线教育实践活动四风问题整改方案
2014/10/26 职场文书
2015大学生实训报告
2014/11/05 职场文书
2014幼儿园中班工作总结
2014/11/10 职场文书
毕业生自荐材料范文
2014/12/30 职场文书
挂职锻炼个人总结
2015/03/05 职场文书
Android实现图片九宫格
2022/06/28 Java/Android