python: logHelper

该代码定义了一个logHelper类,用于处理Python日志记录。它包括不同级别的日志方法如info,warning,error,debug和critical,并使用logging模块进行配置。类还支持自定义日志格式和文件配置,以及使用sys.stdout和sys.stderr进行日志输出。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

# encoding: utf-8
# 版权所有 2023 涂聚文有限公司
# 许可信息查看: https://docs.python.org/3/library/logging.html
# 描述: https://www.programcreek.com/python/example/136/logging.basicConfig
#       https://github.com/amilstead/python-logging-examples
# Author    : geovindu,Geovin Du 涂聚文.
# IDE       : PyCharm 2023.1 python 311
# Datetime  : 2023/7/17 18:54
# User      : geovindu
# Product   : PyCharm
# Project   : pythonTkinterDemo
# File      : LogHelper.py
# explain   : 学习


import json
import os
import sys
import threading
import logging
import asyncio
import json
import logging
from abc import ABC, abstractmethod
from logging import LogRecord
from typing import Dict, Optional, Sequence
from logging import config as logging_config
import glob
import datetime
from inspect import signature
import inspect
import io
import argparse
import struct
import logging
import socket
import pickle
import time


'''
from attrs import define
from slack_sdk.models.blocks import Block, DividerBlock, HeaderBlock, SectionBlock
from slack_sdk.models.blocks.basic_components import MarkdownTextObject, PlainTextObject
from slack_sdk.webhook.async_client import AsyncWebhookClient
'''

