python自定义logger日志输出文件

为什么要写日志?
方便维护、方便调试代码、项目上线后,发现错误能快速定位到错误代码。

web_logging.py

# -*- coding:utf-8 -*-

# [logger]

# 默认日志格式
DEFAULT_LOG_FMT = '%(asctime)s %(filename)s [line:%(lineno)d] %(levelname)s: %(message)s'
# 默认时间格式
DEFUALT_LOG_DATEFMT = '%Y-%m-%d %H:%M:%S'
# 输出日志路径
import os
LOG_OUT_PATH = os.path.abspath('.') + '/logs/'

import sys
import logging
from time import strftime


class Logger(object):
    def __init__(self):
        self._logger = logging.getLogger()
        self.DEFAULT_LOG_FILENAME = '{0}{1}.log'.format(LOG_OUT_PATH, strftime("%Y-%m-%d"))
        self.formatter = logging.Formatter(fmt=DEFAULT_LOG_FMT, datefmt=DEFUALT_LOG_DATEFMT)
        self._logger.addHandler(self._get_file_handler(self.DEFAULT_LOG_FILENAME))
        self._logger.addHandler(self._get_console_handler())
        self._logger.setLevel(logging.INFO)  # 默认等级

    def _get_file_handler(self, filename):
        filehandler = logging.FileHandler(filename, encoding="utf-8")
        filehandler.setFormatter(self.formatter)
        return filehandler

    def _get_console_handler(self):
        console_handler = logging.StreamHandler(sys.stdout)
        console_handler.setFormatter(self.formatter)
        return console_handler

    @property
    def logger(self):
        return self._logger

test.py

from web_logging import Logger
logging = Logger().logger

 logging.info(u"{}:开始XXX操作".format(datetime.datetime.now()))

你可能感兴趣的:(python)