python 的log格式

5 篇文章 0 订阅
  • log.py
import logging
import logging.handlers
import os

def init_log(log_path, level=logging.INFO, when="D", backup=7,
             format='%(asctime)s:[%(levelname)s][%(threadName)s] %(filename)s:%(lineno)d --> %(message)s',
             datefmt='%Y-%m-%d %H:%M:%S'):
    """
    init_log - initialize log module

    Args:
      log_path      - Log file path prefix.
                      Log data will go to two files: log_path.log and log_path.log.wf
                      Any non-exist parent directories will be created automatically
      level         - msg above the level will be displayed
                      DEBUG < INFO < WARNING < ERROR < CRITICAL
                      the default value is logging.INFO
      when          - how to split the log file by time interval
                      'S' : Seconds
                      'M' : Minutes
                      'H' : Hours
                      'D' : Days
                      'W' : Week day
                      default value: 'D'
      format        - format of the log
                      default format:
                      %(levelname)s: %(asctime)s: %(filename)s:%(lineno)d * %(thread)d %(message)s
                      INFO: 12-09 18:02:42: log.py:40 * 139814749787872 HELLO WORLD
      backup        - how many backup file to keep
                      default value: 7

    Raises:
        OSError: fail to create log directories
        IOError: fail to open log file
    """
    formatter = logging.Formatter(format, datefmt)
    logger = logging.getLogger()
    logger.setLevel(level)

    # add console log
    consoleHandler = logging.StreamHandler()
    consoleHandler.setLevel(level)
    consoleHandler.setFormatter(formatter)
    logger.addHandler(consoleHandler)
        
    log_dir = os.path.dirname(log_path)
    if not os.path.isdir(log_dir):
        os.makedirs(log_dir)

    handler = logging.handlers.TimedRotatingFileHandler(log_path + '.log',
                                                        when=when,
                                                        backupCount=backup)
    handler.setLevel(level)
    handler.setFormatter(formatter)
    logger.addHandler(handler)

 

 

  • 你可以把上面的代码拷贝到自己的项目中。在程序初始化时,调用init_log即可使日志打印符合规范
import log
def main():
    log.init_log("./log/my_program")  # 日志保存到./log/my_program.log和./log/my_program.log.wf,按天切割,保留7天
    logging.info("Hello World!!!")

参考

*logging — Logging facility for Python

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
Python中的logging模块是一种用于记录和输出日志信息的工具。通过引入logging模块,可以在代码中添加日志记录,以便于在程序运行时查看和分析程序的执行情况。 在使用logging模块时,可以设置不同的日志级别,包括DEBUG、INFO、WARNING、ERROR和CRITICAL等级别。默认情况下,日志级别为WARNING,只会输出WARNING级别及以上的日志信息。 可以通过配置logging模块的basicConfig函数来设置日志的输出方式,包括输出到控制台或者输出到文件。在输出到文件时,可以指定日志文件的名称、日志级别、文件打开模式和日志格式等参数。 下面是一个示例代码,展示了如何使用logging模块输出日志到文件,并设置日志的级别和格式: ```python import logging # 设置日志文件名 filename = "{}.log".format(__file__) # 设置***志格式 fmt = "%(asctime)s - %(filename)s[line:%(lineno)d - %(levelname)s: %(message)s" # 配置logging模块 logging.basicConfig( level=logging.DEBUG, filename=filename, filemode="w", format=fmt ) # 输出***志信息 logging.info("info") logging.debug("debug") logging.warning("warning") logging.error("error") logging.critical("critical") ``` 通过以上代码,可以将不同级别的日志信息输出到指定的日志文件中,并且在日志信息中包含了时间、文件名、行号、日志级别和具体的日志内容等信息。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *2* *3* [Python编程:logging模块的简单使用](https://blog.csdn.net/mouday/article/details/80760343)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 100%"] [ .reference_list ]
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值