#!/usr/bin/python
#coding:utf-8


########################################################
#   打印日志
#   添加环境变LOG_STDOUT，可将 日志信息打印到控制台
#   $ export LOG_STDOUT=stdout:$LOG_STDOUT
#
#########################################################
import logging.handlers
import os
import sys

if __name__ == "__main__":
    LOG_DIR="./"
    LOG_PATH="log1.txt"
else:
    LOG_DIR="/mcos/dvclient/log/"
    LOG_PATH="/mcos/dvclient/log/dv_client.log"


##################################
#   类声明
#   单例模式
##################################
class LogRecord():
    _instance = 0
    def __init__(self):
        LogRecord._instance = self
        if False == os.path.isdir(LOG_DIR):
            os.makedirs(LOG_DIR)

        # if os.path.isfile(LOG_PATH):
        #     size = os.path.getsize(LOG_PATH) # 文件大小
        #     if size > 1000000:
        #         size_in_MB = size/1000000.0
        #         if size_in_MB > 5:
        #             os.system("rm -f %s" % LOG_PATH)

        self.logger = logging.getLogger(LOG_PATH) # 获取Loger对象

        handler = logging.handlers.RotatingFileHandler(LOG_PATH, maxBytes = 1024*1024, backupCount = 5) # 实例化handler
        fmt = '%(asctime)s - %(filename)s:%(lineno)s - %(name)s - %(levelname)s - %(message)s'

        formatter = logging.Formatter(fmt)            # 实例化formatter
        handler.setFormatter(formatter)               # 为handler添加formatter
        self.logger.addHandler(handler)               # 为logger添加handler

        log_env = os.getenv('LOG_STDOUT')             # 读取环境变量
        if 0 == str(log_env).find('stdout') :         #
            handler_output=logging.StreamHandler(sys.stdout) # 输出到打印 handler
            self.logger.addHandler(handler_output)           # 设置输出到打印

        # self.logger.setLevel(logging.NOTSET)   # notset模式
        self.logger.setLevel(logging.DEBUG)      # debug模式
        # self.logger.setLevel(logging.INFO)     # info模式
        #self.logger.setLevel(logging.WARNING)   # warning模式
        #self.logger.setLevel(logging.ERROR)     # error模式
        #self.logger.setLevel(logging.CRITICAL)  # critical模式

    @classmethod
    def instance(cls):
        if (cls._instance == 0):
            cls._instance = LogRecord()
        return cls._instance

#########################################
### 单元测试
#########################################
if __name__ == "__main__":

    LogRecord.instance().logger.debug("debug")
    LogRecord.instance().logger.info("info")
    LogRecord.instance().logger.warn("warn")
    LogRecord.instance().logger.error("erro")
    LogRecord.instance().logger.critical(u"critical")
    LogRecord.instance().logger.exception("异常")
