我正在创建集中式日志记录。这基本上与下面的脚本类似
logit模块将根据调用它的脚本名称创建一个文件。在这种情况下,apiCaller
最初,我在调用logit时手动定义了它,但是我正在搜索away for logit以确定日志本身的来源
这里有3个模块:
main.py:
def runAnalytic(script):
importlib.import_module("monitoringScripts."+script["package"]+"."+script["module"], package=None)
packageModule = [{"package":"awesome","module":"apiCaller"}]
with concurrent.futures.ThreadPoolExecutor() as executor:
results = executor.map(runAnalytic, packageModule)
apiCaller.py(上面的模块)
from adminTools.logger import logit
logit.create(results[i]["items"][r]["userId"],"apiCaller") #How i currently pass the script name, i want to get rid of this.
logit.py处理所有其他脚本所需的所有日志(集中式日志)
import sys, logging, logging.handlers, pathlib
#Path for all log files for scriptHub
logdir = str(pathlib.Path(__file__).parent.absolute())
#Creates the log file based on a given name from the script
def create(logMessage,scriptName, level="DEBUG"):
#create filename
log_filename = logdir+"/sysLogs/"+scriptName+".logs"
#Creates the logging object
my_logger = logging.getLogger(scriptName)
my_logger.setLevel(logging.DEBUG)
#Formats the log:
formatter = logging.Formatter('%(asctime)s - %(message)s - %(name)s')
#Gives the log file a limit for 100mb if it goes bigger than this, it will create another file, but keep the old one
handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes=100000000, backupCount=1)
handler.setFormatter(formatter)
#Handlers need to be cleared to stop duplicated logs.
if (my_logger.hasHandlers()):
my_logger.handlers.clear()
my_logger.addHandler(handler)
#creates the log message
my_logger.debug(logMessage)
所以,我不确定这对你们是有帮助还是有阻碍,哈哈
本质上,我希望logit从调用它的模块中获取脚本名,而不是向logit提供脚本名。例如,在本例中,“apiCaller”将是传递给logit的名称
好的,有一个重写的问题:
我看到它是以另一种方式完成的,而不是您这样做的——获取一个记录器,然后设置它(模块中有两行,而不是一行)。记录器是每个模块的东西,并且始终存在
在您的情况下,每次都重新获取记录器并重新生成处理程序
这样你就不能利用
logging
模块提供的美丽的可能性因此,基本上,另一种方法是:
在每个脚本中执行
logger = logging.getLogger(__name__)
,通常位于导入下方的顶部附近+您只需调用
logit.setupLogger(logger)
。(在您的情况下,在下一行中。在脚本的情况下,我将它保留在main函数中-这样,如果我将脚本作为模块导入,我将调用imported_module.logger
上需要的任何日志设置,以便它不会垃圾邮件发送错误的日志文件。:D)重写
logit.py
:这样,您只需在
logit
中设置记录器的内部(包括文件处理程序),并且可以使用标准的logging
东西:logit.setupLogger(logger)
更改为logit.setupLogger(logger, logging.INFO)
或任何您需要的级别李>按照您的方式记录日志似乎是一个好主意,但是
logging
模块在您学习如何使用它时非常强大Here's a How-To from Python's docs,但是它有很多信息,所以simpler tutorials on python logging是一个更好的开始Tbh我也从我自己的日志记录实践开始,甚至在阅读了文档和教程之后,因为我根本不懂。当我在使用的库中看到它时,我才切换到上面的方法。:)
这个问题不是很清楚,但是你可以使用
inspect.stack()
loggy.py
thing.py
相关问题 更多 >
编程相关推荐