【发布时间】:2020-05-21 14:33:48
【问题描述】:
我正在创建集中式日志记录。这基本上看起来像下面的脚本。
logit 模块将根据调用它的脚本名称创建一个文件。在这种情况下 apiCaller。
最初我在调用 logit 时手动定义了这个,但是我正在寻找 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 的名称。
【问题讨论】:
-
你可以使用
%(module)s日志格式化器,见docs.python.org/2/library/logging.html的LogRecord属性部分 -
当你做
logging.getLogger时,你应该把__name__作为参数。__name__是模块本身的名称(如果已导入)或"__main__"(如果文件作为脚本运行)。然后日志格式化程序完成剩下的工作。 -
如何从其他脚本调用您的脚本?什么是
logit.py,为什么上面会打印test? -
@Dan 那个“模块”返回的是 logit 模块,而不是调用 logit 模块的那个。
-
@h4z3 name 只返回 logit 包结构(父母等)
标签: python python-3.x