import os
import logging.config #不能只导入logging BASE_DIR=os.path.dirname(os.path.dirname(__file__))
# DB_PATH=os.path.join(BASE_DIR,'db')
# DB_PATH=r'%s\db' %BASE_DIR # 定义日志文件的路径
LOG_PATH=os.path.join(BASE_DIR,'log','access.log')
# LOG_PATH=r'%s\log\access.log' %BASE_DIR
# BOSS_LOG_PATH=r'%s\log\boss.log' %BASE_DIR # 定义三种日志输出格式 开始
standard_format = '[%(asctime)s][%(threadName)s:%(thread)d][task_id:%(name)s][%(filename)s:%(lineno)d]' \
'[%(levelname)s][%(message)s]' #其中name为getlogger指定的名字 simple_format = '[%(levelname)s][%(asctime)s][%(filename)s:%(lineno)d]%(message)s' id_simple_format = '[%(levelname)s][%(asctime)s] %(message)s'
# 定义日志输出格式 结束 logfile_dir = os.path.dirname(os.path.abspath(__file__)) # log文件的目录
logfile_name = 'all2.log' # log文件名 # 如果不存在定义的日志目录就创建一个
if not os.path.isdir(logfile_dir):
os.mkdir(logfile_dir) # log文件的全路径
logfile_path = os.path.join(logfile_dir, logfile_name) # log配置字典
LOGGING_DIC = {
'version': 1,
# 禁用已经存在的logger实例
'disable_existing_loggers': False,
# 定义日志 格式化的 工具
'formatters': {
'standard': {
'format': standard_format
},
'simple': {
'format': simple_format
},
'id_simple': {
'format': id_simple_format
},
},
# 过滤
'filters': {}, # jango此处不同
'handlers': {
#打印到终端的日志
'stream': {
'level': 'DEBUG',
'class': 'logging.StreamHandler', # 打印到屏幕
'formatter': 'simple'
},
#打印到文件的日志,收集info及以上的日志
'access': {
'level': 'DEBUG',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'standard',
'filename': logfile_path, # 日志文件路径
'maxBytes': 1024*1024*5, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
#打印到文件的日志,收集error及以上的日志
'boss': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件
'formatter': 'id_simple',
'filename': BOSS_LOG_PATH, # 日志文件
# 'maxBytes': 1024*1024*5, # 日志大小 5M
'maxBytes': 300, # 日志大小 5M
'backupCount': 5,
'encoding': 'utf-8', # 日志文件的编码,再也不用担心中文log乱码了
},
},
# logger实例
'loggers': {
# 默认的logger应用如下配置
'': {
'handlers': ['stream', 'access','boss'], # 这里把上面定义的两个handler都加上,即log数据既写入文件又打印到屏幕
'level': 'DEBUG',
'propagate': True, # 向上(更高level的logger)传递
},
# logging.getLogger(__name__)拿到的logger配置
# 这样我们再取logger对象时logging.getLogger(__name__),不同的文件__name__不同,这保证了打印日志时标识信息不同,
# 但是拿着该名字去loggers里找key名时却发现找不到,于是默认使用key=''的配置
},
} def load_my_logging_cfg():
logging.config.dictConfig(LOGGING_DIC) # 导入上面定义的logging配置
logger = logging.getLogger(__name__) # 生成一个log实例
logger.info('It works!') # 记录该文件的运行状态 if __name__ == '__main__':
load_my_logging_cfg() #从common.py引用,要传入name,且有返回log实例
# import logging.config
# import logging
# from conf import setting # def get_logger(name):
#logging.config.dictConfig(setting.LOGGING_DIC) # 导入上面定义的logging配置
#l1=logging.getLogger(name)
#return l1 #src.py
# logger1 = common.get_logger('查看余额')
# logger1.debug( dic_user_check['money'] )

Django版log日志:

settings.py:

# 日志配置
BASE_LOG_DIR = os.path.join(BASE_DIR, "log")
LOGGING = {
'version': 1,
# 禁用已经存在的logger实例
'disable_existing_loggers': False,
# 定义日志 格式化的 工具
'formatters': {
'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'
},
'collect': {
'format': '%(message)s'
}
},
# 过滤
'filters': {
'require_debug_true': {
'()': 'django.utils.log.RequireDebugTrue',
},
},
# 日志处理器
'handlers': {
'console': {
'level': 'DEBUG',
'filters': ['require_debug_true'], # 只有在Django debug为True时才在屏幕打印日志
'class': 'logging.StreamHandler',
'formatter': 'simple'
}, 'default': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "info.log"), # 日志文件
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 3,
'formatter': 'standard',
'encoding': 'utf-8',
}, 'error': {
'level': 'ERROR',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "err.log"), # 日志文件
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 5,
'formatter': 'standard',
'encoding': 'utf-8',
}, 'collect': {
'level': 'INFO',
'class': 'logging.handlers.RotatingFileHandler', # 保存到文件,自动切
'filename': os.path.join(BASE_LOG_DIR, "xxx_collect.log"),
'maxBytes': 1024 * 1024 * 50, # 日志大小 50M
'backupCount': 5,
'formatter': 'collect',
'encoding': "utf-8"
}
},
# logger实例
'loggers': {
# 默认的logger应用如下配置
'': {
'handlers': ['default', 'console', 'error'], # 上线之后可以把'console'移除
'level': 'DEBUG',
'propagate': True,
},
# 名为 'collect'的logger还单独处理
'collect': {
'handlers': ['console', 'collect'],
'level': 'INFO',
}
},
}

