首页 > 编程语言 >python: logHelper

python: logHelper

时间:2023-07-17 23:04:48浏览次数:37  
标签:info logging level python handler import logger logHelper

 

# 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 = '%Y%Y%m%d-%H:%M:%S'
        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)

  

标签:info,logging,level,python,handler,import,logger,logHelper
From: https://www.cnblogs.com/geovindu/p/17561511.html

相关文章

  • Python中哈哈哈字符串的简单使用
    1defget_string(string,key):2chars=['。',',','.',',','\\n']3print("oldstr:"+string)4match=re.search(key,string)5ifmatch:6start=match.star......
  • 《python从入门到实践》第二章习题记录
    '''动手试一试请尝试编写一些简短的程序来完成下面的练习,以获得一些使用Python列表的第一手经验。你可能需要为每章的练习创建一个文件夹,以整洁有序的方式存储为完成各章的练习而编写的程序。'''#3-1姓名:将一些朋友的姓名存储在一个列表中,并将其命名为names。依次访问该列表......
  • 《python从入门到实践》第四章习题记录
    #4-1比萨:想出至少三种你喜欢的比萨,将其名称存储在一个列表中,再使用for循环将每种比萨的名称都打印出来。#修改这个for循环,使其打印包含比萨名称的句子,而不仅仅是比萨的名称。对于每种比萨,都显示一行输出,如“Ilikepepperonipizza”。#在程序末尾添加一行代码,它不在for循环......
  • 《python从入门到实践》第五章习题记录
    #在第5章中,你将学习如何使用if语句在不同的条件下采取不同的措施;学习如何将一组较复杂的条件测试组合起来,并在满足特定条件时采取相应的措施。你还将#学习如何在遍历列表时,通过使用if语句对特定元素采取特定的措施。#第5章if语句#5-1#条件测试:编写一系列条件测试;将每......
  • 《python从入门到实践》第一章习题记录
    """第一章第1章起步1-1python.org:浏览Python主页(http://python.org/),寻找你感兴趣的主题。你对Python越熟悉,这个网站对你来说就越有用。1-2输入错误:打开你刚创建的文件hello_world.py,在代码中添加一个输入错误,再运行这个程序。输入错误会引发错误吗?你能理解显示的错误消......
  • Python 运行 shell 命令的一些方法
    哈喽大家好,我是咸鱼我们知道,python在自动化领域中被广泛应用,可以很好地自动化处理一些任务就比如编写Python脚本自动化执行重复性的任务,如文件处理、数据处理、系统管理等需要运行其他程序或者与操作系统交互的任务那么今天我们来看一下在python中如何运行shell命令来与......
  • python中的@classmethod和@staticmethod的作用
    classA(object):bar=1deffunc1(self):print("foo")@classmethoddeffunc2(cls):print("func2")print(cls.bar)cls().func1()A.func2()@classmethod的作用实际时可以在class内部实例化class。作用就是比u输......
  • python
    #不需要定义变量##while循环:#while条件:#xxx#xxx#for循环:#for临时变量in范围容器(可用range,如果是容器的话,就是遍历,如果in10,就是遍历0-10)#for循环的范围是大于等于第一个小于最后一个,也就是inti=0;i<n;i++#输入......
  • python日志调试
    1.日志logging.debug():最低级别,用于小细节,通常用于在诊断问题时,才会关心谢谢消息logging.info():用于记录程序中一般事件的信息,或确认一切工作正常logging.warning():用于表示可能的问题,它不会阻止程序的工作,但将来可能会logging.error():用于记录错误,它导致程序做某事失败logg......
  • python:基础语法(002)
    python的关键字:#打印python都有哪些关键字importkeywordprint(keyword.kwlist) 缩进:缩进快捷键Tab 多行语句:按回车键即可换行,用\反斜杠也可以换行 python的引号:python中可以使用单引号、双引号、三引号#单引号print('你好')#双引号print("你好")#三引......