[Python系列]Python日志模块详解

参考:https://docs.python.org/2/library/logging.html

Logging模块介绍

  • 模块:logging
  • 类:
    • Loggers:暴露直接给用户使用的接口
    • Handler:可以指定日志的输出源(文件/console等)
    • Filters:可以用于指定哪些日志可以输出
    • Formatters:指定日志的格式

我们通过下面的场景和源码来理解Loggers/Handler/Formatters的作用和区别

场景一:输出单一文件日志

logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s > %(message)s',
                        datefmt='%Y/%m/%d %H:%M:%S',
                        filename='testlog.log',
                        filemode='w')

# 输出日志
logging.info("test")

直接使用logging.info()通过root logger输出,且通过logging.basciConfig()可以指定root logger()的参数

场景二:输出单一文件日志和控制台日志

def __init_root_file_log():
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s > %(message)s',
                        datefmt='%Y/%m/%d %H:%M:%S',
                        filename='ui-test.log',
                        filemode='w')
    return


def __init_console_log():
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)

    logging.getLogger('').addHandler(console)
    return

__init_root_file_log()
__init_console_log()

这里相比上一个场景,多了需要将日志输出到控制台,python是通过向logger对象添加一个handler对象(StreamHandler对象)实现的:
logger.getLogger('')获取root logger对象,然后addHandler(console)

场景三:输出多个文件日志(附带控制台日志)

例如:相比场景二,我需要添加一个process_monitor.log,用来专门写进程监控日志

loggers = {}

def init_log():
    __init_root_file_log()
    __init_process_log()
    __init_console_log()


def __init_root_file_log():
    logging.basicConfig(level=logging.INFO,
                        format='%(asctime)s > %(message)s',
                        datefmt='%Y/%m/%d %H:%M:%S',
                        filename='ui-test.log',
                        filemode='w')
    return


def __init_console_log():
    console = logging.StreamHandler()
    console.setLevel(logging.INFO)
    formatter = logging.Formatter('%(name)-12s: %(levelname)-8s %(message)s')
    console.setFormatter(formatter)

    logging.getLogger('').addHandler(console)
    return


def __init_process_log():
    loggerName = "processlog"
    logger = logging.getLogger(loggerName)
    fh = logging.FileHandler("process_monitor.log")
    formatter = logging.Formatter("%(asctime)s > %(message)s")
    fh.setFormatter(formatter)

    logger.setLevel(logging.INFO)
    logger.addHandler(fh)

    loggers[loggerName] = logger

使用process_monitor.log输出日志的调用方式如下:

# 在整个应用开始时调用,初始化所有的logger对象
init_log()

# 输出日志
loggers['processlog'].info("process test")

效果如下:

  • 控制台
  • root logger:
  • process_monitor.log:

�相比场景二的代码,�多了__init_process_log()方法,它的处理如下:
1.logging.getLogger()获取了一个logger对象,这里参数可以是任意字符串
2.向logger对象添加了format对象和handler对象(FileHandler对象)
3.指定logger对象的日志级别
4.【非必须】将创建的logger对象添加到loggers这个dict对象中,方便日志文件较多的时候对日志对象进行管理

上面的基本可以覆盖大部分的硬盘日志需求,如果涉及网络日志,可以看看Python的各种Handler实现,这里后续如果有具体的业务场景的话,可以再讲讲

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • logging模块介绍: logging是python内置的标准库模块,模块提供不同的日志级别,并可以采用不同的方...
    4ffde5305e8f阅读 2,866评论 0 2
  • 本篇文章主要对 python logging 的介绍加深理解。更主要是 讨论在多进程环境下如何使用logging ...
    doudou0o阅读 41,244评论 52 42
  • 前言 在自动化测试实践过程中,必不可少的就是进行日志管理,方便调试和生产问题追踪,python提供了logg...
    苦叶子阅读 849评论 0 0
  • 本文首发于Gevin的博客 原文链接:Python 日志功能详解 未经 Gevin 授权,禁止转载 软件开发中通过...
    Gevin阅读 4,982评论 1 24
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,854评论 18 139