Python 日志记录配置文件

发布于 2024-10-07 17:40:20 字数 1541 浏览 4 评论 0原文

我在尝试将日志记录到我的 python 项目时似乎遇到了一些问题。

我只是尝试模仿以下配置:

Python Logging to Multiple目的地

但是,我不想在代码内部执行此操作,而是希望将其放在配置文件中。

以下是我的配置文件:

[loggers]
keys=root

[logger_root]
handlers=screen,file

[formatters]
keys=simple,complex

[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file,screen

[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('logs/testSuite.log',)

[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)

问题是我的屏幕输出如下所示:
2010-12-14 11:39:04,066 - 根 - 警告 - 3
2010-12-14 11:39:04,066 - 根 - 错误 - 4
2010-12-14 11:39:04,066 - root - CRITICAL - 5

我的文件已输出,但看起来与上面相同(尽管包含额外信息)。但是,调试和信息级别都不会输出到其中任何一个。

我使用的是 Python 2.7

这是我显示失败的简单示例:

import os
import sys
import logging
import logging.config

sys.path.append(os.path.realpath("shared/"))
sys.path.append(os.path.realpath("tests/"))

class Main(object):

  @staticmethod
  def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")

if __name__ == "__main__":
  Main.main()

I seem to be having some issues while attempting to implement logging into my python project.

I'm simply attempting to mimic the following configuration:

Python Logging to Multiple Destinations

However instead of doing this inside of code, I'd like to have it in a configuration file.

Below is my config file:

[loggers]
keys=root

[logger_root]
handlers=screen,file

[formatters]
keys=simple,complex

[formatter_simple]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s

[formatter_complex]
format=%(asctime)s - %(name)s - %(levelname)s - %(module)s : %(lineno)d - %(message)s

[handlers]
keys=file,screen

[handler_file]
class=handlers.TimedRotatingFileHandler
interval=midnight
backupCount=5
formatter=complex
level=DEBUG
args=('logs/testSuite.log',)

[handler_screen]
class=StreamHandler
formatter=simple
level=INFO
args=(sys.stdout,)

The problem is that my screen output looks like:
2010-12-14 11:39:04,066 - root - WARNING - 3
2010-12-14 11:39:04,066 - root - ERROR - 4
2010-12-14 11:39:04,066 - root - CRITICAL - 5

My file is output, but looks the same as above (although with the extra information included). However the debug and info levels are not output to either.

I am on Python 2.7

Here is my simple example showing failure:

import os
import sys
import logging
import logging.config

sys.path.append(os.path.realpath("shared/"))
sys.path.append(os.path.realpath("tests/"))

class Main(object):

  @staticmethod
  def main():
    logging.config.fileConfig("logging.conf")
    logging.debug("1")
    logging.info("2")
    logging.warn("3")
    logging.error("4")
    logging.critical("5")

if __name__ == "__main__":
  Main.main()

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(5

琴流音 2024-10-14 17:40:20

看起来您已经为处理程序设置了级别,但没有为记录器设置了级别。记录器的级别会在每条消息到达其处理程序之前对其进行过滤,默认值为 WARNING 及以上(如您所见)。将根记录器的级别设置为 NOTSET ,以及将其设置为 DEBUG (或您希望记录的最低级别)应该可以解决您的问题。

It looks like you've set the levels for your handlers, but not your logger. The logger's level filters every message before it can reach its handlers and the default is WARNING and above (as you can see). Setting the root logger's level to NOTSET as you have, as well as setting it to DEBUG (or whatever is the lowest level you wish to log) should solve your issue.

自由如风 2024-10-14 17:40:20

将以下行添加到根记录器可以解决我的问题:

level=NOTSET

Adding the following line to the root logger took care of my problem:

level=NOTSET
冰魂雪魄 2024-10-14 17:40:20

只需在[logger_root]中添加日志级别即可。这是有效的。

[logger_root]
level=DEBUG
handlers=screen,file

Just add log level in [logger_root]. It is worked.

[logger_root]
level=DEBUG
handlers=screen,file
゛清羽墨安 2024-10-14 17:40:20

写入终端和文件的简单方法如下:

import logging.config

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("log_file.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

然后在代码中使用它,如下所示:

logger.info('message')
logger.error('message')

A simple approach to both write to terminal and file would be as following:

import logging.config

logging.basicConfig(
    level=logging.INFO,
    format="%(asctime)s [%(levelname)s] %(message)s",
    handlers=[
        logging.FileHandler("log_file.log"),
        logging.StreamHandler()
    ]
)
logger = logging.getLogger(__name__)

And then use it in your code like this:

logger.info('message')
logger.error('message')
天生の放荡 2024-10-14 17:40:20
#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
from logging.config import dictConfig

logger = logging.getLogger(__name__)

DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
    """
    Initialize logging defaults for Project.

    :param logfile_path: logfile used to the logfile
    :type logfile_path: string

    This function does:

    - Assign INFO and DEBUG level to logger file handler and console handler

    """
    dictConfig(DEFAULT_LOGGING)

    default_formatter = logging.Formatter(
        "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
        "%d/%m/%Y %H:%M:%S")

    file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    file_handler.setFormatter(default_formatter)
    console_handler.setFormatter(default_formatter)

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(file_handler)
    logging.root.addHandler(console_handler)



[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module

我认为你应该将disable_existing_loggers添加为false。

#!/usr/bin/env python
# -*- coding: utf-8 -*-

import logging
import logging.handlers
from logging.config import dictConfig

logger = logging.getLogger(__name__)

DEFAULT_LOGGING = {
    'version': 1,
    'disable_existing_loggers': False,
}
def configure_logging(logfile_path):
    """
    Initialize logging defaults for Project.

    :param logfile_path: logfile used to the logfile
    :type logfile_path: string

    This function does:

    - Assign INFO and DEBUG level to logger file handler and console handler

    """
    dictConfig(DEFAULT_LOGGING)

    default_formatter = logging.Formatter(
        "[%(asctime)s] [%(levelname)s] [%(name)s] [%(funcName)s():%(lineno)s] [PID:%(process)d TID:%(thread)d] %(message)s",
        "%d/%m/%Y %H:%M:%S")

    file_handler = logging.handlers.RotatingFileHandler(logfile_path, maxBytes=10485760,backupCount=300, encoding='utf-8')
    file_handler.setLevel(logging.INFO)

    console_handler = logging.StreamHandler()
    console_handler.setLevel(logging.DEBUG)

    file_handler.setFormatter(default_formatter)
    console_handler.setFormatter(default_formatter)

    logging.root.setLevel(logging.DEBUG)
    logging.root.addHandler(file_handler)
    logging.root.addHandler(console_handler)



[31/10/2015 22:00:33] [DEBUG] [yourmodulename] [yourfunction_name():9] [PID:61314 TID:140735248744448] this is logger infomation from hello module

I think you should add the disable_existing_loggers to false.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文