python之logging模块的配置和使用

2023-09-05 14:23:22 浏览数 (1)

1 开始吧!

还是不想说太多的话, 这篇主要写一下logging如何使用, 及日志配置文件, 封装日志模块, 多个文件使用日志对象. 关于logging模块的详细参数介绍和使用请看官网

https://docs.python.org/3/library/logging.html?highlight=logging#module-logging

2 简单使用日志模块

代码语言:javascript复制
# -*- coding: utf-8 -*-
# @Author: Mehaei
# @Date: 2023-09-03 00:58:01
# @Last Modified by: Mehaei
# @Last Modified time: 2023-09-03 00:58:15
import logging

logging.debug("test debug")
logging.info("test info")
logging.warning("test warning")
logging.error("test error")
logging.critical("test critical")

"""
输出
WARNING:root:test warning
ERROR:root:test error
CRITICAL:root:test critical
[Finished in 0.1s]
"""

debug和info没有输出日志, 是因为日志等级默认为warning, 将日志输出等级改为debug, 随便修改输出日志的格式

修改配置文件代码为

代码语言:javascript复制
# -*- coding: utf-8 -*-
# @Author: Mehaei
# @Date: 2023-09-03 00:58:01
# @Last Modified by: Mehaei
# @Last Modified time: 2023-09-03 01:07:55
import logging

FORMAT = "%(asctime)s %(name)s %(filename)s[%(lineno)d] %(funcName)s %(levelname)s %(message)s"
logging.basicConfig(format=FORMAT, level=logging.DEBUG)
logging.debug("test debug")
logging.info("test info")
logging.warning("test warning")
logging.error("test error")
logging.critical("test critical")

"""
输出
2023-09-03 01:07:48,140 root short_use.py[11] <module> DEBUG test debug
2023-09-03 01:07:48,140 root short_use.py[12] <module> INFO test info
2023-09-03 01:07:48,140 root short_use.py[13] <module> WARNING test warning
2023-09-03 01:07:48,140 root short_use.py[14] <module> ERROR test error
2023-09-03 01:07:48,140 root short_use.py[15] <module> CRITICAL test critical
[Finished in 0.1s]
"""

这样就实现了最最基本的自定义配置文件等级和格式

3 更高级的日志模块

配置文件参数及格式可以看官网, 这是我写好的配置文件

支持输出到控制台, 和文件中, 也可以同时输出

下面写一个可以在多个文件中使用的logger对象, 其实就是封装一下

log.conf 配置文件

代码语言:javascript复制
[loggers]
keys=root,debug,crawler

[handlers]
keys=rotateFileHandler,consoleHandler

[formatters]
keys=simpleFormatter

[logger_root]
level=DEBUG
handlers=rotateFileHandler,consoleHandler

[logger_debug]
level=DEBUG
handlers=consoleHandler
qualname=debug
propagate=0

[logger_crawler]
level=DEBUG
handlers=rotateFileHandler
qualname=crawler
propagate=0

[handler_consoleHandler]
class=StreamHandler
args=(sys.stdout,)
level=DEBUG
formatter=simpleFormatter

[handler_rotateFileHandler]
class=handlers.RotatingFileHandler
args=('%(log_path)s/log', 'a', 1024 * 1024 * 10, 1, 'utf8')
level=DEBUG
formatter=simpleFormatter

[formatter_simpleFormatter]
format=%(asctime)s %(name)s %(filename)s:%(funcName)s:%(lineno)d %(levelname)s %(message)s

logger.py 文件

代码语言:javascript复制
# -*- coding: utf-8 -*-
# @Author: Mehaei
# @Date: 2023-09-03 00:31:46
# @Last Modified by: Mehaei
# @Last Modified time: 2023-09-03 09:42:14
import os
import logging
import logging.config


def get_logger(name, plog_conf="log.conf", write_log_path="./log"):
    """
    :param name: logger name
    :param plog_conf: logging config file path
    :param write_log_path: write log file path
    """
    if not os.path.exists(write_log_path):
        os.mkdir(write_log_path)
    logging.config.fileConfig(plog_conf, disable_existing_loggers=False, defaults={"log_path": write_log_path})
    logger = logging.getLogger(name)
    return logger



if __name__ == "__main__":
    # 只输出到控制台
    log = get_logger("debug")
    # # 只输出到文件
    # log = get_logger("crawler")
    # # 同时输出到控制台和文件
    # log = get_logger("root")
    log.debug("test debug")
    log.info("test info")
    log.warning("test warning")
    log.error("test error")
    log.critical("test critical")


"""
输出
2023-09-03 09:44:38,481 debug logger.py:<module>:32 DEBUG test debug
2023-09-03 09:44:38,481 debug logger.py:<module>:33 INFO test info
2023-09-03 09:44:38,481 debug logger.py:<module>:34 WARNING test warning
2023-09-03 09:44:38,481 debug logger.py:<module>:35 ERROR test error
2023-09-03 09:44:38,481 debug logger.py:<module>:36 CRITICAL test critical
[Finished in 0.1s]
"""

4 其它文件导入使用

代码语言:javascript复制
# -*- coding: utf-8 -*-
# @Author: Mehaei
# @Date: 2023-09-03 09:42:45
# @Last Modified by: Mehaei
# @Last Modified time: 2023-09-03 09:43:22
from logger import get_logger

log = get_logger("debug")

log.debug("test debug")
log.info("test info")
log.warning("test warning")
log.error("test error")
log.critical("test critical")

"""
输出
2023-09-03 09:43:22,801 debug crawler.py:<module>:10 DEBUG test debug
2023-09-03 09:43:22,801 debug crawler.py:<module>:11 INFO test info
2023-09-03 09:43:22,801 debug crawler.py:<module>:12 WARNING test warning
2023-09-03 09:43:22,801 debug crawler.py:<module>:13 ERROR test error
2023-09-03 09:43:22,801 debug crawler.py:<module>:14 CRITICAL test critical
[Finished in 0.1s]
"""

快乐的时光总是短暂的, 下次见~

0 人点赞