python实现glog,python log指定输出文件, python log按大小分割文件,python文件重命名os.rename(),python ms级时间戳datetime.now()

1,效果展示

目录结构
log用法
log信息

2,使用说明

2.1,两个日志级别

两个日志级别: ERROR,INFO

2.2,日志输出

M_LOG.log(M_LOG.INFO, "afgadgshsh")
M_LOG.log(M_LOG.ERROR, "afgadgshsh")
M_LOG.info("afgadgshsh")
M_LOG.error("afgadgshsh")

2.3,条件输出

M_LOG.log_if(M_LOG.INFO, tmp==1, "124214332512543")
M_LOG.log_if(M_LOG.ERROR, tmp==1, "124214332512543")
M_LOG.info_if(tmp==1, "124214332512543")
M_LOG.error_if(tmp==1, "124214332512543")

3,实现代码

#!/usr/bin/python
# -*- coding: UTF-8 -*-
import sys, time, os
from datetime import datetime

class M_LOG(object):
    INFO = "I"
    ERROR = "E"

    # 输出重定向到该文件
    out_file = "stderr"
    err_file = "stdout"
    # 写文件开始时间
    out_start_time = str(time.strftime("%Y%m%d_%H:%M:%S", time.localtime()))
    err_start_time = str(time.strftime("%Y%m%d_%H:%M:%S", time.localtime()))
    # 单个文件最大size
    max_file_size = 1024 * 10 #单位:kb * KB * MB
    def __init__(self):
        pass

    # 输出重定向,设置输出文件
    @staticmethod
    def log_base_init(out_file=None, err_file=None):
        if not out_file == None:
            if out_file.rfind("/"):
                path = out_file[:out_file.rfind("/")]
                if not os.path.exists(path):
                    os.makedirs(path, mode=0o777)
            M_LOG.out_file = out_file
            so = open(M_LOG.out_file, "w+")
            # os.dup2(so.fileno(), sys.stdout.fileno())
            sys.stdout = so
            M_LOG.out_start_time = str(time.strftime("%Y%m%d_%H:%M:%S", time.localtime()))
        if not err_file == None:
            if err_file.rfind("/"):
                path = err_file[:err_file.rfind("/")]
                if not os.path.exists(path):
                    os.makedirs(path, mode=0o777)
            M_LOG.err_file = err_file
            se = open(M_LOG.err_file, "w+")
            # os.dup2(se.fileno(), sys.stderr.fileno())
            sys.stderr = se
            M_LOG.err_start_time = str(time.strftime("%Y%m%d_%H:%M:%S", time.localtime()))
    
    # 文件重命名
    @classmethod
    def file_rename(self, file, time):
        path = "./"
        file_name = file
        if file.find("/") >= 0:
            path = file[:file.rfind("/")]
            file_name = file[file.rfind("/")+1:]
        rename = file_name + "-" + time
        os.rename(os.path.join(path, file_name), os.path.join(path, rename))

    # 文件超出设定大小,重命名
    @classmethod
    def file_check(self, file):
        if not file == None:
            if os.path.exists(file):
                size = os.path.getsize(file)
                if size > M_LOG.max_file_size:
                    time = None
                    if file.rfind("out"):
                        time = M_LOG.out_start_time
                    elif file.rfind("err"):
                        time = M_LOG.err_start_time
                    M_LOG.file_rename(file, time)
                    return 0
        return -1

    # 标准错误,写入之前判断文件大小,超出大小,重定向
    @classmethod
    def write_err(self, log_str):
        if M_LOG.file_check(M_LOG.err_file) >= 0:
            M_LOG.log_base_init(err_file=M_LOG.err_file)
        sys.stderr.write(log_str)
        sys.stderr.flush()

    # 标准输出,写入之前判断文件大小,超出大小,重定向
    @classmethod
    def write_out(self, log_str):
        if M_LOG.file_check(M_LOG.out_file) >= 0:
            M_LOG.log_base_init(out_file=M_LOG.out_file)
        sys.stdout.write(log_str)
        sys.stdout.flush()

    # 给信息加上log头
    @staticmethod
    def log(level, message, depth=1):
        file = sys._getframe(depth)
        file_name = str(file.f_code.co_filename)
        file_name = file_name[file_name.rfind("/")+1:] if file_name.rfind("/") >= 0 else file_name
        log_str = "{} {} {} {} {}\n".format(str(level) + str(time.strftime("%m%d", time.localtime())),
                                        str(datetime.now().strftime('%H:%M:%S.%f')[:-3]),
                                        str(os.getpid()), 
                                        file_name + ":" + str(file.f_code.co_name) + ":" + str(file.f_lineno) + str("]  "),
                                        message)
        if level == M_LOG.INFO:
            M_LOG.write_out(log_str)
        elif level == M_LOG.ERROR:
            M_LOG.write_err(log_str)


    @staticmethod
    def log_if(level, active, message):
        if active:
            M_LOG.log(level, message, depth=2)

    @staticmethod
    def info(message, depth=2):
        M_LOG.log(M_LOG.INFO, message, depth)

    @staticmethod
    def error(message, depth=2):
        M_LOG.log(M_LOG.ERROR, message, depth)

    @staticmethod
    def info_if(active, message):
        if active:
            M_LOG.info(message, depth=3)

    @staticmethod
    def error_if(active, message):
        if active:
            M_LOG.error(message, depth=3)

def main():
    stdour = "log/stdout"
    stderr = "log/stderr"
    M_LOG.log_base_init(out_file=stdour, err_file=stderr)

    for i in range(10000):
        M_LOG.info("M_LOG.info: {} -> {}".format(i, "ohfuoehquovhwepiwke[pgokwgowekg[pjv[oqijv[oejvo[qewjvo[wjvioejv[ioejvo"))
        M_LOG.log(M_LOG.INFO, "M_LOG.log: {}".format(i))
        M_LOG.error_if(i%2==0, "M_LOG.error_if i%2==0: {}".format(i))
        M_LOG.log_if(M_LOG.ERROR, i%2!=0, "M_LOG.error_if i%2!=0: {}".format(i))

        time.sleep(1)

if __name__ == "__main__":
    main()      
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值