python 中根据python版本(2或3)定义函数
示意代码如下:
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 | #_*_coding:UTF-8_*_ import time import socket import os import sys if sys.version_info.major = = 2 : reload (sys) sys.setdefaultencoding( 'utf8' ) class LogLevel( object ): debug = 'DEBUG' info = 'INFO' warning = 'WARN' error = 'ERROR' fatal = 'FATAL' class Log4P( object ): def __init__( self , * args_arr, * * args_dict): self .module_name = "unknown" self .task_id = "unknown" if "module_name" in args_dict: self .module_name = args_dict[ "module_name" ] if "task_id" in args_dict: self .task_id = str (args_dict[ "task_id" ]) self .host_name = socket.gethostname() def debug( self , * message): return self .log( * message, level = LogLevel.debug) def info( self , * message): return self .log( * message, level = LogLevel.info) def warn( self , * message): return self .log( * message, level = LogLevel.warning) def error( self , * message): return self .log( * message, level = LogLevel.error) def fatal( self , * message): return self .log( * message, level = LogLevel.fatal) def static( self , case): if case = = 1 : info = "run success" elif case = = 2 : info = "run failed" elif case = = 3 : info = "no master" elif case = = 4 : info = "error master" elif case = = 5 : info = "run fail before switch master" else : info = "unknown error" return self .info(info) if sys.version_info.major = = 2 : def log( self , message, level = LogLevel.info): curr_time = time.localtime(time.time()) log_context = format ( '[%d-%02d-%02d %02d:%02d:%02d][%s][%s][%s-%s]' \ % (curr_time.tm_year, curr_time.tm_mon, curr_time.tm_mday, curr_time.tm_hour, curr_time.tm_min, curr_time.tm_sec, str (level), self .host_name, self .module_name, self .task_id)) print (log_context, message, os.linesep) else : def log( self , * message, level = LogLevel.info): curr_time = time.localtime(time.time()) log_context = format ( '[%d-%02d-%02d %02d:%02d:%02d][%s][%s][%s-%s]' \ % (curr_time.tm_year, curr_time.tm_mon, curr_time.tm_mday, curr_time.tm_hour, curr_time.tm_min, curr_time.tm_sec, str (level), self .host_name, self .module_name, self .task_id)) print (log_context, * message, os.linesep) if __name__ = = "__main__" : logger = Log4P(module_name = "dga" , task_id = "dga_id" ) logger.log( "hello world" ) logger.log( "hello world" , "this is a test" ) a = 100 logger.log( "hello world" , "var:" , a) |
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 理解Rust引用及其生命周期标识(上)
· 浏览器原生「磁吸」效果!Anchor Positioning 锚点定位神器解析
· 没有源码,如何修改代码逻辑?
· 全程不用写代码,我用AI程序员写了一个飞机大战
· MongoDB 8.0这个新功能碉堡了,比商业数据库还牛
· 记一次.NET内存居高不下排查解决与启示
· 白话解读 Dapr 1.15:你的「微服务管家」又秀新绝活了
· DeepSeek 开源周回顾「GitHub 热点速览」