Modified class log

develop
Самоукин Алексей 15 years ago
parent cf419d8b01
commit f92e5a204d

@ -13,47 +13,63 @@
# 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 os
import time
class log():
"""Класс для записи в лог"""
# Директория хранения логов
logDir = "/var/log/calculate"
def __init__(self,fileName, addDataTime=True):
self.logFile = os.path.join(self.logDir,fileName)
if not os.path.exists(self.logDir):
os.makedirs(self.logDir)
self.addDataTime = addDataTime
def addLog(self, textLog):
"""Добавляет текст в лог файл"""
if not os.path.exists(self.logFile):
import logging
import logging.handlers
class log:
def __init__(self, programName,
level=logging.DEBUG,
formatter=logging.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 = formatter
self.filename = filename
self.maxBytes=maxBytes
self.backupCount=backupCount
def addHandler(self):
"""Добавление обработчика"""
if not self.logger.handlers:
try:
fd = os.open(self.logFile, os.O_CREAT,0600)
os.close(fd)
except:
print "Error creating file %s"%self.logFile
handler = logging.handlers.RotatingFileHandler(self.filename,
maxBytes=self.maxBytes,
backupCount=self.backupCount)
except Exception, e:
print "logging - ",self.programName,"-",e
return False
textWrite = textLog
if not textLog[-1:] == "\n" :
textWrite = "%s\n"%textLog
if self.addDataTime:
textWrite = "%s %s"%(time.strftime("%d/%m/%Y %H:%M:%S",\
time.localtime()),textWrite)
try:
FD = open (self.logFile, "a")
FD.write(textWrite)
FD.close()
except:
print "Error writing to file %s"%self.logFile
return False
handler.setLevel(self.level)
handler.setFormatter(self.formatter)
self.logger.addHandler(handler)
return True
def writeError(self, textLog):
"""Добавляет сообщение об ошибке в log"""
return self.addLog("ERROR: %s" %textLog)
def writeSuccess(self, textLog):
"""Добавляет сообщение об успехе в log"""
return self.addLog("SUCCESS: %s" %textLog)
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)

@ -201,7 +201,7 @@ class color_print(object):
), offsetL, printBR)
def printERROR(self, string, offsetL=0, printBR=True):
"""Вывод на печать предупреждения"""
"""Вывод на печать ошибки"""
self.printLine((('redBr',' * '),
('',string),
),

Loading…
Cancel
Save