使用 Python 日志记录管理记录器

发布于 2024-10-01 13:19:07 字数 709 浏览 1 评论 0原文

我正在编写一个服务器应用程序,它应该能够在控制台和日志文件上以不同级别进行日志记录。

问题是,如果设置了logging.basicConfig(),它将记录到控制台,但必须在主线程中设置。

也可以使用 logging.basicConfig(filename='logger.log') 设置以写入文件。

设置控制台日志记录 (logging.StreamHandler()) 或文件日志记录 (logging.FileHandler()) 的句柄是对 logging.baseconfig() 的补充。代码>选项集。

问题是,设置不是独立的。 我的意思是,logging.baseConfig()的日志级别必须包含Handler级别,否则不会被记录。

因此,如果我将 baseConfig 设置为记录到文件,并将 StreamHandler 设置为记录到控制台,则文件日志级别必须低于控制台级别。 (此外,basicConfig 选项会记录所有其他日志。)

我尝试创建两个句柄,一个用于控制台,一个用于日志文件,它们可以工作,但是无论 指定什么日志类型basicConfig() 仍将显示重复消息。

有没有办法禁用 basicConfig() 的输出? 或者还有其他方式来实现这些选项吗?

I'm writing a server app which should be able to log at different levels both on the console and a log file.

The problem is, if logging.basicConfig() is set it will log to the console but it must be set in the main thread.

It can also be set with logging.basicConfig(filename='logger.log') to write to a file.

Setting a handle either for console logging (logging.StreamHandler()) or file logging (logging.FileHandler()) complements the logging.baseconfig() option set.

The problem is, that the settings are not independent.
What I mean is, the loglevel of logging.baseConfig() must include the Handler level, or it wont be logged.

So if I set the baseConfig to log to file, and a StreamHandler to log to console, the file loglevel must be lower than the console level.
(Also, the basicConfig option logs all other logs.)

I tried to create two Handles, one for the console and one for the log file, they work, but whatever log type is specified by basicConfig() will still be displayed duplicating messages.

Is there a way to disable the output of basicConfig()?
Or any other way to implement these options?

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

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

发布评论

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

评论(2

君勿笑 2024-10-08 13:19:07

您在问题中没有确切说明您想要在控制台和文件日志记录上达到什么级别。但是,您不需要调用 basicConfig(),因为它只是一个便利函数。您可以执行例如(刚刚输入的代码,未测试):

import logging

logger = logging.getLogger(__name__)
configured = False

def configure_logging():
    global configured
    if not configured:
        logger.setLevel(logging.DEBUG) # or whatever
        console = logging.StreamHandler()
        file = logging.FileHandler('/path/to/file')
        #set a level on the handlers if you want;
        #if you do, they will only output events that are >= that level
        logger.addHandler(console)
        logger.addHandler(file)
        configured = True

首先将事件传递给记录器,如果要处理事件(由于比较记录器和事件的级别),则将事件传递给每个记录器记录器的处理程序及其所有祖先的处理程序。如果在处理程序上设置了级别,则该处理程序可能会删除该事件,否则它将输出该事件。

You don't say in your question exactly what levels you want on your console and file logging. However, you don't need to call basicConfig(), as it's only a convenience function. You can do e.g. (code just typed in, not tested):

import logging

logger = logging.getLogger(__name__)
configured = False

def configure_logging():
    global configured
    if not configured:
        logger.setLevel(logging.DEBUG) # or whatever
        console = logging.StreamHandler()
        file = logging.FileHandler('/path/to/file')
        #set a level on the handlers if you want;
        #if you do, they will only output events that are >= that level
        logger.addHandler(console)
        logger.addHandler(file)
        configured = True

Events are passed to the logger first, and if an event is to be processed (due to comparing the level of the logger and the event) then the event is passed to each handler of the logger and all its ancestors' handlers as well. If a level is set on a handler the event may be dropped by that handler, otherwise it will output the event.

瞳孔里扚悲伤 2024-10-08 13:19:07

找到下面的示例代码来处理各种异常的日志记录

import mysql.connector
import logging
logging.basicConfig(filename=r'C:\Users\root\Desktop\logs.txt',level=logging.DEBUG,format='%(asctime)s,%(levelname)s:%(message)s',datefmt='%d-%m-%Y %H:%M:%S')

while True:
    try:
        mydb=mysql.connector.connect(host='localhost',user='root',passwd='password123', database='shiva')

        mycursor=mydb.cursor()
        logging.info("Connected mysql db successfully...\n")
        mycursor.execute("show databases")
        mycursor.execute("Create table employee(name varchar(20), salary float(20))")
        mydb.commit()
    except Exception as e:
        logging.info("Trying to Connect MysqlDB...")
        logging.critical("Error Occured While Connecting...\n\n" "CAUSEDBY: "+str(e))
        logging.warning("Check Login Credentials.")
        

Find the below example code to handle the logging with all kind of exceptions

import mysql.connector
import logging
logging.basicConfig(filename=r'C:\Users\root\Desktop\logs.txt',level=logging.DEBUG,format='%(asctime)s,%(levelname)s:%(message)s',datefmt='%d-%m-%Y %H:%M:%S')

while True:
    try:
        mydb=mysql.connector.connect(host='localhost',user='root',passwd='password123', database='shiva')

        mycursor=mydb.cursor()
        logging.info("Connected mysql db successfully...\n")
        mycursor.execute("show databases")
        mycursor.execute("Create table employee(name varchar(20), salary float(20))")
        mydb.commit()
    except Exception as e:
        logging.info("Trying to Connect MysqlDB...")
        logging.critical("Error Occured While Connecting...\n\n" "CAUSEDBY: "+str(e))
        logging.warning("Check Login Credentials.")
        
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文