您好,欢迎来到三六零分类信息网!老站,搜索引擎当天收录,欢迎发信息

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

2024/2/25 6:23:46发布17次查看
本文实例讲述了python实现的系统实用log类。分享给大家供大家参考。具体如下:
每个系统都必不可少会需要一个log类,方便了解系统的运行状况和排错,python本身已经提供了一个logger了,很强大,只要稍微封装一下就可以放到自己的系统了,下面是我自己的log类
文件名:logger.py
this module takes care of the logginglogger helps in creating a logging system for the application logging is initialised by function loggerinit.import loggingimport osimport sysclass 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程序设计有所帮助。
该用户其它信息

VIP推荐

免费发布信息,免费发布B2B信息网站平台 - 三六零分类信息网 沪ICP备09012988号-2
企业名录 Product