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
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
#注意跨平台性
#os.path.join 用来拼接绝对路径 如果有2个头 就是C D的话,会取第二个
import os,sys
BaseDir=os.path.join('C:\\','a','b','c','d.txt')
print(BaseDir)#C:\\a\b\c\d.txt #如果有2个头 就是C D的话,会取第二个
BaseDir2=os.path.join('C:\\','a','b','D:\\','d.txt')
print(BaseDir2) BaseDir3=os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
print(BaseDir3)
#拼出access.log的路径
LOG_PATH=os.path.join(BaseDir3,'log','access.log')
print(LOG_PATH)
DB_PATH=os.path.join(BaseDir3,'db','user')
print(DB_PATH)
LIB_PATH=os.path.join(BaseDir3,'lib','common.py')
print(LIB_PATH) # 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s' # log配置字典
LOGGING_DIC = {
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
'id_simple' : {
'format' : id_simple_format
},
},
'filters': {},
'handlers': {
#打印到终端的日志
'console': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'default': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': LOG_PATH, # 日志文件
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
}, },
'loggers': {
'': {
'handlers': ['default', 'console'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': False, # 向上(更高level的logger)传递
},
},
}
common.py
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
from conf import setting
import logging.config
# def log(msg):
# with open(setting.LOG_PATH,'a',encoding='utf-8') as f:
# f.write('%s\n'%msg) def logger_handle(log_name):
logging.config.dictConfig(setting.LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(log_name) # 生成一个log实例
return logger
start.py
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
""" import os,sys
print(os.path.abspath(__file__)) #打印当前文件的绝对路径 BaseDir=os.path.dirname(os.path.abspath(__file__))#取到star的目录bin
#print(BaseDir)
BaseDir2=os.path.dirname(os.path.dirname(os.path.abspath(__file__))) #取到bin的目录ATM
#print(BaseDir2) #取到了ATM sys.path.append(BaseDir2) #添加到环境变量
from core import src
if __name__=='__main__':
src.run()
src.py
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
"""
from lib import common
def transfure():
print('转账')
msg='陈凯给周琪转账中....'
logger = common.logger_handle('转账')
logger.info(msg) def pay():
print('支付') def shopping_cart():
print('购物车') def run():
msg=""" 1 转账
2 支付
3 购物车 """
while True:
print(msg)
user_choice=input('choice:>>').strip()
if not user_choice:continue
if user_choice=='':
transfure()
elif user_choice=='':
pay()
elif user_choice=='':
shopping_cart()
================================================logging end============================================================
下面内容与实际使用无关,只是做个了解
日志模块分析代码
"""
Description:
Author:Nod
Date:
Record:
#---------------------------------v1-----------------------------------#
""" #日志级别对应不同的数字
#介绍
# import logging
# logging.basicConfig(
# # filename='access.log',
# #日志名 日志级别 日志模块 日志信息
# format='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
# datefmt='%Y-%m-%d %H:%M:%S %p',
# level=10
# )
# logging.debug('debug is 调试') #10
# logging.info('info is 正常信息') #20
# logging.warning('warning is 警告信息') #30
# logging.error('error is 错误信息') #40
# logging.critical('critical is ') #50
#日志级别设置为30 30以上的会打印 30以下的不会打印 默认的日志级别是30 #日志模块的详细用法
"""
1 logger 产生日志
2 filter 基本不用 忽略
3 handler 接收logger传过来的日志 进行日志格式化
,可以打印到终端,也可以打印到文件 4 formatter 日志格式 logger-->handeler(可以多个)-->formatter 5 为handler绑定日志格式 6 """
# 1 logger 产生日志 import logging logger1=logging.getLogger('访问日志') # 3 handler 接收logger传过来的日志 进行日志格式化 sh=logging.StreamHandler() #打印到终端
fh1=logging.FileHandler('s1.log',encoding='utf-8')
fh2=logging.FileHandler('s2.log',encoding='utf-8') #4 formatter 日志格式
formatter1=logging.Formatter( fmt='%(asctime)s - %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) formatter2=logging.Formatter( fmt='%(asctime)s = %(name)s = %(levelname)s =%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) formatter3=logging.Formatter( fmt='%(asctime)s | %(name)s | %(levelname)s |%(module)s: %(message)s',
datefmt='%Y-%m-%d %H:%M:%S %p', ) # 5 为handler绑定格式 绑定handler与formatter的关系 sh.setFormatter(formatter1)
fh1.setFormatter(formatter2)
fh2.setFormatter(formatter3) #6 为logger绑定handler
logger1.addHandler(sh)
logger1.addHandler(fh1)
logger1.addHandler(fh2)
#7 设置日志级别 logger1可以设置级别 handler也可以设置级别
#logger对象的日志级别应该<=handler对象的日志级别
logger1.setLevel(10) #如果此处设置为50的话 则可以显示1条
sh.setLevel(10)
fh1.setLevel(10)
fh2.setLevel(10) #测试
logger1.debug('测试debug')
logger1.info('测试info')
logger1.warning('测试warning')
logger1.error('测试errror')
logger1.critical('测试critical')
Python日志模块logging&JSON的更多相关文章
- python日志模块logging
python日志模块logging 1. 基础用法 python提供了一个标准的日志接口,就是logging模块.日志级别有DEBUG.INFO.WARNING.ERROR.CRITICAL五种( ...
- Python 日志模块logging
logging模块: logging是一个日志记录模块,可以记录我们日常的操作. logging日志文件写入默认是gbk编码格式的,所以在查看时需要使用gbk的解码方式打开. logging日志等级: ...
- 『无为则无心』Python日志 — 64、Python日志模块logging介绍
目录 1.日志的作用 2.为什么需要写日志 3.Python中的日志处理 (1)logging模块介绍 (2)logging模块的四大组件 (3)logging日志级别 1.日志的作用 从事与软件相关 ...
- 【python】【logging】python日志模块logging常用功能
logging模块:应用程序的灵活事件日志系统,可以打印并自定义日志内容 logging.getLogger 创建一个log对象 >>> log1=logging.getLogger ...
- Python日志模块logging用法
1.日志级别 日志一共分成5个等级,从低到高分别是:DEBUG INFO WARNING ERROR CRITICAL. DEBUG:详细的信息,通常只出现在诊断问题上 INFO:确认一切按预期运行 ...
- python日志模块logging学习
介绍 Python本身带有logging模块,其默认支持直接输出到控制台(屏幕),或者通过配置输出到文件中.同时支持TCP.HTTP.GET/POST.SMTP.Socket等协议,将日志信息发送到网 ...
- Python日志模块logging简介
日志处理是项目的必备功能,配置合理的日志,可以帮助我们了解系统的运行状况.定位位置,辅助数据分析技术,还可以挖掘出一些额外的系统信息. 本文介绍Python内置的日志处理模块logging的常见用法. ...
- Python 日志模块 logging通过配置文件方式使用
vim logger_config.ini[loggers]keys=root,infoLogger,errorlogger [logger_root]level=DEBUGhandlers=info ...
- python日志模块---logging
1.将日志打印到屏幕 import logging logging.debug('This is debug message---by liu-ke') logging.info('This is i ...
随机推荐
- 第9天【btrfs文件系统、压缩工具及for语句、程序包管理】
btrfs文件系统管理与应用(01)_recv halt centos7: mkfs.btrfs命令: -L:指定卷标 -m:元数据 -d:指定数据存储的类型,raid1.5.10.single 实验 ...
- const static extern
http://wenku.baidu.com/link?url=saMJ3WpR_Lili2oflaIK-xK7wkQhtP2I-FdEX6I_XjmNxl7m0Z8SYHJtfqyXYkSmok8h ...
- linux学习--目录切换命令 cd
- serial front_door signment and gps signment
import socketimport serialimport osimport sysimport struct#serial ser_intf = serial.Serial(port='/de ...
- css颜色的五种表示方法
一.最简单.最古老的颜色类型在CSS颜色的关键词,如red blue等. 二.十六进制值,如#0000. 三.RGB: rgb(255,0,0),这是给定的三个参数表示的红色,绿色和蓝色通道的颜色值每 ...
- vuejs的双向绑定实现原理
Vue在初始化的时候,会有两个大步骤: 1.Compile 从root的节点开始编译,根据正则表达式,把特殊的v-*类的标签,全部转换成对应的内存中的object 2.Observe 全部的data, ...
- eureka 服务注册与发现
1.创建父工程来管理依赖包 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http:/ ...
- Java语法基础学习DayTen(集合续)
一.集合 1.Set:存储的元素是无序的.不可重复的 (1)无序性:无序性不等于随机性,无序指的是元素在底层存储的位置是无序的. (2)不可重复性:当向Set中添加相同的元素时,后添加的元素不能添加进 ...
- wire [7:0] regAddr; 理解
首先要指出的是wire[7,0]a和wire[8,1]a这样的表达在verilog中是错误的,应该写成wire[7:0]a和wire[8:1]a wire[7:0]a表示定义了一个wire型数据,该数 ...
- noj装载问题
描述 有两艘船,载重量分别是c1. c2,n个集装箱,重量是wi (i=1…n),且所有集装箱的总重量不超过c1+c2.确定是否有可能将所有集装箱全部装入两艘船. 输入 多个测例,每个测例的输入占 ...