广告
返回顶部
首页 > 资讯 > 后端开发 > Python >Python标准库 - logging
  • 797
分享到

Python标准库 - logging

标准Pythonlogging 2023-01-31 06:01:09 797人浏览 泡泡鱼

Python 官方文档:入门教程 => 点击学习

摘要

编写代码时, 常要跟踪下其运行过程, 记录日志是常用的方式. 较简单的就是print命令打印到终端, 或通过open函数写入文件. 但随着代码量的增加, 该方式不可控的弊端, 也凸显出来, 这也正是logging模块出现的背景.对于logg


编写代码时, 常要跟踪下其运行过程, 记录日志是常用的方式. 较简单的就是print命令打印到终端, 或通过open函数写入文件. 但随着代码量的增加, 该方式不可控的弊端, 也凸显出来, 这也正是logging模块出现的背景.



对于logging模块, 简单来说直接import进来, 就可以用了.

In [1]: import logging


In [2]: logging.warning('Watch out!')

WARNING:root:Watch out!


In [3]: logging.info('I told you so')


In [4]:


In [4]:


第二个语句没有输出呢, 这需了解下日志等级的概念. logging模块默认的日志等级是WARNING, 大于该等级的日志才会输出, 细节如下.

    Level        When it’s used
DEBUGDetailed infORMation, typically of interest only when diagnosing problems.
INFOConfirmation that things are working as expected.
WARNINGAn indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected.
ERRORDue to a more serious problem, the software has not been able to perform some function.
CRITICALA serious error, indicating that the program itself may be unable to continue running.


借助basicConfig方法, 可对日志记录做些配置.

In [1]: import logging


In [2]: logging.basicConfig(filename='/tmp/example.log',level=logging.DEBUG)


In [3]: logging.debug('This message should Go to the log file')


In [4]: logging.info('So should this')


In [5]: logging.warning('And this, too')


$ cat /tmp/example.log

DEBUG:root:This message should go to the log file

INFO:root:So should this

WARNING:root:And this, too


在脚本中, 可按照下面的方式使用logging模块.

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# myapp.py


import logging

import mylib


def main():

    logging.basicConfig(filename='myapp.log', format='%(asctime)s - %(name)s - %(levelname)s - %(pathname)s - %(message)s', level=logging.INFO)

    logging.info('Started')

    mylib.do_something()

    logging.info('Finished')


if __name__ == '__main__':

    main()


#!/usr/bin/env Python

# -*- coding: utf-8 -*-

# mylib.py


import logging


def do_something():

    logging.info('Doing something')


$ python myapp.py

$ cat myapp.log

2018-01-19 17:00:14,821 - root - INFO - myapp.py - Started

2018-01-19 17:00:14,821 - root - INFO - /home/zz/stage/mylib.py - Doing something

2018-01-19 17:00:14,821 - root - INFO - myapp.py - Finished



简单了解了logging模块的使用, 接着看下其中几个重要的概念.

1. Logger 日志记录器, 暴露给应用程序直接使用的接口, 几个方法用于设置记录器.


Logger.setLevel() - 指定日志记录器处理的日志最低级别.

Logger.addHandler(), Logger.removeHandler() - 为日志记录器添加, 或移除处理器.


2. Handler 处理器, 将记录器获取的日志, 传送到其定义的目的地, 也有几个方法设置处理器.


setLevel() - 指定处理器处理的日志最低级别.

setFormatter() - 为处理器选择一个格式化器.


3. Formatter 格式化器, 指定日志的输出格式.



最开始说了logging模块的简单用法, 以及了解了上面的概念后, 看下开发较大应用时, 如何使用logging呢.


这主要介绍两种方式, 其一是, 将logging模块的配置直接写在应用代码中, 如下所示.

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# simple_logging_module.py


import logging


# create logger

logger = logging.getLogger('simple_example')

logger.setLevel(logging.DEBUG)


# create console handler and set level to debug

ch = logging.StreamHandler()

ch.setLevel(logging.DEBUG)


# create formatter

formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')


# add formatter to ch

ch.setFormatter(formatter)


# add ch to logger

logger.addHandler(ch)


# 'application' code

logger.debug('debug message')

logger.info('info message')

logger.warn('warn message')

logger.error('error message')

logger.critical('critical message')


$ python simple_logging_module.py

