Python将log日志保存至指定文件

这篇博客介绍了如何使用Python的日志模块将应用程序的日志记录保存到指定的文件中,通过示例1和示例2详细展示了日志函数的参数列表和使用方法。

日志函数参数列表

日志文件中的格式所用到的参数如下所示:

属性名称

格式

描述

args

不需要格式化。

合并到 msg 以产生 message 的包含参数的元组,或是其中的值将被用于合并的字典(当只有一个参数且其类型为字典时)。

asctime

%(asctime)s

表示 LogRecord 何时被创建的供人查看时间值。 默认形式为 '2003-07-08 16:49:45,896' (逗号之后的数字为时间的毫秒部分)。

created

%(created)f

LogRecord 被创建的时间(即 time.time() 的返回值)。

exc_info

不需要格式化。

异常元组 (例如 sys.exc_info) 或者如未发生异常则为 None

filename

%(filename)s

pathname 的文件名部分。

funcName

%(funcName)s

函数名包括调用日志记录.

levelname

%(levelname)s

消息文本记录级别 ('DEBUG', 'INFO', 'WARNING', 'ERROR', 'CRITICAL').

levelno

%(levelno)s

消息数字记录级别 (DEBUG, INFO, WARNING, ERROR, CRITICAL).

lineno

%(lineno)d

发出日志记录调用所在的源行号(如果可用)。

message

%(message)s

记入日志的消息,即 msg % args 的结果。 这是在发起调用 Formatter.format() 时设置的。

module

%(module)s

模块 (filename 的名称部分)。

msecs

%(msecs)d

LogRecord 被创建的时间的毫秒部分。

msg

不需要格式化。

在原始日志记录调用中传入的格式字符串。 与 args 合并以产生 message,或是一个任意对象 (参见 使用任意对象作为消息)。

name

%(name)s

用于记录调用的日志记录器名称。

pathname

%(pathname)s

发出日志记录调用的源文件的完整路径名(如果可用)。

process

%(process)d

进程ID(如果可用)

processName

%(processName)s

进程名(如果可用)

relativeCreated

%(relativeCreated)d

以毫秒数表示的 LogRecord 被创建的时间,即相对于 logging 模块被加载时间的差值。

stack_info

不需要格式化。

当前线程中从堆栈底部起向上直到包括日志记录调用并导致创建此记录的堆栈帧的堆栈帧信息(如果可用)。

thread

%(thread)d

线程ID(如果可用)

threadName

%(threadName)s

线程名(如果可用)

示例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
评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

great-wind

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值