日志配置

#!/usr/bin/python2.7

import os
import logging def get_logger(path='./', filename='access.log', level='debug'):
log_level = {
'debug':logging.DEBUG,
'info':logging.INFO,
'warning':logging.WARNING,
'error':logging.ERROR,
'critical':logging.CRITICAL
}
level = 'debug' if level not in log_level else level file = os.path.join(path,filename)
formatter = logging.Formatter('"%(asctime)s" "%(filename)s[line:%(lineno)d]" "%(levelname)s" "%(message)s"')
handler = logging.FileHandler(file, mode='a')
# handler.setLevel(log_level[level])
handler.setFormatter(formatter) logger = logging.getLogger(__name__)
logger.setLevel(log_level[level])
logger.addHandler(handler) return logger

logging模块简单使用-LMLPHP

注意logger.setLevel 和 handler.setLevel 是不一样的。

给日志每个字段加上双引号,方便后面结合awk进行统计分析

awk -F \" '{print $2}' analysis.log

项目里的应用

定义

import logging

logger = logging.getLogger("HorizonLog")  # 指定一个名称
logger.setLevel(logging.DEBUG)
formatter = logging.Formatter("%(asctime)s :: %(process)s :: %(message)s", datefmt="%Y-%m-%d %H:%M:%S")
handler = logging.FileHandler(settings.LOG_PATH + '/horizon.log')
handler.setFormatter(formatter)
logger.addHandler(handler)

使用

# Return a logger with the specified name or,
# if no name is specified, return a logger which is the root logger of the hierarchy. logger = logging.getLogger("HorizonLog") logger.info(...)
logger.warning(...)
logger.error(...)
05-11 01:01