2018-01-19 21:41:58,180 - simple_example - DEBUG - debug message

2018-01-19 21:41:58,180 - simple_example - INFO - info message

2018-01-19 21:41:58,180 - simple_example - WARNING - warn message

2018-01-19 21:41:58,180 - simple_example - ERROR - error message

2018-01-19 21:41:58,180 - simple_example - CRITICAL - critical message


其二, 配置信息写入文件中, 借助fileConfig方法加载该文件, 如下所示.

#!/usr/bin/env python

# -*- coding: utf-8 -*-

# simple_logging_config.py


import logging

import logging.config


logging.config.fileConfig('logging.conf')


# create logger

logger = logging.getLogger('simpleExample')


# 'application' code

logger.debug('debug message')

logger.info('info message')

logger.warn('warn message')

logger.error('error message')

logger.critical('critical message')


# logging.conf

[loggers]

keys=root,simpleExample


[handlers]

keys=consoleHandler


[formatters]

keys=simpleFormatter


[logger_root]

level=DEBUG

handlers=consoleHandler


[logger_simpleExample]

level=DEBUG

handlers=consoleHandler

qualname=simpleExample

propagate=0


[handler_consoleHandler]

class=StreamHandler

level=DEBUG

formatter=simpleFormatter

args=(sys.stdout,)


[formatter_simpleFormatter]

format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

datefmt=


$ python simple_logging_config.py

2018-01-19 21:53:46,216 - simpleExample - DEBUG - debug message

2018-01-19 21:53:46,216 - simpleExample - INFO - info message

2018-01-19 21:53:46,216 - simpleExample - WARNING - warn message

2018-01-19 21:53:46,216 - simpleExample - ERROR - error message

2018-01-19 21:53:46,216 - simpleExample - CRITICAL - critical message



最后简单说下, 如何总结一个模块, 可围绕下面三点进行说明.

1. 该模块解决的问题, 其它方法是如何做的.

2. 模块的使用, 以及核心概念(或定义).

3. 核心api的梳理.


若感兴趣可关注订阅号”数据库最佳实践”(DBBestPractice).

qrcode_for_gh_54ffa7e55478_258.jpg

--结束END--

本文标题: Python标准库 - logging

本文链接: https://www.lsjlt.com/news/190520.html(转载时请注明来源链接)

有问题或投稿请发送至: 邮箱/279061341@qq.com    QQ/279061341

本篇文章演示代码以及资料文档资料下载

下载Word文档到电脑,方便收藏和打印~

