作者StubbornLin (鍵盤創業家)
看板Python
標題Re: [心得] Python Logging
時間Sat Aug 4 00:22:45 2012
※ 引述《timTan (用口頭禪區分年記)》之銘言:
: 大家好,這是我最近寫下來的 Python Logging 心得,希望對大家有幫助。
: http://www.icoding.co/2012/08/logging.html
直接回覆好了
現在可以用 yaml 讓它的 dictConfig 去吃
比起那醜不拉機又很難寫的 .ini 好太多了
給個從我的程式裡出來的片段
def setup_logging(
default_path='logging.yaml',
default_level=logging.INFO,
env_key='LOG_CFG'
):
"""Setup logging configuration
"""
path = default_path
value = os.getenv(env_key, None)
if value:
path = value
if os.path.exists(path):
with open(path, 'rt') as f:
config = yaml.load(f.read())
logging.config.dictConfig(config)
else:
logging.basicConfig(level=default_level)
setup_logging()
而 yaml 的範例
---
version: 1
formatters:
simple:
format: "%(asctime)s - %(name)s - %(levelname)s - %(message)s"
handlers:
console:
class: logging.StreamHandler
level: DEBUG
formatter: simple
stream: ext://sys.stdout
error_file_handler:
class: logging.handlers.RotatingFileHandler
level: ERROR
formatter: simple
filename: logs/errors.log
maxBytes: 10485760 # 10MB
backupCount: 20
encoding: utf8
root:
level: INFO
handlers: [console, error_file_handler]
loggers:
usage:
level: INFO
handlers: [console]
propagate: False
...
--
※ 發信站: 批踢踢實業坊(ptt.cc)
◆ From: 118.170.211.196
推 timTan:清楚多了!! 08/04 10:20
推 cobrasgo:喔喔喔,我還不知道有這東西,感謝 08/05 02:08