簡単な紹介
以前の計画によると、この一つの小さな仲間は説明:(1)マルチモジュールロギングの使用を、(2)ロギングモジュールファイル、(3)自分のパッケージのログ(ログ)クラス。ログの小さなパートナーを有することができる二つのサブ長さが彼女を導入する理由を疑問があるでしょうか???ログは、ソフトウェアの操作の設定ファイルやイベントログとメッセージログに分けることができ、イベントを記録するためのシステムを記録するために非常に重要であるためです。データ処理、追跡の歴史の中で重要な役割を持っており、問題を診断するためのシステム、ソフトウェア、およびその他の活動を理解し、開発やテストシステムソフトウェアプロセスに問題がある、私たちが最初に考えた彼女--loggingです。;少女90の後、彼女が披露するのが大好き、披露愛する人々は、人々が名付けられていたに達している、ガチョウ「空は翼の痕跡を残していないが、私は飛行している」:彼女は、タゴールは言っ好きではないこと音のレベル。まあ、面白い誰もが幸せに、私たちは、今日の話題の入力を開始することができます。
マルチモジュールロギング
1、親モジュールfatherModule.py:
図2に示すように、サブモジュールのsonModule.py。
3、演算結果、および制御出力ログファイルのlog.txt:
まず、親モジュールを直接することができ、再設定する必要はありません、結果のオブジェクトが同じである「(fatherModule「)のgetLoggerによってインタプリタプロセス内の他の場所でそれが設定されていることを、あなたがすることができ、および」logger'fatherModuleを定義します使用しています。サブロガー定義ロガー、
親ロガーが共有され、構成定義することができる、いわゆるサンズロガーは、任意「fatherModule」に、名前によって識別され、例えば「fatherModule.son」、そのサブロガーロガーが開始されます。
实际开发一个application,首先可以通过logging配置文件编写好这个application所对应的配置,可以生成一个根logger,如'PythonAPP',然后在主函数中通过fileConfig加载logging配置,接着在application的其他地方、不同的模块中,可以使用根logger的子logger,
如'PythonAPP.Core','PythonAPP.Web'来进行log,而不需要反复的定义和配置各个模块的logger。
4、参考代码
fatherModule.py文件:
1 # coding=utf-8 2 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 3 4 # 2.注释:包括记录创建时间,创建人,项目名称。 5 ''' 6 Created on 2019-5-24 7 @author: 北京-宏哥 8 Project:学习和使用python的logging日志模块-多模块使用logging 9 ''' 10 # 3.导入模块 11 import logging 12 import sonModule 13 logger = logging.getLogger("fatherModule") 14 logger.setLevel(level = logging.INFO) 15 handler = logging.FileHandler("log.txt") 16 handler.setLevel(logging.INFO) 17 formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') 18 handler.setFormatter(formatter) 19 20 console = logging.StreamHandler() 21 console.setLevel(logging.INFO) 22 console.setFormatter(formatter) 23 24 logger.addHandler(handler) 25 logger.addHandler(console) 26 27 28 logger.info("creating an instance of sonModule.sonModuleClass") 29 a = sonModule.SonModuleClass() 30 logger.info("calling sonModule.sonModuleClass.doSomething") 31 a.doSomething() 32 logger.info("done with sonModule.sonModuleClass.doSomething") 33 logger.info("calling sonModule.some_function") 34 sonModule.som_function() 35 logger.info("done with sonModule.some_function")
sonModule.py文件:
1 # coding=utf-8 2 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 3 4 # 2.注释:包括记录创建时间,创建人,项目名称。 5 ''' 6 Created on 2019-5-24 7 @author: 北京-宏哥 8 Project:学习和使用python的logging日志模块-多模块使用logging 9 ''' 10 # 3.导入模块 11 import logging 12 13 module_logger = logging.getLogger("fatherModule.son") 14 class SonModuleClass(object): 15 def __init__(self): 16 self.logger = logging.getLogger("fatherModule.son.module") 17 self.logger.info("creating an instance in SonModuleClass") 18 def doSomething(self): 19 self.logger.info("do something in SonModule") 20 a = [] 21 a.append(1) 22 self.logger.debug("list a = " + str(a)) 23 self.logger.info("finish something in SonModuleClass") 24 25 def som_function(): 26 module_logger.info("call function some_function")
文件配置logging模块
1、通过logging.config模块配置日志构造信息
logger.conf文件:
[loggers] keys = root, example01, example02 [logger_root] level = DEBUG handlers = hand01, hand02 [logger_example01] handlers = hand01, hand02 qualname = example01 propagate = 0 [logger_example02] handlers = hand01, hand03 qualname = example02 propagate = 0 [handlers] keys = hand01, hand02, hand03 [handler_hand01] class = StreamHandler level = INFO formatter = form01 args=(sys.stdout, ) [handler_hand02] class = FileHandler level = DEBUG formatter = form01 args = ('log/test_case_log.log', 'a') [handler_hand03] class = handlers.RotatingFileHandler level = INFO formatter = form01 args = ('log/test_case_log.log', 'a', 10*1024*1024,3) [formatters] keys = form01, form02 [formatter_form01] format = %(asctime)s-%(filename)s-[line:%(lineno)d]-%(levelname)s-[LogInfoMessage]: %(message)s datefmt = %a, %d %b %Y %H:%M:%S [formatter_form02] format = %(name)-12s: %(levelname)-8s-[日志信息]: %(message)s datefmt = %a, %d %b %Y %H:%M:%S
一、实例:
1、实例代码
2、运行结果:
3、参考代码:
# coding=utf-8 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 # 2.注释:包括记录创建时间,创建人,项目名称。 ''' Created on 2019-5-27 @author: 北京-宏哥 Project:学习和使用python的logging日志模块-多模块使用logging ''' # 3.导入模块 import logging import logging.config logging.config.fileConfig("logger.conf") logger = logging.getLogger("example01") logger.debug('This is debug message') logger.info('This is info message') logger.warning('This is warning message')
二、实例
1、实例代码
2、运行结果
3、参考代码:
# coding=utf-8 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 # 2.注释:包括记录创建时间,创建人,项目名称。 ''' Created on 2019-5-24 @author: 北京-宏哥 Project:学习和使用python的logging日志模块-多模块使用logging ''' # 3.导入模块 import logging import logging.config logging.config.fileConfig("logger.conf") logger = logging.getLogger("example02") logger.debug('This is debug message') logger.info('This is info message') logger.warning('This is warning message')
2、通过JSON文件配置
json配置文件:
{ "version":1, "disable_existing_loggers":false, "formatters":{ "simple":{ "format":"%(asctime)s - %(name)s - %(levelname)s - %(message)s" } }, "handlers":{ "console":{ "class":"logging.StreamHandler", "level":"DEBUG", "formatter":"simple", "stream":"ext://sys.stdout" }, "info_file_handler":{ "class":"logging.handlers.RotatingFileHandler", "level":"INFO", "formatter":"simple", "filename":"info.log", "maxBytes":"10485760", "backupCount":20, "encoding":"utf8" }, "error_file_handler":{ "class":"logging.handlers.RotatingFileHandler", "level":"ERROR", "formatter":"simple", "filename":"errors.log", "maxBytes":10485760, "backupCount":20, "encoding":"utf8" } }, "loggers":{ "my_module":{ "level":"ERROR", "handlers":["info_file_handler"], "propagate":"no" } }, "root":{ "level":"INFO", "handlers":["console","info_file_handler","error_file_handler"] } }
1、通过JSON加载配置文件,然后通过logging.dictConfig配置logging:
2、运行结果:
3、参考代码:
1 import json
2 import logging.config
3 import os
4
5 def setup_logging(default_path = "logging.json",default_level = logging.INFO,env_key = "LOG_CFG"):
6 path = default_path
7 value = os.getenv(env_key,None) 8 if value: 9 path = value 10 if os.path.exists(path): 11 with open(path,"r") as f: 12 config = json.load(f) 13 logging.config.dictConfig(config) 14 else: 15 logging.basicConfig(level = default_level) 16 17 def func(): 18 logging.info("start func") 19 20 logging.info("exec func") 21 22 logging.info("end func") 23 24 if __name__ == "__main__": 25 setup_logging(default_path = "logging.json") 26 func()
3、通过YAML文件配置
1、首先要导入yaml模块,输入命令 python2: pip install yaml python3:pip install pyyaml
2、通过YAML文件进行配置,比JSON看起来更加简介明了:
logging.yaml文件:
version: 1 disable_existing_loggers: False formatters: simple: format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s" handlers: console: class: logging.StreamHandler level: DEBUG formatter: simple stream: ext://sys.stdout info_file_handler: class: logging.handlers.RotatingFileHandler level: INFO formatter: simple filename: info.log maxBytes: 10485760 backupCount: 20 encoding: utf8 error_file_handler: class: logging.handlers.RotatingFileHandler level: ERROR formatter: simple filename: errors.log maxBytes: 10485760 backupCount: 20 encoding: utf8 loggers: my_module: level: ERROR handlers: [info_file_handler] propagate: no root: level: INFO handlers: [console,info_file_handler,error_file_handler]
3、通过YAML加载配置文件,然后通过logging.dictConfig配置logging:
4、运行结果:
5、参考代码:
# coding=utf-8 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 # 2.注释:包括记录创建时间,创建人,项目名称。 ''' Created on 2019-5-24 @author: 北京-宏哥 Project:学习和使用python的logging日志模块-yaml文件配置logging ''' # 3.导入模块 import yaml import logging.config import os def setup_logging(default_path = "logging.yaml",default_level = logging.INFO,env_key = "LOG_CFG"): path = default_path value = os.getenv(env_key,None) if value: path = value if os.path.exists(path): with open(path,"r") as f: config = yaml.load(f) logging.config.dictConfig(config) else: logging.basicConfig(level = default_level) def func(): logging.info("start func") logging.info("exec func") logging.info("end func") if __name__ == "__main__": setup_logging(default_path = "logging.yaml") func()
注意:配置文件中“disable_existing_loggers” 参数设置为 False;如果不设置为False,创建了 logger,然后你又在加载日志配置文件之前就导入了模块。logging.fileConfig 与 logging.dictConfig 默认情况下会使得已经存在的 logger 失效。那么,这些配置信息就不会应用到你的 Logger 上。“disable_existing_loggers” = False解决了这个问题
自己封装一个logging类
1、实例代码:
2、运行结果:
3、参考代码:
1 # coding=utf-8 2 # 1.先设置编码,utf-8可支持中英文,如上,一般放在第一行 3 4 # 2.注释:包括记录创建时间,创建人,项目名称。 5 ''' 6 Created on 2019-5-27 7 @author: 北京-宏哥 8 Project:学习和使用python的logging日志模块-自己封装logging 9 ''' 10 # 3.导入模块 11 import logging 12 class Log(object): 13 def __init__(self, name=__name__, path='mylog.log', level='DEBUG'): 14 self.__name = name 15 self.__path = path 16 self.__level = level 17 self.__logger = logging.getLogger(self.__name) 18 self.__logger.setLevel(self.__level) 19 20 def __ini_handler(self): 21 """初始化handler""" 22 stream_handler = logging.StreamHandler() 23 file_handler = logging.FileHandler(self.__path, encoding='utf-8') 24 return stream_handler, file_handler 25 26 def __set_handler(self, stream_handler, file_handler, level='DEBUG'): 27 """设置handler级别并添加到logger收集器""" 28 stream_handler.setLevel(level) 29 file_handler.setLevel(level) 30 self.__logger.addHandler(stream_handler) 31 self.__logger.addHandler(file_handler) 32 33 def __set_formatter(self, stream_handler, file_handler): 34 """设置日志输出格式""" 35 formatter = logging.Formatter('%(asctime)s-%(name)s-%(filename)s-[line:%(lineno)d]' 36 '-%(levelname)s-[日志信息]: %(message)s', 37 datefmt='%a, %d %b %Y %H:%M:%S') 38 stream_handler.setFormatter(formatter) 39 file_handler.setFormatter(formatter) 40 41 def __close_handler(self, stream_handler, file_handler): 42 """关闭handler""" 43 stream_handler.close() 44 file_handler.close() 45 46 @property 47 def Logger(self): 48 """构造收集器,返回looger""" 49 stream_handler, file_handler = self.__ini_handler() 50 self.__set_handler(stream_handler, file_handler) 51 self.__set_formatter(stream_handler, file_handler) 52 self.__close_handler(stream_handler, file_handler) 53 return self.__logger 54 55 56 if __name__ == '__main__': 57 log = Log(__name__, 'file.log') 58 logger = log.Logger 59 logger.debug('I am a debug message') 60 logger.info('I am a info message') 61 logger.warning('I am a warning message') 62 logger.error('I am a error message') 63 logger.critical('I am a critical message')
小结
1、在yaml文件配置logging的时候,会有个报警信息。有代码洁癖的人,可以处理一下
2、是什么原因造成上面的告警呢???是因为:YAML 5.1版本后弃用了yaml.load(file)这个用法,因为觉得很不安全,5.1版本之后就修改了需要指定Loader,通过默认加载器(FullLoader)禁止执行任意函数,该load函数也变得更加安全。
3、解决办法:
不用改很多代码 加一句就行了 在yaml.load(f, Loader=yaml.FullLoader)
加上 Loader=yaml.FullLoader 就行了。这里要注意的是L要大写的,否则会报错的。
4、加上以后,看一下运行结果:
最后给大家留个彩蛋:文章中有一处bug,会影响运行结果而报错,聪明的你,可以找到吗???嘿嘿!!!欢迎互动和留言