日志函数参数列表
日志文件中的格式所用到的参数如下所示:
属性名称 | 格式 | 描述 |
|---|---|---|
args | 不需要格式化。 | 合并到 |
asctime |
| 表示 |
created |
|
|
exc_info | 不需要格式化。 | 异常元组 (例如 |
filename |
|
|
funcName |
| 函数名包括调用日志记录. |
levelname |
| 消息文本记录级别 ( |
levelno |
| 消息数字记录级别 ( |
lineno |
| 发出日志记录调用所在的源行号(如果可用)。 |
message |
| 记入日志的消息,即 |
module |
| 模块 ( |
msecs |
|
|
msg | 不需要格式化。 | 在原始日志记录调用中传入的格式字符串。 与 |
name |
| 用于记录调用的日志记录器名称。 |
pathname |
| 发出日志记录调用的源文件的完整路径名(如果可用)。 |
process |
| 进程ID(如果可用) |
processName |
| 进程名(如果可用) |
relativeCreated |
| 以毫秒数表示的 LogRecord 被创建的时间,即相对于 logging 模块被加载时间的差值。 |
stack_info | 不需要格式化。 | 当前线程中从堆栈底部起向上直到包括日志记录调用并导致创建此记录的堆栈帧的堆栈帧信息(如果可用)。 |
thread |
| 线程ID(如果可用) |
threadName |
| 线程名(如果可用) |
示例1
import logging
logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG) # 日志等级
# 设置日志格式
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')
# 创建保存日志文件的处理器
file_handler = logging.FileHandler('spam.log') #保存日志对象
file_handler.setLevel(logging.DEBUG) #保存的日志等级
file_handler.setFormatter(formatter) #保存文件中的日志格式
# 创建控制台日志输出的处理器
stream_handler = logging.StreamHandler() #控制台日志对象
stream_handler.setLevel(logging.ERROR) #控制台日志等级
stream_handler.setFormatter(formatter) #控制台日志格式
# 将处理器添加至日志管理(logger)
logger.addHandler(file_handler) #保存日志文件的处理器
logger.addHandler(stream_handler ) #控制台日志输出的处理器
# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warning('warn message')
logger.error('error message')
logger.critical('critical message')
示例2
# Copyright (c) 2020 PaddlePaddle Authors. All Rights Reserve.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
# http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
import os
import sys
import logging
import functools
logger_initialized = {}
@functools.lru_cache()
def get_logger(name='root', log_file=None, log_level=logging.INFO):
"""Initialize and get a logger by name.
If the logger has not been initialized, this method will initialize the
logger by adding one or two handlers, otherwise the initialized logger will
be directly returned. During initialization, a StreamHandler will always be
added. If `log_file` is specified a FileHandler will also be added.
Args:
name (str): Logger name.
log_file (str | None): The log filename. If specified, a FileHandler
will be added to the logger.
log_level (int): The logger level. Note that only the process of
rank 0 is affected, and other processes will set the level to
"Error" thus be silent most of the time.
Returns:
logging.Logger: The expected logger.
"""
logger = logging.getLogger(name)
if name in logger_initialized:
return logger
for logger_name in logger_initialized:
if name.startswith(logger_name):
return logger
formatter = logging.Formatter(
'[%(asctime)s] %(name)s %(levelname)s: %(message)s',
datefmt="%Y/%m/%d %H:%M:%S")
stream_handler = logging.StreamHandler(stream=sys.stdout)
stream_handler.setFormatter(formatter)
logger.addHandler(stream_handler)
if log_file is not None:
log_file_folder = os.path.split(log_file)[0]
os.makedirs(log_file_folder, exist_ok=True)
file_handler = logging.FileHandler(log_file, 'a')
file_handler.setFormatter(formatter)
logger.addHandler(file_handler)
logger.setLevel(log_level)
logger_initialized[name] = True
return logger
这篇博客介绍了如何使用Python的日志模块将应用程序的日志记录保存到指定的文件中,通过示例1和示例2详细展示了日志函数的参数列表和使用方法。
1389





