简体   繁体   English

python日志记录:记录器不会写入文件

[英]python logging: logger wont write to file

Im working on a project with several modules that should all log to the same file. 我在一个带有多个模块的项目上工作,这些模块应该都记录到同一个文件中。

Initializing the logger: 初始化记录器:

parentLogger = logging.getLogger('PARENTLOGGER')
logger = logging.getLogger('PARENTLOGGER.' + __name__)
#set format
fmt = logging.Formatter('%(asctime)s [%(levelname)s] %(name)s: %(message)s')
#set handler for command line
ch = logging.StreamHandler()
ch.setLevel(logging.DEBUG)
ch.setFormatter(fmt)
#set file handler
open('data/logs.log', 'w+').close() #for creating the file in case it doesnt exists. I got exceptions otherwise.
fh = RotatingFileHandler('data/logs.log', maxBytes=5242880, backupCount=1)
fh.setLevel(logging.DEBUG)
fh.setFormatter(fmt)
parentLogger.addHandler(fh)
parentLogger.addHandler(ch)
#

than, on all other modules im calling: 比,在所有其他模块上我调用:

self._logger = logging.getLogger('PARENTLOGGER.' + __name__)

The problem is that the rotating file handler wont write anything to the log file. 问题是旋转文件处理程序不会将任何内容写入日志文件。 In any module. 在任何模块中。

Am I configuring the logger correctly? 我是否正确配置记录器? I've tried several examples from pythons' logging cookbook without success... 我已经尝试了python日志记录手册中的几个示例,但没有成功...

Regards and thanks in advance! 致以诚挚的谢意!

You should tell logging when and what to log. 您应该告诉logging何时以及什么日志。 Also, the log file will be created by default, no need to create it yourself. 另外,默认情况下将创建日志文件,而无需自己创建。 Here's a simple example: 这是一个简单的例子:

$ cat test_log.py
import logging

log = '/home/user/test_log.log'
logging.basicConfig(filename=log,
                    format='%(asctime)s [%(levelname)s]: %(message)s at line: %(lineno)d (func: "%(funcName)s")')

try:
    this_will_fail
except Exception as err:
    logging.error('%s' % err)
$ python test_log.py
$ cat /home/user/test_log.log
2018-02-07 11:31:24,127 [ERROR]: name 'this_will_fail' is not defined at line: 10 (func: "<module>")

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM