学习 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

你可能感兴趣的:(python)