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

# Copyright 2008-2012 Calculate Ltd. http://www.calculate-linux.org
#
#  Licensed under the Apache License, Version 2.0 (the "License");
#  you may not use this file except in compliance with the License.
#  You may obtain a copy of the License at
#
#      http://www.apache.org/licenses/LICENSE-2.0
#
#  Unless required by applicable law or agreed to in writing, software
#  distributed under the License is distributed on an "AS IS" BASIS,
#  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
#  See the License for the specific language governing permissions and
#  limitations under the License.

import logging
import logging.handlers
import cl_overriding

class log:
    def __init__(self, programName,
                 level=logging.DEBUG,
                 formatter=\
                         "%(asctime)s - %(name)s - %(levelname)s - %(message)s",
                 filename='/var/log/calculate/calculate2.log',
                 maxBytes=1048576,
                 backupCount=5):
        self.programName = programName
        self.logger = logging.getLogger(self.programName)
        self.level = level
        self.logger.setLevel(self.level)
        self.formatter = logging.Formatter(formatter)
        self.filename = filename
        self.maxBytes=maxBytes
        self.backupCount=backupCount

    def addHandler(self):
        """Добавление обработчика"""
        if not self.logger.handlers:
            try:
                handler = logging.handlers.RotatingFileHandler(self.filename,
                                                  maxBytes=self.maxBytes,
                                                  backupCount=self.backupCount)
            except Exception, e:
                cl_overriding.printERROR("logging - "+" "+self.programName+\
                                         " - "+str(e))
                return False
            handler.setLevel(self.level)
            handler.setFormatter(self.formatter)
            self.logger.addHandler(handler)
        return True

    def _addLogMessage(self,typeMessage,message):
        """Добавить сообщение данного типа"""
        if self.addHandler():
            getattr(self.logger,typeMessage)(message)

    def debug(self, message):
        """Отладочное сообщение"""
        self._addLogMessage("debug", message)

    def info(self, message):
        """Информационное сообщение"""
        self._addLogMessage("info", message)

    def warn(self, message):
        """Предупреждающее сообщение"""
        self._addLogMessage("warn", message)

    def error(self, message):
        """Сообщение о ошибке"""
        self._addLogMessage("error", message)

    def critical(self, message):
        """Критическое сообщение"""
        self._addLogMessage("critical", message)
