从Python中的不同类登录到多个日志文件 [英] Logging to multiple log files from different classes in Python
问题描述
我想编写一个使用Python日志记录的Python类.该Python类将负责在init函数中创建具有给定名称的文件.
I want to write a Python class which uses Python logging. This Python class will be responsible for the creating a file with a given name in init function.
我想在两个或多个类中创建上述类的对象,并期望生成两个或文件.
I want to create a object of the above class in two or more classes and expect two or files getting generated.
我尝试编写此类,但无法创建多个文件.
I tried writing this class but I am not able to create multiple files.
有人可以指导我该怎么做吗?
Can anyone guide me how do I do that?
我创建了以下课程:
class Logger:
def __init__(self, log_filename = "test.log"):
if not os.path.exists("LogFiles"):
os.makedirs("LogFiles")
self.Logger = logging.getLogger("main")
logging.basicConfig(level=logging.DEBUG,
format='%(asctime)s : %(message)s',
filename= log_filename,
filemode='w') # change filemode to 'w' to overwrite file on each run
consoleHandler = logging.StreamHandler()
consoleHandler.setLevel(logging.DEBUG)
formatter = logging.Formatter('%(asctime)s - %(message)s')
consoleHandler.setFormatter(formatter)
logging.getLogger('').addHandler(consoleHandler) # Add to the root logger
self.Logger.info("Starting new logging sessions")
def writeToFile(self, line):
if self.Logger.propagate == True:
self.Logger.debug(line)
def closeFile(self):
if self.Logger.propagate == True:
self.Logger.propagate = False
推荐答案
类似您课程内部的声音应该具有 FileHandler
到Logger
.您可能要考虑只使用创建Logger
并添加处理程序的工厂方法,而不是实现自己的类.您可能需要创建用于保存日志文件的目录.请参见此答案以获取有关创建目录的建议.
Sounds like the internals of your class should probably have a Logger
and that you'll want to add a FileHandler
to the Logger
. You might want to consider just using a factory method that creates Logger
s and adds the handler instead of implementing your own class. You may need to create the directories that hold the log files. See this answer for advice on creating directories.
我认为您不需要编写自己的Logger
类. Python的logging
模块具有您需要的所有内容.您可能只需要一种工厂方法.要实现的关键是您需要创建两个单独的,完全独立的日志记录对象.您可以使用logging.getLogger
进行此操作,并且每次给它传递一个不同的名称时,它都会为您提供一个不同的记录器.您可以使用所需的任何名称作为记录器的名称.当然,您想要远离basicConfig
所做的事情.对于只希望Logger
不做任何特别事情的人来说,它的设计很简单.
I don't think you need to write your own Logger
class. Python's logging
module has all the pieces you need. You probably just need a factory method. The key to realize is you need to create two separate, completely independent logging objects. You do this with logging.getLogger
, and any time you pass it a different name, it gives you a different logger. You can use anything you want for the logger's name. For sure, you want to stay away from basicConfig
for what you're doing. It's designed to be something simple for people who just want one Logger
not doing anything too special.
我认为这证明了您所追求的功能.关键是用不同的处理程序创建两个不同的记录器.然后分别使用它们.请记住,我第二次调用logging.getLogger
不会创建新的记录器;它得到了我们最初在setup_logger
中设置的那个.
I think this demonstrates the functionality you're after. The key is create two different loggers with different handlers. Then use them separately. Keep in mind that my second call to logging.getLogger
doesn't create a new logger; it gets the one we set up initially in setup_logger
.
log_test.py:
log_test.py:
from __future__ import absolute_import
import logging
def setup_logger(logger_name, log_file, level=logging.INFO):
l = logging.getLogger(logger_name)
formatter = logging.Formatter('%(asctime)s : %(message)s')
fileHandler = logging.FileHandler(log_file, mode='w')
fileHandler.setFormatter(formatter)
streamHandler = logging.StreamHandler()
streamHandler.setFormatter(formatter)
l.setLevel(level)
l.addHandler(fileHandler)
l.addHandler(streamHandler)
def main():
setup_logger('log1', r'C:\temp\log1.log')
setup_logger('log2', r'C:\temp\log2.log')
log1 = logging.getLogger('log1')
log2 = logging.getLogger('log2')
log1.info('Info for log 1!')
log2.info('Info for log 2!')
log1.error('Oh, no! Something went wrong!')
if '__main__' == __name__:
main()
样品运行:
C:\temp>C:\Python\27\python.exe logtest.py
2013-06-12 02:00:13,832 : Info for log 1!
2013-06-12 02:00:13,832 : Info for log 2!
2013-06-12 02:00:13,832 : Oh, no! Something went wrong!
log1.log:
2013-06-12 02:00:13,832 : Info for log 1!
2013-06-12 02:00:13,832 : Oh, no! Something went wrong!
log2.log:
2013-06-12 02:00:13,832 : Info for log 2!
这篇关于从Python中的不同类登录到多个日志文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!