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进阶教程之循环对象
Aug 30 Python
Python实现CET查分的方法
Mar 10 Python
python中numpy包使用教程之数组和相关操作详解
Jul 30 Python
python 中if else 语句的作用及示例代码
Mar 05 Python
Python运行不显示DOS窗口的解决方法
Oct 22 Python
分享Python切分字符串的一个不错方法
Dec 14 Python
Python功能点实现:函数级/代码块级计时器
Jan 02 Python
opencv实现静态手势识别 opencv实现剪刀石头布游戏
Jan 22 Python
Python字符串处理的8招秘籍(小结)
Aug 13 Python
Python实现的爬取豆瓣电影信息功能案例
Sep 15 Python
使用pytorch和torchtext进行文本分类的实例
Jan 08 Python
keras和tensorflow使用fit_generator 批次训练操作
Jul 03 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
Ajax+PHP边学边练 之五 图片处理
2009/12/03 PHP
php for 循环使用的简单实例
2016/06/02 PHP
thinkPHP框架实现图像裁剪、缩放、加水印的方法
2017/03/14 PHP
Windows下php+mysql5.7配置教程
2017/05/16 PHP
PHP实现基于图的深度优先遍历输出1,2,3...n的全排列功能
2017/11/10 PHP
ExtJS PropertyGrid中使用Combobox选择值问题
2010/06/13 Javascript
JS数组去重与取重的示例代码
2014/01/24 Javascript
js跳转页面方法实现汇总
2014/02/11 Javascript
jquery mobile的触控点击事件会多次触发问题的解决方法
2014/05/08 Javascript
深入理解Javascript中this的作用域
2014/08/12 Javascript
node-webkit打包成exe文件被360误报木马的解决方法
2015/03/11 Javascript
js实现基于正则表达式的轻量提示插件
2015/08/29 Javascript
点评js异步加载的4种方式
2015/12/22 Javascript
jQuery中的100个技巧汇总
2016/12/15 Javascript
微信小程序本地缓存数据增删改查实例详解
2017/05/24 Javascript
nodejs搭建本地服务器并访问文件操作示例
2019/05/11 NodeJs
js实现固定区域内的不重叠随机圆
2019/10/24 Javascript
Vue实现商品飞入购物车效果(电商项目)
2019/11/26 Javascript
JavaScript中常用的3种弹出提示框(alert、confirm、prompt)
2020/11/10 Javascript
零基础学Python(一)Python环境安装
2014/08/20 Python
实现python版本的按任意键继续/退出
2016/09/26 Python
Python使用回溯法子集树模板获取最长公共子序列(LCS)的方法
2017/09/08 Python
Python 读取图片文件为矩阵和保存矩阵为图片的方法
2018/04/27 Python
浅谈PYTHON 关于文件的操作
2019/03/19 Python
Python插件机制实现详解
2020/05/04 Python
如何用 Python 制作一个迷宫游戏
2021/02/25 Python
css3学习心得分享
2013/08/19 HTML / CSS
size?瑞典:英国伦敦的球鞋精品店
2018/03/01 全球购物
Clarria化妆品官方网站:购买天然和有机化妆品系列
2018/04/08 全球购物
什么是网络协议
2016/04/07 面试题
端午节粽子促销活动方案
2014/02/02 职场文书
校庆接待方案
2014/03/18 职场文书
活动总结的格式
2014/05/07 职场文书
美术学专业求职信
2014/07/23 职场文书
2014年检察院个人工作总结
2014/12/09 职场文书
WINDOWS 64位 下安装配置mysql8.0.25最详细的教程
2022/03/22 MySQL