我一直在学习日志,并在这里得到了关于设置带有外部配置文件的记录器的帮助。在
我已经根据示例进行了设置,但是消息只在控制台上看到,在长文件中看不到(不是创建的)。在
你能看看我做错了什么吗?在
效用记录器:
#!/usr/bin/env python
# -*- coding: utf-8 -*-
'''
My app
'''
# ~~~~~ LOGGING SETUP ~~~~~ #
# set up the first logger for the app
import os
import testLogging as vlog
# path to the current script's dir
scriptdir = os.path.dirname(os.path.realpath(__file__))
LOG_CONFIG = '../config/logging.conf'
print scriptdir
def logpath():
'''
Return the path to the main log file; needed by the logging.yml
use this for dynamic output log file paths & names
'''
global scriptdir
return (vlog.logpath(scriptdir = scriptdir, logfile = 'log.txt'))
logger = vlog.log_setup(config_file=LOG_CONFIG, logger_name="app")
logger.debug("App is starting...")
测试日志记录:
^{pr2}$在日志记录.conf文件:
[loggers]
keys=root
[handlers]
keys=consoleHandler
[formatters]
keys=simpleFormatter
[logger_root]
level=DEBUG
handlers=consoleHandler
qualname=app
[logger_app]
level=DEBUG
handlers=consoleHandler
qualname=app
propagate=true
[handler_consoleHandler]
class=StreamHandler
level=DEBUG
formatter=simpleFormatter
args=(sys.stdout,)
[handler_fileHandler]
class=FileHandler
level=DEBUG
formatter=fileFormatter
args=('%(logfilename)s',)
[main]
()=__main__.logpath
level=DEBUG
formatter=simpleFormatter
[formatter_fileFormatter]
format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %
(message)s # %(module)s:
datefmt="%Y-%m-%d %H:%M:%S"
[formatter_simpleFormatter]
format=%(asctime)s (%(name)s:%(funcName)s:%(lineno)d:%(levelname)s) %(message)s # %(module)s:
datefmt="%Y-%m-%d %H:%M:%S"
更新,问题已标记为已回答,感谢@zwer帮助!在
最后一个目标是要理解的是,有没有更多的python方法来实例化一个logger到类(但我也希望能够登录main)。有了明确的答案,我把下面的内容放在一起,但我不确定这是main和类日志记录的最优雅的解决方案。在
class TestLog(object):
def __init__(self, logger):
self.logger = logger
self.__sub_test = 0
def add_test(self):
self.logger.debug('addition')
a = 1 + 1
self.logger.debug('result {}'.format(a, 1))
def sub_test(self):
self.logger.debug('subtraction')
b = 5 -2
self.logger.debug('result {}'.format(b, 1))
def main():
logger = vlog.log_setup(config_file=LOG_CONFIG, logger_name="app",
log_file=LOG_PATH)
logger.debug("App is starting...")
test1 = TestLog(logger)
print test1.add_test()
print test1.sub_test()
if __name__ == "__main__":
sys.exit(main())
好吧,让我们把它打包成一个答案来避免注释限制。在
配置的主要问题是根本没有初始化fileHandler。如果要使用它,请确保将其添加到
[handlers]
部分,例如:至于您的另一个错误,因为在您的
^{pr2}$[handler_fileHandler]
中,您为文件名定义了一个动态参数logfilename
,因此在Python中加载日志配置时需要提供它,例如:这应该能解决问题。在
更新-只要您提供一个正确的文件路径,所述的应该可以工作,但是您仍然需要稍微修改一下配置,以便在所有日志记录器中启用文件记录器。因此,请将配置更改为:
另外,要使其更灵活,请将
testLogging.log_setup()
更改为如下内容:最后,当您设置它时,只需将其调用为:
根据您的本地路径进行了调整,它应该可以按预期工作。我只是在我这边做了测试,结果很好。在
相关问题 更多 >
编程相关推荐