Python记录 - 如何在循环中添加每个迭代的新日志文件?
我正在尝试使用以下方式在循环中为每次迭代生成新的日志文件:
def custlogger(Filename,loglevel=logging.DEBUG):
# set method name from where its called
logger_name = inspect.stack()[1][3]
# create logger
logger = logging.getLogger(logger_name)
logger.setLevel(loglevel)
# create console handler of file handler and set log level
file_handler = logging.FileHandler(filename=Filename)
# create formatter
formatter = logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')
# add formatter to console or file handler
file_handler.setFormatter(formatter)
# add console handler to loogger
logger.addHandler(file_handler)
然后我调用newlogger = Custlogger(NewFilename)
,并在每次迭代末尾关闭日志记录。 )在循环中。这是正确的方法吗?
这是我如何使用它的示例:
def analyze_scds_files(scds_directory, sample_name):
logfile = scds_directory+'/log_'+sample_name+'.txt'
newlogger = custlogger(logfile,logging.ERROR)
try:
dosomething()
except Exception as e:
newlogger.logger.exception('error while trying to ...: ')
sys.exit()
.
.
.
# Shut down the logger
logging.shutdown()
return status
I am trying to generate new log file for each iteration in a loop using:
def custlogger(Filename,loglevel=logging.DEBUG):
# set method name from where its called
logger_name = inspect.stack()[1][3]
# create logger
logger = logging.getLogger(logger_name)
logger.setLevel(loglevel)
# create console handler of file handler and set log level
file_handler = logging.FileHandler(filename=Filename)
# create formatter
formatter = logging.Formatter('%(asctime)s,%(msecs)d %(name)s %(levelname)s %(message)s')
# add formatter to console or file handler
file_handler.setFormatter(formatter)
# add console handler to loogger
logger.addHandler(file_handler)
and I call the newlogger = custlogger(newfilename)
and shut down logging at the end of each iteration logging.shutdown()
inside the loop. Is this the right way to do it?
Here is an example how I am using it:
def analyze_scds_files(scds_directory, sample_name):
logfile = scds_directory+'/log_'+sample_name+'.txt'
newlogger = custlogger(logfile,logging.ERROR)
try:
dosomething()
except Exception as e:
newlogger.logger.exception('error while trying to ...: ')
sys.exit()
.
.
.
# Shut down the logger
logging.shutdown()
return status
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
建议,有点记录的问题,将其从弹奏中移出并打电话给标头(1倍,您正在重新启动)
的最小模式是:
首先将其打印在终端中,然后添加格式和其他功能。亲吻v1,然后拟合。
Suggestions, a little under documented question, Move this out of func and call in header (1x, you are redeclaring)
The minimal pattern is:
Get it to print in terminal first, then add formatting and other features. KISS v1, then complify.