學習 python logging(2): 格式化日誌輸出

1. 簡介

在實際項目中,我們可能需要根據實際需要去記錄日誌,包括記錄的時間、進程號、日誌的等級、出現的對應文件及行號等等,以幫助我們定位問題,分析過程。python已經爲我們提供了基礎的這些,包括:

name format_str meaning
asctime %(asctime)s Human-readable time when the LogRecord was created. By default this is of the form ‘2003-07-08 16:49:45,896’ (the numbers after the comma are millisecond
created %(created)f Time when the LogRecord was created (as returned by time.time()).
filename %(filename)s Filename portion of pathname.
funcName %(funcName)s Name of function containing the logging call.
levelname %(levelname)s Text logging level for the message (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).
levelno %(levelno)s Numeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno %(lineno)d Source line number where the logging call was issued (if available).
message %(message)s The logged message, computed as msg % args. This is set when Formatter.format() is invoked.
module %(module)s Module (name portion of filename).
msecs %(msecs)d Millisecond portion of the time when the LogRecord was created.
name %(name)s Name of the logger used to log the call.
pathname %(pathname)s Full pathname of the source file where the logging call was issued (if available).
process %(process)d Process ID (if available).
processName %(processName)s Process name (if available).
relativeCreated %(relativeCreated)d Time in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
thread %(thread)d Thread ID (if available).
threadName %(threadName)s Thread name (if available).

在基本使用中,已經足夠了, 簡單的例子:

logging.basicConfig(
    format="%(asctime)s-%(filename)s-%(levelno)s-%(lineno)s, %(message)s"
)
logging.warning("test message")

日誌輸出爲:
2019-01-03 21:36:53,772-logging_format_sample.py-30-11, test message

2. 三種格式化方式

在python中日誌模塊中,有三種格式化日誌信息的方式: %-formatting, str.format(), Template, %s是默認的。

2.1 默認 %-formatting

以上例子已給出

2.2 使用 str.format()

需要將格式化的 style 參數設置成 {

logging.basicConfig(
    style='{',
    format="{asctime}-{filename}-{levelno}-{lineno}, {message}"
)
logging.warning("test format message")

日誌輸出爲
2019-01-03 21:49:59,689-logging_format_sample.py-30-11, test format message

2.3 使用Template

需要將格式化的 style 參數設置成 $

logging.basicConfig(
    style='$',
    format="$asctime-$filename-$levelno-$lineno, $message"
)
logging.warning("test template message")

日誌輸出爲
2019-01-03 21:53:56,873-logging_format_sample.py-30-11, test template message

以上,就是記錄日誌格式化消息的基本操作。


參考:

  1. https://docs.python.org/3/howto/logging.html#logging-basic-tutorial
  2. https://docs.python.org/3/library/logging.html
  3. https://docs.python.org/3/howto/logging-cookbook.html#logging-cookbook
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章