python: logHelper
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 | # 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) |
哲学管理(学)人生, 文学艺术生活, 自动(计算机学)物理(学)工作, 生物(学)化学逆境, 历史(学)测绘(学)时间, 经济(学)数学金钱(理财), 心理(学)医学情绪, 诗词美容情感, 美学建筑(学)家园, 解构建构(分析)整合学习, 智商情商(IQ、EQ)运筹(学)生存.---Geovin Du(涂聚文)
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 25岁的心里话
· 闲置电脑爆改个人服务器(超详细) #公网映射 #Vmware虚拟网络编辑器
· 基于 Docker 搭建 FRP 内网穿透开源项目(很简单哒)
· 零经验选手,Compose 一天开发一款小游戏!
· 一起来玩mcp_server_sqlite,让AI帮你做增删改查!!
2018-07-17 PHP7.27: connect mysql 5.7 using new mysqli_connect
2014-07-17 sql:日期操作注意的,如果以字符串转日期时的函数,因为数据量大,会出问题
2013-07-17 Csharp: Detect Mobile Browsers