日志的配置文件
import os
PROJECT_NAME = "monitor_demo"
TOOLS_PROJECT_NAME = "monitor_tools"
LOG_LEVEL = os.getenv('LOG_LEVEL', "DEBUG")
LOG_HANDLERS = os.getenv('LOG_HANDLERS', "console,file")
BACKUP_COUNT = int(os.getenv("BACKUP_COUNT", "500"))
LOG_INTERVAL = int(os.getenv("LOG_INTERVAL", "1"))
LOG_WHEN = os.getenv("LOG_WHEN", "midnight")
LOG_NAME = os.getenv("LOG_NAME", "tornado")
TOOLS_SCHED_NAME = "sched_tasks"
TOOLS_ANA_MONGO_NAME = "analysis_mongo"
BASE_DIR = "/opt/logs"
PROJECT_LOG_DIR = BASE_DIR + "/" + PROJECT_NAME
TOOLS_PROJECT_LOG_DIR = PROJECT_LOG_DIR + "/" + TOOLS_PROJECT_NAME
if not os.path.exists(PROJECT_LOG_DIR):
os.makedirs(PROJECT_LOG_DIR)
if not os.path.exists(TOOLS_PROJECT_LOG_DIR):
os.makedirs(TOOLS_PROJECT_LOG_DIR)
file_name = "".join([PROJECT_LOG_DIR, "/", LOG_NAME, '.log'])
sched_tasks = "".join([TOOLS_PROJECT_LOG_DIR, "/", TOOLS_SCHED_NAME, ".log"])
analysis_mongo = "".join([TOOLS_PROJECT_LOG_DIR, "/", TOOLS_ANA_MONGO_NAME, ".log"])
LOG_CONF = {
'version': 1,
'disable_existing_loggers': False,
'root': {
'level': 'WARNING',
'handlers': ['file']
},
'formatters': {
'verbose': {
'format': '{asctime} {levelname} {filename}:{lineno} '
'pid/tid: {process:d}/{thread:d} message: {message}',
'style': '{',
},
'simple': {
'format': '{levelname} {message}',
'style': '{',
},
},
'handlers': {
'console': {
'level': LOG_LEVEL,
'formatter': 'verbose',
'class': 'logging.StreamHandler',
},
'file': {
'level': LOG_LEVEL,
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': LOG_WHEN,
'interval': LOG_INTERVAL,
'filename': file_name,
'formatter': 'verbose',
'backupCount': BACKUP_COUNT,
},
'sched_tasks': {
'level': LOG_LEVEL,
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': LOG_WHEN,
'interval': LOG_INTERVAL,
'filename': sched_tasks,
'formatter': 'verbose',
'backupCount': BACKUP_COUNT,
},
'analysis_mongo': {
'level': LOG_LEVEL,
'class': 'logging.handlers.TimedRotatingFileHandler',
'when': LOG_WHEN,
'interval': LOG_INTERVAL,
'filename': analysis_mongo,
'formatter': 'verbose',
'backupCount': BACKUP_COUNT,
},
},
'loggers': {
'tornado': {
'handlers': LOG_HANDLERS.split(","),
'level': LOG_LEVEL,
'propagate': True
},
'sched': {
'handlers': ['sched_tasks'],
'level': LOG_LEVEL,
'propagate': True
},
'analysis': {
'handlers': ['analysis_mongo'],
'level': LOG_LEVEL,
'propagate': True
},
}
}
日志使用
import logging.config
logging.config.dictConfig(LOG_CONF)
logger = logging.getLogger('analysis')
LOG等级
DEBUG logging.debug() 最低级别,追踪问题时使用
INFO logging.info() 记录程序中一般事件的信息,或确认一切工作正常
WARNING logging.warning() 记录信息,用于警告
ERROR logging.error() 用于记录程序报错信息
CRITICAL logging.critical() 最高级别,记录可能导致程序崩溃的错误