zoukankan      html  css  js  c++  java
  • 使用logging模块记录日志

    import logging
    from logging.handlers import RotatingFileHandler
    def setlog():
       #此处为对root logger进行设置,应在程序最开始的地方调用 logging.basicConfig(level
    =log_config.get("LOG_LEVEL", logging.INFO))
       #此处设置日志文件的位置 file_log_handler
    = RotatingFileHandler('/workspace/project_name/log/app.log', maxBytes=1024*1024*100, backupCount=15, encoding="utf-8") #设置日志格式
       formatter
    = logging.Formatter( '[' + '%(levelname)s' + '],' + 'at:%(asctime)s,function:%(funcName)s(),line:%(lineno)d,%(message)s') file_log_handler.setFormatter(formatter)
       #为root logger设置handler logging.getLogger().addHandler(file_log_handler)

    其他方法:

    config.py:

    import os
    from datetime import datetime
    
    moduleName='test_module'
    BASE_DIR=os.path.join(os.path.dirname(__file__).split(moduleName)[0],moduleName)
    
    LOG_DIR=os.path.join(BASE_DIR,'log')
    #日志文件以日志产生的日期来命名 myapp_log_file
    =os.path.join(LOG_DIR,datetime.strftime(datetime.now(), "%Y-%m-%d")+".log")

    mylogger.py:

    import logging
    from config import myapp_log_file,moduleName
    
    #设置将日志写入指定文件 fh
    = logging.FileHandler(myapp_log_file)
    #设置每条日志的格式为:日志等级,at:时刻,calling 方法名(),line:logger所在行号,用户自定义信息 fh.setFormatter(logging.Formatter(
    '%(levelname)s,at:%(asctime)s,calling %(funcName)s(),line:%(lineno)d,%(message)s')) logger = logging.getLogger(moduleName) logger.addHandler(fh)
    #设置日志的最低等级,调用最低等级(含)之上的日志方法才会生效,debug<info<warning<error<critial
    logger.setLevel(level=logging.DEBUG)
    def test():   logger.info('info')   logger.exception('exception occurred.',exc_info=False)      logger.exception('error info here.') if __name__=='__main__':      test()

     执行test()方法,将会在test_module/log目录下自动创建2020-06-23.log,并写入:

    INFO,at:2020-06-23 11:24:20,679,calling test(),line:17,info
    ERROR,at:2020-06-23 11:24:20,679,calling test(),line:18,exception occurred.
    ERROR,at:2020-06-23 11:24:20,679,calling test(),line:19,error info here.

    可以发现,logger.exception()和logger.error()都会产生一条error级别日志信息,其中exception()方法若设置exc_info=False(默认为True表示自动记录异常信息,若无异常则会输出NoneType:None)之后与error()方法效果一样。

  • 相关阅读:
    hdu1238 Substrings
    CCF试题:高速公路(Targin)
    hdu 1269 迷宫城堡(Targin算法)
    hdu 1253 胜利大逃亡
    NYOJ 55 懒省事的小明
    HDU 1024 Max Sum Plus Plus
    HDU 1087 Super Jumping! Jumping! Jumping!
    HDU 1257 最少拦截系统
    HDU 1069 Monkey and Banana
    HDU 1104 Remainder
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/13181169.html
Copyright © 2011-2022 走看看