20210822
logging的简单使用
简介
日志等级
日志等级可以分为5个,从低到高分别是:
- DEBUG
- INFO
- WARNING
- ERROR
- CRITICAL
日志等级说明:
- DEBUG:程序调试bug时使用
- INFO:程序正常运行时使用
- WARNING:程序未按预期运行时使用,但并不是错误,如:用户登录密码错误
- ERROR:程序出错误时使用,如:IO操作失败
- CRITICAL:特别严重的问题,导致程序不能再继续运行时使用,如:磁盘空间为空,一般很少使用
- 默认的是WARNING等级,当在WARNING或WARNING之上等级的才记录日志信息。
- 日志等级从低到高的顺序是: DEBUG < INFO < WARNING < ERROR < CRITICAL
配置
logging.basicConfig(**kwargs)
用于设置日志参数,常用的参数用level和format
def basicConfig(**kwargs):
"""
Do basic configuration for the logging system.
This function does nothing if the root logger already has handlers
configured, unless the keyword argument *force* is set to ``True``.
It is a convenience method intended for use by simple scripts
to do one-shot configuration of the logging package.
The default behaviour is to create a StreamHandler which writes to
sys.stderr, set a formatter using the BASIC_FORMAT format string, and
add the handler to the root logger.
A number of optional keyword arguments may be specified, which can alter
the default behaviour.
filename Specifies that a FileHandler be created, using the specified
filename, rather than a StreamHandler.
filemode Specifies the mode to open the file, if filename is specified
(if filemode is unspecified, it defaults to ‘a‘).
format Use the specified format string for the handler.
datefmt Use the specified date/time format.
style If a format string is specified, use this to specify the
type of format string (possible values ‘%‘, ‘{‘, ‘$‘, for
%-formatting, :meth:`str.format` and :class:`string.Template`
- defaults to ‘%‘).
level Set the root logger level to the specified level.
stream Use the specified stream to initialize the StreamHandler. Note
that this argument is incompatible with ‘filename‘ - if both
are present, ‘stream‘ is ignored.
handlers If specified, this should be an iterable of already created
handlers, which will be added to the root handler. Any handler
in the list which does not have a formatter assigned will be
assigned the formatter created in this function.
force If this keyword is specified as true, any existing handlers
attached to the root logger are removed and closed, before
carrying out the configuration as specified by the other
arguments.
Note that you could specify a stream created using open(filename, mode)
rather than passing the filename and mode in. However, it should be
remembered that StreamHandler does not close its stream (since it may be
using sys.stdout or sys.stderr), whereas FileHandler closes its stream
when the handler is closed.
.. versionchanged:: 3.8
Added the ``force`` parameter.
.. versionchanged:: 3.2
Added the ``style`` parameter.
.. versionchanged:: 3.3
Added the ``handlers`` parameter. A ``ValueError`` is now thrown for
incompatible arguments (e.g. ``handlers`` specified together with
``filename``/``filemode``, or ``filename``/``filemode`` specified
together with ``stream``, or ``handlers`` specified together with
``stream``.
"""
level参数的值:
CRITICAL = 50
FATAL = CRITICAL
ERROR = 40
WARNING = 30
WARN = WARNING
INFO = 20
DEBUG = 10
NOTSET = 0
format参数的值:
如果对 %(asctime)s的默认格式化时间不满意,可使用参数logging.basicConfig的datefmt再对%(asctime)s的时间进行自定义
logging.basicConfig(
level=logging.DEBUG,
format=‘%(asctime)s‘, datefmt=‘%m/%d/%Y %I:%M:%S %p‘)
# 默认结果:2021-08-22 16:31:42,567
# 使用datefmt之后的结果:08/22/2021 04:30:44 PM
class Formatter(object):
"""
Formatter instances are used to convert a LogRecord to text.
Formatters need to know how a LogRecord is constructed. They are
responsible for converting a LogRecord to (usually) a string which can
be interpreted by either a human or an external system. The base Formatter
allows a formatting string to be specified. If none is supplied, the
the style-dependent default value, "%(message)s", "{message}", or
"${message}", is used.
The Formatter can be initialized with a format string which makes use of
knowledge of the LogRecord attributes - e.g. the default value mentioned
above makes use of the fact that the user‘s message and arguments are pre-
formatted into a LogRecord‘s message attribute. Currently, the useful
attributes in a LogRecord are described by:
%(name)s Name of the logger (logging channel)
%(levelno)s Numeric logging level for the message (DEBUG, INFO,
WARNING, ERROR, CRITICAL)
%(levelname)s Text logging level for the message ("DEBUG", "INFO",
"WARNING", "ERROR", "CRITICAL")
%(pathname)s Full pathname of the source file where the logging
call was issued (if available)
%(filename)s Filename portion of pathname
%(module)s Module (name portion of filename)
%(lineno)d Source line number where the logging call was issued
(if available)
%(funcName)s Function name
%(created)f Time when the LogRecord was created (time.time()
return value)
%(asctime)s Textual time when the LogRecord was created
%(msecs)d Millisecond portion of the creation time
%(relativeCreated)d Time in milliseconds when the LogRecord was created,
relative to the time the logging module was loaded
(typically at application startup time)
%(thread)d Thread ID (if available)
%(threadName)s Thread name (if available)
%(process)d Process ID (if available)
%(message)s The result of record.getMessage(), computed just as
the record is emitted
"""
控制台输出日志
import logging
# 配置日志参数
# 把默认的warning级别改为debug, level=logging.DEBUG
# 格式化日志信息:
# %(name)s 用户??
# %(asctime)s 时间
# %(filename)s 文件名
# %(lineno)d 日志代码所在行号
# %(levelname)s 日志等级
# %(message)s 日志信息
logging.basicConfig(
level=logging.DEBUG,
format=
‘%(name)s - %(asctime)s - %(filename)s[%(lineno)d] - %(levelname)s: %(message)s‘)
logging.debug(‘debug日志‘)
logging.info(‘info日志‘)
logging.warning(‘warning日志‘)
logging.error(‘debug日志‘)
logging.critical(‘critical日志‘)
结果:
root - 2021-08-22 16:22:12,750 - 01_logging日志.py[9] - DEBUG: debug日志
root - 2021-08-22 16:22:12,750 - 01_logging日志.py[10] - INFO: info日志
root - 2021-08-22 16:22:12,750 - 01_logging日志.py[11] - WARNING: warning日志
root - 2021-08-22 16:22:12,750 - 01_logging日志.py[12] - ERROR: debug日志
root - 2021-08-22 16:22:12,750 - 01_logging日志.py[13] - CRITICAL: critical日志
日志输出到文件中
import logging
# 配置日志参数
# 把默认的warning级别改为debug, level=logging.DEBUG
# 格式化日志信息:
# %(name)s 用户??
# %(asctime)s 时间
# %(filename)s 文件名
# %(lineno)d 日志代码所在行号
# %(levelname)s 日志等级
# %(message)s 日志信息
# filename=‘log.txt‘ 日志输出的文件,默认是追加模式(a),可通过filemode修改默认模式,如改为每次都清空日志重新写入filemode=‘w‘
logging.basicConfig(
level=logging.DEBUG,
format=
‘%(name)s - %(asctime)s - %(filename)s[%(lineno)d] - %(levelname)s: %(message)s‘
, filename=‘log.txt‘)
logging.debug(‘debug日志‘)
logging.info(‘info日志‘)
logging.warning(‘warning日志‘)
logging.error(‘debug日志‘)
logging.critical(‘critical日志‘)
其它
如果需要同时在控制台输出的同时还写入文件,可参考