# -*- coding: utf-8 -*-
import os
import logging
import datetime


def get_logger(directory, name):
    """
    """
    logger = logging.getLogger(name)
    logger.setLevel(logging.INFO)
    date_handler = DateFileHandler(directory, name)
    fmt_str = '%(asctime)s %(process)d %(module)s.%(funcName)s.%(lineno)d %(levelname)s : %(message)s'
    fmt = logging.Formatter(fmt_str, datefmt='%Y-%m-%d %H:%M:%S')
    date_handler.setFormatter(fmt)
    logger.addHandler(date_handler)
    return logger


class DateFileHandler(logging.StreamHandler):
    """
    log by date file
    """
    def __init__(self, directory, log_name='', mode='a'):
        self.directory = directory
        self.log_name = log_name
        self.mode = mode
        self.last_date = None
        logging.StreamHandler.__init__(self, self._open())

    def close(self):
        """
        Closes the stream.
        """
        self.acquire()
        try:
            if self.stream:
                self.flush()
                if hasattr(self.stream, "close"):
                    self.stream.close()
                logging.StreamHandler.close(self)
                self.stream = None
        finally:
            self.release()

    def gen_file_name(self):
        self.last_date  = datetime.datetime.now().date()
        log_directory = '%s/%04d-%02d' % (self.directory, self.last_date.year, self.last_date.month)
        os.system("mkdir -p %s" % log_directory)
        log_file = '%s/%s.%s.log' % (log_directory, self.last_date.day, self.log_name)
        return log_file

    def 
(self):
        log_file = self.gen_file_name()
        stream = open(log_file, self.mode)
        return stream

    def should_roll(self):
        date = datetime.datetime.now().date()
        if date == self.last_date:
            return False
        else:
            return True

    def emit(self, record):
        """
        Emit a record.
        """
        if self.should_roll():
            self.close()
        if self.stream is None:
            self.stream = self._open()
        logging.StreamHandler.emit(self, record)

_open