Python 日志。同一项目不同日志文件
我想把日志记录到不同的文件里。目前,我所有的日志都写在同一个文件里。
我有两个文件:
- extract.py
- insert.py
extract.py 会调用 insert.py。
在我的 extract.py 里:
import insert
import logging
logging.basicConfig(filename='log/extract.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)
在我的 insert.py 里:
import logging
logging.basicConfig(filename='log/insert.log', level=logging.DEBUG, format='%(asctime)s - %(levelname)s - %(message)s')
现在的问题是,所有的日志都被发送到了 insert.log 这个文件里。我该怎么做才能把 extract.py 生成的日志记录到 extract.log 里,而把 insert.py 生成的日志记录到 insert.log 里呢?
谢谢!
2 个回答
0
只需把这个放到你的 extract.py 文件里就可以了(这在 python2.7 及以上版本和 python3.2 及以上版本都能用):
import logging
import logging.config
LOGGING = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(levelname)s:%(name)s: %(message)s '
'(%(asctime)s; %(filename)s:%(lineno)d)',
'datefmt': "%Y-%m-%d %H:%M:%S",
}
},
'handlers': {
'extract_rotate_file': {
'level': 'DEBUG',
'formatter': 'standard',
'class' : 'logging.handlers.RotatingFileHandler',
'filename' : 'extract.log',
'encoding': 'utf8',
'maxBytes': 1024*1024*2, # 2 MB
'backupCount': 5,
},
'insert_rotate_file': {
'level': 'DEBUG',
'formatter': 'standard',
'class' : 'logging.handlers.RotatingFileHandler',
'filename' : 'insert.log',
'encoding': 'utf8',
'maxBytes': 1024*1024*2, # 2 MB
'backupCount': 5,
}
},
'loggers': {
'extract': { # <-- put here name of your logger in extract.py
'handlers': ['extract_rotate_file'],
'level': 'DEBUG',
},
'insert': { # <-- put here name of your logger in insert.py
'handlers': ['insert_rotate_file'],
'level': 'DEBUG',
},
}
}
logging.config.dictConfig(LOGGING)
不过要注意你日志记录器的准确名称,可以在上面的代码中找 # <--
。
1
你需要准备两个记录器,每个记录器都有自己的文件处理器。每个文件的内容如下:
log= logging.getLogger(__name__)
hdlr = logging.FileHandler(__name__+'.log', mode="w")
log.addHandler(hdlr)
log.setLevel(logging.DEBUG)
然后在log
中调用记录功能,而不是直接使用logging
模块。
log.debug("my message")
一般来说,Python的文档质量非常高。在logging
文档中包含的高级教程讲解了这个问题以及更多内容。