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 struct.unpack
Sep 06 Python
python类型强制转换long to int的代码
Feb 10 Python
python学习教程之Numpy和Pandas的使用
Sep 11 Python
Python lambda函数基本用法实例分析
Mar 16 Python
Python(Django)项目与Apache的管理交互的方法
May 16 Python
18个Python脚本可加速你的编码速度(提示和技巧)
Oct 17 Python
python使用yield压平嵌套字典的超简单方法
Nov 02 Python
python 递归调用返回None的问题及解决方法
Mar 16 Python
python3 通过 pybind11 使用Eigen加速代码的步骤详解
Dec 07 Python
python实现socket简单通信的示例代码
Apr 13 Python
Pandas 稀疏数据结构的实现
Jul 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
Flash空降上海 化身大魔王接受挑战
2020/03/02 星际争霸
图片存储与浏览一例(Linux+Apache+PHP+MySQL)
2006/10/09 PHP
PHP批量删除、清除UTF-8文件BOM头的代码实例
2014/04/14 PHP
php使用iconv中文截断问题的解决方法
2015/02/11 PHP
php搜索文件程序分享
2015/10/30 PHP
phpQuery采集网页实现代码实例
2020/04/02 PHP
js实现具有高亮显示效果的多级菜单代码
2015/09/01 Javascript
封装获取dom元素的简单实例
2016/07/08 Javascript
Angular的$http的ajax的请求操作(推荐)
2017/01/10 Javascript
jQuery仿IOS弹出框插件
2017/02/18 Javascript
Vue组件之Tooltip的示例代码
2017/10/18 Javascript
jQuery ajax读取本地json文件的实例
2017/10/31 jQuery
JS canvas绘制五子棋的棋盘
2020/05/28 Javascript
Layui tree 下拉菜单树的实例代码
2019/09/21 Javascript
bootstrap-paginator服务器端分页使用方法详解
2020/02/13 Javascript
vue实现简单计算商品价格
2020/09/14 Javascript
[08:02]DOTA2牵红线 zhou神抱得美人归
2014/03/22 DOTA
[51:22]Fnatic vs IG 2018国际邀请赛小组赛BO2 第一场 8.17
2018/08/18 DOTA
[08:54]DOTA2-DPC中国联赛 正赛 Aster vs LBZS 选手采访
2021/03/11 DOTA
python获取豆瓣电影简介代码分享
2014/01/16 Python
python matplotlib折线图样式实现过程
2019/11/04 Python
Python logging日志库空间不足问题解决
2020/09/14 Python
python3实现语音转文字(语音识别)和文字转语音(语音合成)
2020/10/14 Python
Python实现手势识别
2020/10/21 Python
CSS3 Notes: -webkit-box-reflect实现倒影的实例
2016/12/08 HTML / CSS
Html5跳转到APP指定页面的实现
2020/01/14 HTML / CSS
创造美妙香氛体验:Aera扩散器和香水
2018/11/25 全球购物
英语专业学生个人求职信范文
2014/01/06 职场文书
节约用水演讲稿
2014/05/21 职场文书
党支部先进事迹材料
2014/12/24 职场文书
长辈生日祝福语大全(72句)
2019/08/09 职场文书
sql通过日期判断年龄函数的示例代码
2021/07/16 SQL Server
基于MySql验证的vsftpd虚拟用户
2021/11/07 MySQL
MySql分区类型及创建分区的方法
2022/04/13 MySQL
Redis实现分布式锁的五种方法详解
2022/06/14 Redis
如何利用python创作字符画
2022/06/25 Python