阅读documentation on logging之后,我知道我可以使用这样的代码来执行简单的日志(log)记录:

import logging

def main():
    logging.basicConfig(filename="messages.log",
                        level=logging.WARNING,
                        format='%(filename)s: '    
                                '%(levelname)s: '
                                '%(funcName)s(): '
                                '%(lineno)d:\t'
                                '%(message)s')

    logging.debug("Only for debug purposes\n")
    logging.shutdown()

main()

然而,我意识到我不知道如何在每个记录器的基础上更改日志(log)消息的格式,因为basicConfig是一个模块级函数.这段代码用于创建具有不同级别、名称等的不同日志(log)记录者.但是有没有一种方法可以在每个日志(log)记录者的基础上以类似于basicConfig的方式更改这些日志(log)消息的格式?

import inspect
import logging

def function_logger(level=logging.DEBUG):
    function_name = inspect.stack()[1][3]
    logger = logging.getLogger(function_name)
    logger.setLevel(level)
    logger.addHandler(logging.FileHandler("{0}.log".format(function_name)))
    return logger

def f1():
    f1_logger = function_logger()
    f1_logger.debug("f1 Debug message")
    f1_logger.warning("f1 Warning message")
    f1_logger.critical("f1 Critical message")

def f2():
    f2_logger = function_logger(logging.WARNING)
    f2_logger.debug("f2 Debug message")
    f2_logger.warning("f2 Warning message")
    f2_logger.critical("f2 Critical message")

def main():
    f1()
    f2()
    logging.shutdown()

main()

推荐答案

试试这个

import logging

logger = logging.getLogger('simple_example')
logger.setLevel(logging.DEBUG)
# create file handler that logs debug and higher level messages
fh = logging.FileHandler('spam.log')
fh.setLevel(logging.DEBUG)
# create console handler with a higher log level
ch = logging.StreamHandler()
ch.setLevel(logging.ERROR)
# create formatter and add it to the handlers
formatter = logging.Formatter(
    '%(asctime)s - %(name)s - %(levelname)s - %(message)s')
ch.setFormatter(formatter)
fh.setFormatter(formatter)
# add the handlers to logger
logger.addHandler(ch)
logger.addHandler(fh)

# 'application' code
logger.debug('debug message')
logger.info('info message')
logger.warn('warn message')
logger.error('error message')
logger.critical('critical message')

更多信息请参见http://docs.python.org/howto/logging-cookbook.html#multiple-handlers-and-formatters

Python-3.x相关问答推荐

根据收件箱内部的值以行降序的特定顺序重新排序列

只有在Chrome尚未打开的情况下,打开Chrome后,PySimpleGUI窗口才会崩溃

CDKTF ec2 具有特定私有 IP 地址的娱乐

tkinter treeview 如何在获取所选项目时将设置的对象作为对象返回

SQL Server 2022和Python3.10脚本错误

如何立即从asyncio.Task获取异常?

从列表的元素和python中的多个多索引数据帧执行方程

类不继承时 super() 的用途

使用 selenium 加速网页抓取

活动屏幕上的 PyQt4 中心窗口

Python 3 list(dictionary.keys()) 引发错误.我究竟做错了什么?

django.core.exceptions.ImproperlyConfigured

Python过滤器函数 - 单个结果

登录csv文件的正确方法是什么?

在 WSL (Ubuntu) 中为 python3 安装 venv

TypeError: write() 参数必须是 str,而不是字节(Python 3 vs Python 2)

在 Ipython 中使用 Pylint (Jupyter-Notebook)

如何判断列表中的所有项目是否都是字符串

将 Python SIGINT 重置为默认信号处理程序

为什么异步库比这个 I/O 绑定操作的线程慢?