下载Word文档
猜你喜欢
  • Python标准库 - logging
    编写代码时, 常要跟踪下其运行过程, 记录日志是常用的方式. 较简单的就是print命令打印到终端, 或通过open函数写入文件. 但随着代码量的增加, 该方式不可控的弊端, 也凸显出来, 这也正是logging模块出现的背景.对于logg...
    99+
    2023-01-31
    标准 Python logging
  • python标准库--logging模块
    logging模块的几个级别,默认情况下Logging模块有6个级别,代码如下#!/usr/bin/env python # coding: utf-8 __author__ = '...
    99+
    2023-01-30
    模块 标准 python
  • python标准库logging模块怎么用
    本文小编为大家详细介绍“python标准库logging模块怎么用”,内容详细,步骤清晰,细节处理妥当,希望这篇“python标准库logging模块怎么用”文章能帮助大家解决疑惑,下面跟着小编的思路慢慢深入,一起来学习新知识吧。问题1:如...
    99+
    2023-06-30
  • Python标准库中的logging用法示例
    本篇文章给大家带来了关于Python的相关知识,logging是Python标准库中记录常用的记录日志库,通过logging模块存储各种格式的日志,主要用于输出运行日志,可以设置输出日志的等级、日志保存路径、日志文件回滚等,下面一起来看一下...
    99+
    2022-09-05
  • 代码解析python标准库logging模块
    目录问题1:如何获取caller的(文件名,行号,函数名)?findCaller内容如下:currentframe函数的定义:问题2: Logger对象的层级,父子关系如何实现的?M...
    99+
    2022-11-11
  • Python标准库中的logging用法示例详解
    目录1、logging的介绍2、简单用法示例3、日志级别4、打印格式的各个参数5、日志输出到指定文件6、日志回滚(按照文件大小滚动)7、日志回滚(按照时间滚动)1、logging的介...
    99+
    2022-11-11
  • python标准库
    Python有一套很有用的标准库(standard library)。标准库会随着Python解释器,一起安装在你的电脑中的。它是Python的一个组成部分。这些标准库是Python为你准备好的利器,可以让编程事半功倍。 我将根据我个人的使...
    99+
    2023-01-31
    标准 python
  • python标准库--functools
    官方相关地址:https://docs.python.org/3.6/library/functools.html   一.简单介绍:        functools模块用于高阶函数:作用于或返回其他函数的函数。一般而言,任何可调用对象...
    99+
    2023-01-30
    标准 python functools
  • python之标准库
    Python的标准安装包括一组模块,称为标准库。10.1 模块>>>emport math>>>math.sin(0)0.010.1.1 模块是程序任何python程序都可以作为模块导入。#hello.p...
    99+
    2023-01-31
    标准 python
  • Python标准库 - subproce
    编写Python脚本时, 经常要执行Linux操作系统命令, 如mkdir zzzz. 目前比较推荐的方法是使用subprocess模块.通过该模块的帮助文档, 可看到其主要提供了4个API, 和相应的使用说明.Main API======...
    99+
    2023-01-31
    标准 Python subproce
  • Python标准库 - re
    编写代码时, 经常要匹配特定字符串, 或某个模式的字符串, 一般会借助字符串函数, 或正则表达式完成.对于正则表达式, 有些字符具有特殊含义, 需使用反斜杠字符'\'转义, 使其表示本身含义. 如想匹配字符'\', 却要写成'\\\\', ...
    99+
    2023-01-31
    标准 Python
  • python常用标准库
    -------------------系统内建函数-------------------1、字符串str='这是一个字符串数据测试数据'对应str[0]:获取str字符串中下标为0的字符。str[3]:获取str字符串中下标为3的字符。st...
    99+
    2023-01-31
    常用 标准 python
  • Python标准库大全
    以下是Python标准库大全 文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 stringprep:互联网字符串准备工具 ...
    99+
    2023-10-26
    python 开发语言
  • python 标准库简介
    操作系统接口 os 模块提供了许多与操作系统交互的函数: >>> >>> import os >>> os.getcwd() # Return the current ...
    99+
    2023-01-31
    标准 简介 python
  • python 标准库大全
    文本 string:通用字符串操作 re:正则表达式操作 difflib:差异计算工具 textwrap:文本填充 unicodedata:Unicode字符数据库 stringprep:互联网字符串准备工具 readline:GNU...
    99+
    2023-01-31
    标准 大全 python
  • Python标准库之os
    文章目录 1. OS标准库简介2. OS标准库常用函数和属性2.1 文件和目录2.1.1 `os.getcwd()`2.1.2 `os.mkdir(path, mode=0o777, *, d...
    99+
    2023-09-04
    python linux 标准库 os 常用函数
  • python中的标准库html
    目录python之标准库html__init__.py文件提供两个函数:html库中的 entities 模块html库中的 parser 模块python之标准库html html...
    99+
    2022-11-10
  • Python Logging库HTTP
    Python的logging库是标准库中用来实现日志的库,功能强大,而且使用起来也算是方便。该库提供了很多个不同的Handler,用来对日志进行不同的处理。例如FileHandler用来将日志记录到文件,RotateFileHandle...
    99+
    2023-01-31
    Python Logging HTTP
  • Python标准库之数据库 sqlite3
    目录1、创建数据库 2、插入数据3、查询4、更新与删除Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配P...
    99+
    2022-11-12
  • Python标准库14 数据库 (sqlite3)
    Python自带一个轻量级的关系型数据库SQLite。这一数据库使用SQL语言。SQLite作为后端数据库,可以搭配Python建网站,或者制作有数据存储需求的工具。SQLite还在其它领域有广泛的应用,比如HTML5和移动端。Python...
    99+
    2023-06-02
软考高级职称资格查询
编程网,编程工程师的家园,是目前国内优秀的开源技术社区之一,形成了由开源软件库、代码分享、资讯、协作翻译、讨论区和博客等几大频道内容,为IT开发者提供了一个发现、使用、并交流开源技术的平台。
  • 官方手机版

  • 微信公众号

  • 商务合作