Python Logging模塊的簡單使用


前言

日志是非常重要的,最近有接觸到這個,所以系統的看一下Python這個模塊的用法。本文即為Logging模塊的用法簡介,主要參考文章為Python官方文檔,鏈接見參考列表。

另外,Python的HOWTOs文檔很詳細,連日志該怎么用都寫了,所以有英文閱讀能力的同學建議去閱讀一下。

Logging模塊構成

組成

主要分為四個部分:

  • Loggers:提供應用程序直接使用的接口
  • Handlers:將Loggers產生的日志傳到指定位置
  • Filters:對輸出日志進行過濾
  • Formatters:控制輸出格式

日志級別

Level Numeric value When it’s used
DEBUG 10 Detailed information, typically of interest only when diagnosing problems.
INFO 20 Confirmation that things are working as expected.
WARNING 30 An 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.
ERROR 40 Due to a more serious problem, the software has not been able to perform some function.
CRITICAL 50 A serious error, indicating that the program itself may be unable to continue running.
NOSET 0 getattr(logging, loglevel.upper())

默認級別是WARNING,可以使用打印到屏幕上的方式記錄,也可以記錄到文件中。

模塊使用示例

簡單例子

打印輸出
In [5]: import logging

In [6]: logging.warning("FBI warning")
WARNING:root:FBI warning

In [7]: logging.info("information")
# 沒有打印是因為默認級別是warning
輸出到文件中
In [4]: import logging

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

In [6]: logging.debug("debug")

In [7]: logging.warning('warning')

In [8]: logging.info('info')

In [9]: ls
C++ STL/     a.py         example.log  parser/      test.sh*

In [10]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info

In [14]: logging.warning('new warning')
# 注意這種是直接往后面添加,也就是add的,若是想覆蓋內容可以更改文件寫入方式

In [15]: cat example.log
DEBUG:root:debug
WARNING:root:warning
INFO:root:info
WARNING:root:new warning

# 覆蓋的方式寫入例子
(test) ➜  test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import logging

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

In [3]: logging.warning('FBI warning')

In [4]: ls
C++ STL/     a.py         example.log  parser/      test.sh*

In [5]: cat example.log
WARNING:root:FBI warning

In [6]: quit
(test) ➜  test ipython
WARNING: Attempting to work in a virtualenv. If you encounter problems, please install IPython inside the virtualenv.
Python 2.7.11 (default, Jun 17 2016, 20:01:51)
Type "copyright", "credits" or "license" for more information.

IPython 4.2.0 -- An enhanced Interactive Python.
?         -> Introduction and overview of IPython's features.
%quickref -> Quick reference.
help      -> Python's own help system.
object?   -> Details about 'object', use 'object??' for extra details.

In [1]: import logging

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

In [3]: logging.warning('warning')

In [4]: cat example.log
WARNING:root:warning
變量的使用

print語句中使用變量一樣,如:

In [5]: logging.warning('%s before you %s', 'Look', 'leap!')

In [6]: cat example.log
WARNING:root:warning
WARNING:root:Look before you leap!
輸出格式

可以在basicConfig中設置,參數名稱可以參見鏈接,可以設置時間什么的,如:

In [2]: import logging

In [3]: logging.basicConfig(format='%(asctime)s:%(levelname)s:%(message)s', level=logging.DEBUG)

In [4]: logging.warning('And this, too')
2016-12-06 15:40:43,577:WARNING:And this, too

進階使用

當想項目中使用logging模塊的時候肯定不能在這樣一句句的寫了,一般可能會抽象出一個模塊來,這樣比較有效一些。logging模塊提供了四個類(Loggers,Formatters,Filtters,Handlers)來實現不同的功能,與此對應的我們如果想封裝一個函數,也就要針對這幾個功能來自定義一下。

想自定義的話思路也很簡單,首先實例化一個相應的對象,然后進行一些設置,可以簡單看一下下面的例子:

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
2005-03-19 15:10:26,618 - simple_example - DEBUG - debug message
2005-03-19 15:10:26,620 - simple_example - INFO - info message
2005-03-19 15:10:26,695 - simple_example - WARNING - warn message
2005-03-19 15:10:26,697 - simple_example - ERROR - error message
2005-03-19 15:10:26,773 - simple_example - CRITICAL - critical message
從配置文件導入配置

模塊內容:

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')

# 輸出
$ python simple_logging_config.py
2005-03-19 15:38:55,977 - simpleExample - DEBUG - debug message
2005-03-19 15:38:55,979 - simpleExample - INFO - info message
2005-03-19 15:38:56,054 - simpleExample - WARNING - warn message
2005-03-19 15:38:56,055 - simpleExample - ERROR - error message
2005-03-19 15:38:56,130 - simpleExample - CRITICAL - critical message

配置文件內容:

[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

同時也可以使用YAML格式的配置文件,如:

version: 1
formatters:
  simple:
    format: '%(asctime)s - %(name)s - %(levelname)s - %(message)s'
handlers:
  console:
    class: logging.StreamHandler
    level: DEBUG
    formatter: simple
    stream: ext://sys.stdout
loggers:
  simpleExample:
    level: DEBUG
    handlers: [console]
    propagate: no
root:
  level: DEBUG
  handlers: [console]

PS

Logging模塊使用也會有很多坑,常見的是日志重復打印的問題,大家可以搜一下,這里提供一些鏈接供參考:

  1. http://www.jianshu.com/p/25f70905ae9d
  2. https://yinzo.github.io/14610807170718.html
  3. http://python.jobbole.com/86887/

參考

  1. https://docs.python.org/2/library/logging.html
  2. https://docs.python.org/2/howto/logging.html#logging-basic-tutorial


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM