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

2小時內可以學會Python的基本編程概念和技能。 1.學習變量和數據類型,2.掌握控制流(條件語句和循環),3.理解函數的定義和使用,4.通過簡單示例和代碼片段快速上手Python編程。

Python在web開發、數據科學、機器學習、自動化和腳本編寫等領域有廣泛應用。 1)在web開發中,Django和Flask框架簡化了開發過程。 2)數據科學和機器學習領域,NumPy、Pandas、Scikit-learn和TensorFlow庫提供了強大支持。 3)自動化和腳本編寫方面,Python適用於自動化測試和系統管理等任務。

兩小時內可以學到Python的基礎知識。 1.學習變量和數據類型,2.掌握控制結構如if語句和循環,3.了解函數的定義和使用。這些將幫助你開始編寫簡單的Python程序。

如何在10小時內教計算機小白編程基礎?如果你只有10個小時來教計算機小白一些編程知識,你會選擇教些什麼�...

使用FiddlerEverywhere進行中間人讀取時如何避免被檢測到當你使用FiddlerEverywhere...

Python3.6環境下加載Pickle文件報錯:ModuleNotFoundError:Nomodulenamed...

如何解決jieba分詞在景區評論分析中的問題?當我們在進行景區評論分析時,往往會使用jieba分詞工具來處理文�...

如何使用正則表達式匹配到第一個閉合標籤就停止?在處理HTML或其他標記語言時,常常需要使用正則表達式來�...


熱AI工具

Undresser.AI Undress
人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover
用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool
免費脫衣圖片

Clothoff.io
AI脫衣器

AI Hentai Generator
免費產生 AI 無盡。

熱門文章

熱工具

ZendStudio 13.5.1 Mac
強大的PHP整合開發環境

Atom編輯器mac版下載
最受歡迎的的開源編輯器

Safe Exam Browser
Safe Exam Browser是一個安全的瀏覽器環境,安全地進行線上考試。該軟體將任何電腦變成一個安全的工作站。它控制對任何實用工具的訪問,並防止學生使用未經授權的資源。

SublimeText3 Linux新版
SublimeText3 Linux最新版

SublimeText3漢化版
中文版,非常好用