python日志管理

python日志管理

开发过程中日志管理是很重要的,Java中有 log4j插件,具体格式为时间、类型、日志内容,那么python中如何构建这个日志

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


import datetime
import logging
import logging.handlers
import os
# import fileutil

def log(log_message, log_file = 'log.txt', terminator_print = False):
#    if terminator_print:
#        try:
#            print log_message
#        except:
#            print 'An exception occured when print log message.'
    bug_file = file(log_file, 'a')
    date_time = datetime.datetime.now()
    bug_file.write(date_time.strftime('%Y-%m-%d %H:%M:%S') + '\n')
    bug_file.write(log_message + '\n')
    bug_file.close()

def write(message, aim_file):
    aim_file = file(aim_file, 'a')
    aim_file.write(message)
    aim_file.close()

class logger(object):

    def __init__(self, name = 'root', log_level = logging.DEBUG, log_filename = os.path.join('log', 'log.txt'), maxBytes = 1000000, backupCount = 5):
        self.logger = logging.getLogger(name)
        self.logger.setLevel(log_level)

        log_directory = os.sep.join(log_filename.split(os.sep)[:-1])

        if (not os.path.exists(log_directory)) or (not os.path.isdir(log_directory)):
            os.makedirs(log_directory)

        handler = logging.handlers.RotatingFileHandler(log_filename, maxBytes = maxBytes, backupCount = backupCount)
        formatter = logging.Formatter('%(asctime)s %(levelname)s %(filename)s %(lineno)d %(module)s %(funcName)s %(message)s')

        handler.setFormatter(formatter)
        self.logger.addHandler(handler)

    def settings(self, name = 'root', log_level = logging.DEBUG, log_filename = os.path.join('log', 'log.txt'), maxBytes = 1000000, backupCount = 5):
        self.__init__(name, log_level, log_filename, maxBytes, backupCount)

logger = logger()

if __name__ == '__main__':
    logger.logger.critical('This is a critical.')
    logger.logger.debug('This is a debug.')
    logger.logger.info('This is a info.')
    logger.logger.error('This is an error.')
    logger.logger.exception('This is an exception.')
联系我

本人qq群 463175657

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值