学习 python logging(2): 格式化日志输出

1. 简介

在实际项目中,我们可能需要根据实际需要去记录日志,包括记录的时间、进程号、日志的等级、出现的对应文件及行号等等,以帮助我们定位问题,分析过程。python已经为我们提供了基础的这些,包括:

nameformat_strmeaning
asctime%(asctime)sHuman-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)fTime when the LogRecord was created (as returned by time.time()).
filename%(filename)sFilename portion of pathname.
funcName%(funcName)sName of function containing the logging call.
levelname%(levelname)sText logging level for the message (‘DEBUG’, ‘INFO’, ‘WARNING’, ‘ERROR’, ‘CRITICAL’).
levelno%(levelno)sNumeric logging level for the message (DEBUG, INFO, WARNING, ERROR, CRITICAL).
lineno%(lineno)dSource line number where the logging call was issued (if available).
message%(message)sThe logged message, computed as msg % args. This is set when Formatter.format() is invoked.
module%(module)sModule (name portion of filename).
msecs%(msecs)dMillisecond portion of the time when the LogRecord was created.
name%(name)sName of the logger used to log the call.
pathname%(pathname)sFull pathname of the source file where the logging call was issued (if available).
process%(process)dProcess ID (if available).
processName%(processName)sProcess name (if available).
relativeCreated%(relativeCreated)dTime in milliseconds when the LogRecord was created, relative to the time the logging module was loaded.
thread%(thread)dThread ID (if available).
threadName%(threadName)sThread 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
  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值