zoukankan      html  css  js  c++  java
  • Python日志模块logging&JSON

    日志模块的用法

    json部分

    先开一段测试代码:注意  str可以直接处理字典   eval可以直接将字符串转成字典的形式

    dic={'key1':'value1','key2':'value2'}

    data=str(dic)#字典直接转成字符串

    print(type(data),data)

    #
    # with open('db.txt','w',encoding='utf-8') as f:
    # f.write(str(dic))
    #

    with open('db.txt','r',encoding='utf-8') as f:
    data=f.read()
    print(data,type(data))
    dic2=eval(data)
    print(dic2,type(dic2))

    原先目录结构为:

    =======================================================logging begin===============================================================

    settings.py

     1 """
     2 Description:
     3 Author:Nod
     4 Date:
     5 Record:
     6 #---------------------------------v1-----------------------------------#
     7 """
     8 #注意跨平台性
     9 #os.path.join   用来拼接绝对路径   如果有2个头 就是C  D的话,会取第二个
    10 import os,sys
    11 BaseDir=os.path.join('C:\','a','b','c','d.txt')
    12 print(BaseDir)#C:\acd.txt
    13 
    14 #如果有2个头 就是C  D的话,会取第二个
    15 BaseDir2=os.path.join('C:\','a','b','D:\','d.txt')
    16 print(BaseDir2)
    17 
    18 
    19 BaseDir3=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
    20 print(BaseDir3)
    21 #拼出access.log的路径
    22 LOG_PATH=os.path.join(BaseDir3,'log','access.log')
    23 print(LOG_PATH)
    24 DB_PATH=os.path.join(BaseDir3,'db','user')
    25 print(DB_PATH)
    26 LIB_PATH=os.path.join(BaseDir3,'lib','common.py')
    27 print(LIB_PATH)
    28 
    29 
    30 
    31 
    32 # 定义三种日志输出格式 开始
    33 standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' 
    34                   '[%(levelname)s][%(message)s]'
    35 
    36 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s'
    37 
    38 id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
    39 
    40 # log配置字典
    41 LOGGING_DIC = {
    42     'version': 1,
    43     'disable_existing_loggers': False,
    44     'formatters': {
    45         'standard': {
    46             'format': standard_format
    47         },
    48         'simple': {
    49             'format': simple_format
    50         },
    51         'id_simple' : {
    52             'format' : id_simple_format
    53         },
    54     },
    55     'filters': {},
    56     'handlers': {
    57         #打印到终端的日志
    58         'console': {
    59             'level': 'DEBUG',
    60             'class': 'logging.StreamHandler',  # 打印到屏幕
    61             'formatter': 'simple'
    62         },
    63         #打印到文件的日志,收集info及以上的日志
    64         'default': {
    65             'level': 'DEBUG',
    66             'class': 'logging.handlers.RotatingFileHandler',  # 保存到文件
    67             'formatter': 'standard',
    68             'filename': LOG_PATH,  # 日志文件
    69             'maxBytes': 1024*1024*5,  # 日志大小 5M
    70             'backupCount': 5,
    71             'encoding': 'utf-8',  # 日志文件的编码,再也不用担心中文log乱码了
    72         },
    73 
    74     },
    75     'loggers': {
    76         '': {
    77             'handlers': ['default', 'console'],  # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
    78             'level': 'DEBUG',
    79             'propagate': False,  # 向上(更高level的logger)传递
    80         },
    81     },
    82 }
    View Code

    common.py

     1 """
     2 Description:
     3 Author:Nod
     4 Date:
     5 Record:
     6 #---------------------------------v1-----------------------------------#
     7 """
     8 from conf import setting
     9 import logging.config
    10 # def log(msg):
    11 #     with open(setting.LOG_PATH,'a',encoding='utf-8') as f:
    12 #         f.write('%s
    '%msg)
    13 
    14 def logger_handle(log_name):
    15     logging.config.dictConfig(setting.LOGGING_DIC)  # 导入上面定义的logging配置
    16     logger = logging.getLogger(log_name)  # 生成一个log实例
    17     return logger
    View Code

    start.py

     1 """
     2 Description:
     3 Author:Nod
     4 Date:
     5 Record:
     6 #---------------------------------v1-----------------------------------#
     7 """
     8 
     9 import os,sys
    10 print(os.path.abspath(__file__))  #打印当前文件的绝对路径
    11 
    12 
    13 BaseDir=os.path.dirname(os.path.abspath(__file__))#取到star的目录bin
    14 #print(BaseDir)
    15 BaseDir2=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #取到bin的目录ATM
    16 #print(BaseDir2)  #取到了ATM
    17 
    18 sys.path.append(BaseDir2)   #添加到环境变量
    19 from core import src
    20 if __name__=='__main__':
    21     src.run()
    View Code

    src.py

     1 """
     2 Description:
     3 Author:Nod
     4 Date:
     5 Record:
     6 #---------------------------------v1-----------------------------------#
     7 """
     8 from lib import common
     9 def transfure():
    10     print('转账')
    11     msg='陈凯给周琪转账中....'
    12     logger = common.logger_handle('转账')
    13     logger.info(msg)
    14 
    15 
    16 def pay():
    17     print('支付')
    18 
    19 
    20 def shopping_cart():
    21     print('购物车')
    22 
    23 def run():
    24     msg="""
    25     
    26     1 转账
    27     2 支付
    28     3 购物车
    29     
    30     """
    31     while True:
    32         print(msg)
    33         user_choice=input('choice:>>').strip()
    34         if not user_choice:continue
    35         if user_choice=='1':
    36             transfure()
    37         elif user_choice=='2':
    38             pay()
    39         elif user_choice=='3':
    40             shopping_cart()
    View Code

    ================================================logging end============================================================

    下面内容与实际使用无关,只是做个了解

    日志模块分析代码

      1 """
      2 Description:
      3 Author:Nod
      4 Date:
      5 Record:
      6 #---------------------------------v1-----------------------------------#
      7 """
      8 
      9 #日志级别对应不同的数字
     10 #介绍
     11 # import logging
     12 # logging.basicConfig(
     13 # # filename='access.log',
     14 #     #日志名    日志级别   日志模块   日志信息
     15 #                     format='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
     16 #                     datefmt='%Y-%m-%d %H:%M:%S %p',
     17 #                     level=10
     18 # )
     19 # logging.debug('debug is 调试')  #10
     20 # logging.info('info is 正常信息') #20
     21 # logging.warning('warning is 警告信息') #30
     22 # logging.error('error is 错误信息')  #40
     23 # logging.critical('critical is ')  #50
     24 #日志级别设置为30  30以上的会打印  30以下的不会打印   默认的日志级别是30
     25 
     26 
     27 
     28 #日志模块的详细用法
     29 """
     30 1  logger  产生日志
     31 2   filter  基本不用   忽略
     32 3   handler   接收logger传过来的日志   进行日志格式化
     33 ,可以打印到终端,也可以打印到文件
     34 
     35 4  formatter   日志格式
     36 
     37 logger-->handeler(可以多个)-->formatter
     38 
     39 5 为handler绑定日志格式
     40 
     41 6 
     42 
     43 """
     44 #   1  logger  产生日志
     45 
     46 import logging
     47 
     48 logger1=logging.getLogger('访问日志')
     49 
     50 
     51 
     52 #    3  handler   接收logger传过来的日志   进行日志格式化
     53 
     54 sh=logging.StreamHandler()   #打印到终端
     55 fh1=logging.FileHandler('s1.log',encoding='utf-8')
     56 fh2=logging.FileHandler('s2.log',encoding='utf-8')
     57 
     58 #4  formatter   日志格式
     59 formatter1=logging.Formatter(
     60 
     61 fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s:  %(message)s',
     62 datefmt='%Y-%m-%d %H:%M:%S %p',
     63 
     64 )
     65 
     66 formatter2=logging.Formatter(
     67 
     68 fmt='%(asctime)s = %(name)s = %(levelname)s =%(module)s:  %(message)s',
     69 datefmt='%Y-%m-%d %H:%M:%S %p',
     70 
     71 )
     72 
     73 
     74 formatter3=logging.Formatter(
     75 
     76 fmt='%(asctime)s | %(name)s | %(levelname)s |%(module)s:  %(message)s',
     77 datefmt='%Y-%m-%d %H:%M:%S %p',
     78 
     79 )
     80 
     81 # 5  为handler绑定格式  绑定handler与formatter的关系
     82 
     83 sh.setFormatter(formatter1)
     84 fh1.setFormatter(formatter2)
     85 fh2.setFormatter(formatter3)
     86 
     87 #6  为logger绑定handler
     88 logger1.addHandler(sh)
     89 logger1.addHandler(fh1)
     90 logger1.addHandler(fh2)
     91 #7  设置日志级别  logger1可以设置级别  handler也可以设置级别
     92 #logger对象的日志级别应该<=handler对象的日志级别
     93 logger1.setLevel(10)   #如果此处设置为50的话  则可以显示1条
     94 sh.setLevel(10)
     95 fh1.setLevel(10)
     96 fh2.setLevel(10)
     97 
     98 
     99 #测试
    100 logger1.debug('测试debug')
    101 logger1.info('测试info')
    102 logger1.warning('测试warning')
    103 logger1.error('测试errror')
    104 logger1.critical('测试critical')
    View Code
  • 相关阅读:
    智能移动机器人背后蕴含的技术——激光雷达
    Kalman Filters
    Fiddler抓HttpClient的包
    VSCode开发WebApi EFCore的坑
    WPF之小米Logo超圆角的实现
    windows react打包发布
    jenkins in docker踩坑汇总
    Using ML.NET in Jupyter notebooks 在jupyter notebook中使用ML.NET ——No design time or full build available
    【Linux知识点】CentOS7 更换阿里云源
    【Golang 报错】exec gcc executable file not found in %PATH%
  • 原文地址:https://www.cnblogs.com/nodchen/p/8798456.html
Copyright © 2011-2022 走看看