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

 更新时间:2015年06月30日 10:07:03   作者:liujian0616  
这篇文章主要介绍了python实现的系统实用log类,实例分析了Python基于logging模块实现日志类的相关技巧,需要的朋友可以参考下

本文实例讲述了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程序设计有所帮助。

相关文章

  • 删除PyCharm解释器的方法步骤

    删除PyCharm解释器的方法步骤

    这篇文章主要给大家介绍了关于删除PyCharm解释器的方法步骤,PyCharm解释器是指在PyCharm集成开发环境中用于运行和调试Python代码的解释器,需要的朋友可以参考下
    2023-09-09
  • Python正则表达式re.sub()用法详解

    Python正则表达式re.sub()用法详解

    re.sub用于替换字符串中的匹配项,下面这篇文章主要给大家介绍了关于Python正则表达式re.sub()用法的相关资料,文中通过实例代码以及图文介绍的非常详细,需要的朋友可以参考下
    2022-09-09
  • Python读写常用数据文件的示例详解

    Python读写常用数据文件的示例详解

    Python 提供了多种强大的工具和库,可以轻松实现对各种类型文件的读写操作,本文为大家整理了Python读写常用的那些数据文件的方法,希望对大家有所帮助
    2025-01-01
  • Python判断for循环最后一次的6种方法

    Python判断for循环最后一次的6种方法

    在Python中,通常我们不会直接判断for循环是否正在执行最后一次迭代,因为Python的for循环是基于可迭代对象的,它不知道也不关心迭代的内部状态(比如当前是第几次迭代),但是,我们可以使用一些技巧来间接地实现这个需求,需要的朋友可以参考下
    2025-01-01
  • Python实现打印金字塔图案的方法详解

    Python实现打印金字塔图案的方法详解

    使用简单的 for 循环在 python 中打印模式。第一个外循环用于处理行数, 而内嵌套循环用于处理列数。操作打印语句,可以打印不同的数字图案、字母图案或星形图案。本文将利用这些方法实现打印金字塔图案,需要的可以参考一下
    2022-09-09
  • python读csv文件时指定行为表头或无表头的方法

    python读csv文件时指定行为表头或无表头的方法

    这篇文章主要介绍了python读csv文件时指定行为表头或无表头的方法,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-06-06
  • Python基于tkinter模块实现的改名小工具示例

    Python基于tkinter模块实现的改名小工具示例

    这篇文章主要介绍了Python基于tkinter模块实现的改名小工具,结合实例形式分析了tkinter模块操作文件后缀名的相关实现技巧,需要的朋友可以参考下
    2017-07-07
  • python中子类调用父类函数的方法示例

    python中子类调用父类函数的方法示例

    Python中类的初始化方法是__init__(),因此父类、子类的初始化方法都是这个,下面这篇文章主要给大家介绍了关于python中子类调用父类函数的方法示例,文中通过示例代码介绍的非常详细,需要的朋友可以参考下。
    2017-08-08
  • python高并发异步服务器核心库forkcore使用方法

    python高并发异步服务器核心库forkcore使用方法

    这篇文章主要介绍了python高并发异步服务器核心库forkcore的使用方法,大家参考使用吧
    2013-11-11
  • Flask实现的接口响应中存在中文时接口返回为unicode乱码的解决方法

    Flask实现的接口响应中存在中文时接口返回为unicode乱码的解决方法

    本文给大家分享了新版Flask实现的接口响应中存在中文时接口返回为unicode乱码的解决方法,文中通过代码示例和图文介绍的非常详细,如果有遇到相同问题的朋友,可以参考阅读本文
    2023-11-11

最新评论