• 使用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()方法效果一样。

  • 相关阅读:
    微信小程序获取用户绑定手机号码完整版
    SQL读取当天的数据
    Android 百度离线地图(由apk文件转入手机内部存储)
    解决windows家庭版系统不支持远程桌面功能问题
    微信小程序携参跳转页面
    微信小程序 websocket 封装
    微信小程序HTTP请求封装
    Ionic项目打包Android在9版本以上不能进行HTTP通信问题
    Ionic 使用 MQTT
    Ionic HTTP 请求
  • 原文地址:https://www.cnblogs.com/aaronhoo/p/13181169.html
Copyright © 2020-2023  润新知