class logHelper(object):

    global here #= os.path.abspath(os.path.dirname(__file__))
    global LOGGING_CONFIG # = os.path.abspath(os.path.join(here, 'test.log'))

    def __init__(self):
        here = os.path.abspath(os.path.dirname(__file__))
        LOGGING_CONFIG = os.path.abspath(os.path.join(here, 'test.log'))
        logging.basicConfig(filename='geovindu.log', filemode='w', format='%(name)s - %(levelname)s - %(message)s')


    def getLogInfo(self,info:str):
        """
         程序运行的关键步骤信息
        :param info:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.info(info)
        app_logger = logging.getLogger('app')
        app_logger.info(info)

    def getLogWarning(self, info: str):
        """
         警告信息
        :param info:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.warning(info)


    def getLogError(self, info: str):
        """
        程序错误,某个功能无法执行
        :param info:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.error(info)


    def getLogDebug(self, info: str):
        """
         提供详细
        :param info:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.debug(info)
        logger.critical(info)

    def getLoCritical(self, info: str):
        """
        Critical 严重错误,可能整个程序无法执行
        :param info:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.critical(info)


    def get_logger(self,filename):
        """

        :param filename
        :return:
        """
        logging.basicConfig(filename=f"{filename}", filemode='a', format="%(message)s")
        logging.warning(f"[{datetime.datetime.now()}] {'=' * 10}")

        def log(message, error=True):
            func = inspect.currentframe().f_back.f_code
            final_msg = "(%s:%i) %s" % (
                func.co_name,
                func.co_firstlineno,
                message
            )
            if error:
                logging.warning(final_msg)
                print(f"[ERROR] {final_msg}")
            else:
                print(final_msg)

        return log


    def getMessage(self):
        """

        :return:
        """

        logging_config.fileConfig(LOGGING_CONFIG)
        formatter = logging.Formatter('%(levelname)s - %(message)s')
        formatter.datefmt = '%A %b %d, %Y'
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)
        logger = logging.getLogger(__name__)
        logger.addHandler(handler)
        logger.setLevel(logging.INFO)

        logger.info('My current format!')

        formatter = logging.Formatter('[%(asctime)s] %(levelname)s - %(message)s')
        handler.setFormatter(formatter)
        logger.info('My format changed!')

    def basic_levels(self):
        """

        :return:
        """

        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.info('{:-^100}'.format(' BASIC LEVELS '))
        # Examples of logging API usage
        logger.debug('This is a simple DEBUG level message.')
        logger.info('This is a simple INFO level message.')
        logger.warning('This is a simple WARNING level message.')
        logger.warn('This is a simple WARN level message.')
        logger.error('This is a simple ERROR level message.')
        logger.exception('This is an ERROR level message with exc_info.')

        try:
            raise Exception('Random exception!')
        except Exception:
            logger.exception('This is an ERROR level message with a stack trace!')

        logger.critical('This is a simple CRITICAL level message')
        logger.fatal('This is a simple FATAL level message')

        # AND you can use the generic log method (but please don't).
        logger.log(logging.DEBUG, 'This is the same as logging.debug')
        logger.log(logging.INFO, 'This is the same as logging.info')
        logger.log(logging.WARNING, 'This is the same as logging.warning')
        logger.log(logging.WARN, 'This is the same as logging.warn')
        logger.log(logging.ERROR, 'This is the same as logging.exception', exc_info=True)
        logger.log(logging.CRITICAL, 'This is the same as logging.critical')
        logger.log(logging.FATAL, 'This is the same as logging.fatal')

    def message_arguments(self):
        """

        :return:
        """

        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.info('{:-^100}'.format(' MESSAGE ARGUMENTS '))
        logger.info(
            'What %s is it? %.5f',
            'time', time.time()
        )

        logger.info(
            'Now with %(my_arg)s arguments!',
            {'my_arg': 'named'}
        )



    def stderr_logger(self):

        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger('stderr_logger')
        logger.setLevel(logging.INFO)
        handler = logging.StreamHandler(stream=sys.stderr)  # also the default
        logger.addHandler(handler)

        logger.info('This is through sys.stderr!')

    def stdout_logger(self):

        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger('stdout_logger')
        logger.setLevel(logging.INFO)
        handler = logging.StreamHandler(stream=sys.stdout)  # also the default
        logger.addHandler(handler)

        logger.info('This is through sys.stdout!')

    def bytestream_logger(self):

        # A file "stream"
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger('bytestream_logger')
        logger.setLevel(logging.INFO)
        with io.BytesIO() as _buffer:
            handler = logging.StreamHandler(stream=_buffer)
            logger.addHandler(handler)
            logger.info('This is being written to an I/O buffer!')
            print(_buffer.getvalue())

    def make_handler(self,with_level=None):
        """


        :param with_level:
        :return:
        """

        hdlr_level = with_level if with_level is not None else "no level"
        format_str = 'hdlr_level: {}'.format(hdlr_level)
        format_str += ' - %(levelname)s - %(message)s'
        formatter = logging.Formatter(format_str)

        # make a handler with a level
        handler = logging.StreamHandler()
        handler.setFormatter(formatter)

        if with_level is not None:
            handler.setLevel(with_level)

        return handler

    def mainHandler(self):
        """

        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger(__name__)
        logger.setLevel(logging.DEBUG)

        # make a handler with a level
        handler_with_level = self.make_handler(with_level=logging.ERROR)

        # and without
        handler_without = self.make_handler()

        logger.addHandler(handler_with_level)
        logger.addHandler(handler_without)
        logger.info('My level my differ from my handler levels!')
        logger.error('This should have only been handled by one handler!')




    def serve(self,_socket):
        """

        :param _socket:
        :return:
        """
        logging_config.fileConfig(LOGGING_CONFIG)
        logger = logging.getLogger('server')
        while True:
            conn, address = _socket.accept()
            # Shamelessly copied from logging.config
            chunk = conn.recv(4)
            slen = struct.unpack(">L", chunk)[0]
            chunk = conn.recv(slen)
            while len(chunk) < slen:
                chunk = chunk + conn.recv(slen - len(chunk))

            # Message is roughly JSON:
            try:
                message = json.loads(chunk)
            except ValueError:
                continue

            level = message['level']
            msg = message['msg']
            args = pickle.loads(message['args'])
            logger.log(level, msg, *args)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值