日志字典配置

views.py:

import logging

# 生成一个以当前文件名命名的logger实例
logger = logging.getLogger(__name__)
# 生成一个名为collect的logger实例
collect_logger = logging.getLogger("collect") logger.info("xxx")
collect_logger.info("xxx")

在视图函数中使用

python 之 logger日志 字典配置文件的更多相关文章

  1. python logger日志通用配置文件

    阅读须知⚠️ 1.示例代码可直接放在项目py文件中即可使用 2.project_name,logfile_name变量需根据你的项目进行修改 3.日志输出格式format选择(可根据你的需要替换或修改 ...

  2. python接口自动化(四十)- logger 日志 - 下(超详解)

    简介 按照上一篇的计划,这一篇给小伙伴们讲解一下:(1)多模块使用logging,(2)通过文件配置logging模块,(3)自己封装一个日志(logging)类.可能有的小伙伴在这里会有个疑问一个l ...

  3. python logger 日志模块

    logger 日志 """logging配置""" import osimport logging.config # 定义三种日志输出格式 ...

  4. python之配置日志的三种方式

    以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文件,然后使用fileCo ...

  5. Python之配置日志的几种方式(logging模块)

    原文:https://blog.csdn.net/WZ18810463869/article/details/81147167 作为开发者,我们可以通过以下3种方式来配置logging: 1)使用Py ...

  6. 【转】python之配置日志的几种方式

    [转]python之配置日志的几种方式 作为开发者,我们可以通过以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用 ...

  7. python之配置日志的几种方式

    作为开发者,我们可以通过以下3种方式来配置logging: 1)使用Python代码显式的创建loggers, handlers和formatters并分别调用它们的配置函数: 2)创建一个日志配置文 ...

  8. 【转】Python之向日志输出中添加上下文信息

    [转]Python之向日志输出中添加上下文信息 除了传递给日志记录函数的参数(如msg)外,有时候我们还想在日志输出中包含一些额外的上下文信息.比如,在一个网络应用中,可能希望在日志中记录客户端的特定 ...

  9. Python开发之日志记录模块:logging

    1 引言 最近在开发一个应用软件,为方便调试和后期维护,在代码中添加了日志,用的是Python内置的logging模块,看了许多博主的博文,颇有所得.不得不说,有许多博主大牛总结得确实很好.似乎我再写 ...

随机推荐

  1. ubuntu系统五笔输入法安装

    转载:https://jingyan.baidu.com/article/454316ab67d702f7a7c03a1a.html Ubuntu 16.04 在安装时选择中文安装,安装过程中将自动安 ...

  2. #C++初学记录(acm试题#预处理)

    C - Lucky 7 in the Pocket BaoBao loves number 7 but hates number 4, so he refers to an integer as a ...

  3. appium 多线程还是多进程(转)

    https://www.cnblogs.com/zouzou-busy/p/11440175.html 在前面我们都是使用一个机器进行测试,在做app自动化的时候,我们要测不同的机型,也就是兼容性测试 ...

  4. 10个超漂亮的CSS 3D特效

    10个超漂亮的CSS 3D特效 一.总结 一句话总结: 后面有空得好好练一练,也可以作为录课素材 二.10个超漂亮的CSS 3D特效 转自或参考:10个超漂亮的CSS 3D特效https://blog ...

  5. chrome 等浏览器不支持本地ajax请求,的问题

    XMLHttpRequest cannot load file:///D:/WWW/angularlx/ui-router-test/template/content.html. Cross orig ...

  6. 获取div下的input type为file的所有对象

    var files = $(".profile-content").find("input[type='file']"); files.each(functio ...

  7. 20161209pod search 'fmdb'提示[!] Unable to find a pod with name, author, summary, or description matching `fmdb`

    从SVN上更新工程之后运行工程提示错误: The sandbox is not in sync with the Podfile.lock. Run 'pod install' or update y ...

  8. 微信jaapi签名

    public WeiXinJsSignature(string weixinUrl) { //string url = ConfigurationManager.AppSettings["U ...

  9. Ionic4.x ion-refresher 下拉更新

    官方文档:https://ionicframework.com/docs/api/refresher <ion-header> <ion-toolbar> <ion-ti ...

  10. std::shared_mutex和std::mutex的性能对比(banchmark)

    原文作者:@玄冬Wong 转载请注明原文出处:http://aigo.iteye.com/blog/2296462 key world: std::shared_mutex.std::mutex.pe ...